1 | import axios from "axios"; |
2 |
|
3 | type ShareSettings = { |
4 | shareWith?: string; |
5 | publicUpload?: boolean; |
6 | password?: string; |
7 | permissions?: number; |
8 | expireDate?: string; |
9 | note?: string; |
10 | label?: string; |
11 | sendMail?: boolean; |
12 | }; |
13 |
|
14 | |
15 | * Creates a Nextcloud share via OCS. |
16 | * |
17 | * shareType examples: |
18 | * - 0: user |
19 | * - 1: group |
20 | * - 3: public link |
21 | */ |
22 | export async function main( |
23 | ncResource: RT.Nextcloud, |
24 | path: string, |
25 | shareType: number, |
26 | shareWith: string, |
27 | settings: ShareSettings = {} |
28 | ) { |
29 | if (!path || !String(path).trim()) { |
30 | throw new Error("path is required"); |
31 | } |
32 |
|
33 | const body = new URLSearchParams(); |
34 | body.set("path", path); |
35 | body.set("shareType", String(shareType)); |
36 | body.set("shareWith", shareWith); |
37 |
|
38 | |
39 | setIfDefined(body, "publicUpload", settings.publicUpload); |
40 | setIfDefined(body, "password", settings.password); |
41 | setIfDefined(body, "permissions", settings.permissions); |
42 | setIfDefined(body, "expireDate", settings.expireDate); |
43 | setIfDefined(body, "note", settings.note); |
44 | setIfDefined(body, "label", settings.label); |
45 | setIfDefined(body, "sendMail", settings.sendMail); |
46 |
|
47 | const response = await axios.post( |
48 | `${ncResource.baseUrl.replace(/\/$/, "")}/ocs/v2.php/apps/files_sharing/api/v1/shares`, |
49 | body.toString(), |
50 | { |
51 | auth: { |
52 | username: ncResource.userId, |
53 | password: ncResource.token, |
54 | }, |
55 | headers: { |
56 | "OCS-APIRequest": "true", |
57 | "Content-Type": "application/x-www-form-urlencoded", |
58 | Accept: "application/json", |
59 | }, |
60 | params: { |
61 | format: "json", |
62 | }, |
63 | } |
64 | ); |
65 |
|
66 | const data = response.data; |
67 | const statusCode = data?.ocs?.meta?.statuscode; |
68 | if (statusCode !== 200) { |
69 | const msg = data?.ocs?.meta?.message || "Unknown error"; |
70 | throw new Error(`Failed to create share: ${msg}`); |
71 | } |
72 |
|
73 | return data?.ocs?.data; |
74 | } |
75 |
|
76 | function setIfDefined(body: URLSearchParams, key: string, value: string | boolean | number | undefined) { |
77 | if (value !== undefined) { |
78 | body.set(key, String(value)); |
79 | } |
80 | } |
81 |
|