1 | |
2 |
|
3 | export type DynSelect_folder_id = string |
4 |
|
5 | |
6 | export async function folder_id(auth: RT.Gdrive) { |
7 | const url = new URL("https://www.googleapis.com/drive/v3/files") |
8 | url.searchParams.append( |
9 | "q", |
10 | "mimeType = 'application/vnd.google-apps.folder' and trashed = false" |
11 | ) |
12 | url.searchParams.append("fields", "files(id, name)") |
13 | url.searchParams.append("orderBy", "name") |
14 | url.searchParams.append("pageSize", "1000") |
15 | url.searchParams.append("supportsAllDrives", "true") |
16 | url.searchParams.append("includeItemsFromAllDrives", "true") |
17 | const response = await fetch(url, { |
18 | headers: { |
19 | Authorization: `Bearer ${auth.token}`, |
20 | Accept: "application/json", |
21 | }, |
22 | }) |
23 | if (!response.ok) { |
24 | throw new Error(`${response.status} ${await response.text()}`) |
25 | } |
26 | const { files } = (await response.json()) as { |
27 | files: { id: string; name: string }[] |
28 | } |
29 | return [ |
30 | { value: "root", label: "My Drive (root)" }, |
31 | ...files.map((f) => ({ value: f.id, label: `${f.name} (${f.id})` })), |
32 | ] |
33 | } |
34 |
|
35 | |
36 | * Move File |
37 | * Move a file or folder into another folder: the new folder is added as its parent and every current parent is removed. Works across My Drive and shared drives the account can edit. |
38 | */ |
39 | export async function main( |
40 | auth: RT.Gdrive, |
41 | file_id: string, |
42 | folder_id: DynSelect_folder_id |
43 | ) { |
44 | const headers = { |
45 | Authorization: `Bearer ${auth.token}`, |
46 | Accept: "application/json", |
47 | } |
48 | const fileUrl = `https://www.googleapis.com/drive/v3/files/${file_id}` |
49 |
|
50 | const current = await fetch( |
51 | `${fileUrl}?fields=parents&supportsAllDrives=true`, |
52 | { headers } |
53 | ) |
54 | if (!current.ok) { |
55 | throw new Error(`${current.status} ${await current.text()}`) |
56 | } |
57 | const { parents = [] } = (await current.json()) as { parents?: string[] } |
58 |
|
59 | const url = new URL(fileUrl) |
60 | url.searchParams.append("addParents", folder_id) |
61 | const remove = parents.filter((p) => p !== folder_id) |
62 | if (remove.length > 0) |
63 | url.searchParams.append("removeParents", remove.join(",")) |
64 | url.searchParams.append("supportsAllDrives", "true") |
65 | url.searchParams.append("fields", "id, name, parents, webViewLink") |
66 |
|
67 | const response = await fetch(url, { |
68 | method: "PATCH", |
69 | headers: { ...headers, "Content-Type": "application/json" }, |
70 | body: "{}", |
71 | }) |
72 |
|
73 | if (!response.ok) { |
74 | throw new Error(`${response.status} ${await response.text()}`) |
75 | } |
76 |
|
77 | return await response.json() |
78 | } |
79 |
|