aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/lib/upload.ts
blob: 06f007f78d55d75ac98236d7b4dd83e7125b6f3e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import ReactNativeBlobUtil from "react-native-blob-util";
import { useMutation } from "@tanstack/react-query";

import { BookmarkTypes, ZBookmark } from "@karakeep/shared/types/bookmarks";
import {
  zUploadErrorSchema,
  zUploadResponseSchema,
} from "@karakeep/shared/types/uploads";

import type { Settings } from "./settings";
import { api } from "./trpc";
import { buildApiHeaders } from "./utils";

export function useUploadAsset(
  settings: Settings,
  options: {
    onSuccess?: (bookmark: ZBookmark & { alreadyExists: boolean }) => void;
    onError?: (e: string) => void;
  },
) {
  const invalidateAllBookmarks =
    api.useUtils().bookmarks.getBookmarks.invalidate;

  const { mutate: createBookmark, isPending: isCreatingBookmark } =
    api.bookmarks.createBookmark.useMutation({
      onSuccess: (d) => {
        invalidateAllBookmarks();
        if (options.onSuccess) {
          options.onSuccess(d);
        }
      },
      onError: (e) => {
        if (options.onError) {
          options.onError(e.message);
        }
      },
    });

  const { mutate: uploadAsset, isPending: isUploading } = useMutation({
    mutationFn: async (file: { type: string; name: string; uri: string }) => {
      // There's a bug in the native FormData implementation (https://github.com/facebook/react-native/issues/44737)
      // that will only get fixed in react native 0.77. Using the BlobUtil implementation for now.
      const resp = await ReactNativeBlobUtil.fetch(
        "POST",
        `${settings.address}/api/assets`,
        {
          ...buildApiHeaders(settings.apiKey, settings.customHeaders),
          "Content-Type": "multipart/form-data",
        },
        [
          {
            name: "file",
            filename: file.name,
            type: file.type,
            data: ReactNativeBlobUtil.wrap(file.uri.replace("file://", "")),
          },
        ],
      );
      return zUploadResponseSchema.parse(await resp.json());
    },
    onSuccess: (resp) => {
      const assetId = resp.assetId;
      const assetType =
        resp.contentType === "application/pdf" ? "pdf" : "image";
      createBookmark({
        type: BookmarkTypes.ASSET,
        assetId,
        assetType,
        source: "mobile",
      });
    },
    onError: (e) => {
      if (options.onError) {
        const err = zUploadErrorSchema.parse(JSON.parse(e.message));
        options.onError(err.error);
      }
    },
  });

  return {
    uploadAsset,
    isPending: isUploading || isCreatingBookmark,
  };
}