diff options
author | Chocobozzz <me@florianbigard.com> | 2023-08-17 08:59:21 +0200 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2023-08-17 08:59:21 +0200 |
commit | c380e3928517eb5311b38cf257816642617d7a33 (patch) | |
tree | 2ea9b70ebca16b5d109bcce98fe7f944dad89319 /packages/server-commands | |
parent | a8ca6190fb462bf6eb5685cfc1d8ae444164a487 (diff) | |
parent | 3a4992633ee62d5edfbb484d9c6bcb3cf158489d (diff) | |
download | PeerTube-c380e3928517eb5311b38cf257816642617d7a33.tar.gz PeerTube-c380e3928517eb5311b38cf257816642617d7a33.tar.zst PeerTube-c380e3928517eb5311b38cf257816642617d7a33.zip |
Merge branch 'feature/esm-and-nx' into develop
Diffstat (limited to 'packages/server-commands')
78 files changed, 7825 insertions, 0 deletions
diff --git a/packages/server-commands/package.json b/packages/server-commands/package.json new file mode 100644 index 000000000..df9778198 --- /dev/null +++ b/packages/server-commands/package.json | |||
@@ -0,0 +1,19 @@ | |||
1 | { | ||
2 | "name": "@peertube/peertube-server-commands", | ||
3 | "private": true, | ||
4 | "version": "0.0.0", | ||
5 | "main": "dist/index.js", | ||
6 | "files": [ "dist" ], | ||
7 | "exports": { | ||
8 | "types": "./dist/index.d.ts", | ||
9 | "peertube:tsx": "./src/index.ts", | ||
10 | "default": "./dist/index.js" | ||
11 | }, | ||
12 | "type": "module", | ||
13 | "devDependencies": {}, | ||
14 | "scripts": { | ||
15 | "build": "tsc", | ||
16 | "watch": "tsc -w" | ||
17 | }, | ||
18 | "dependencies": {} | ||
19 | } | ||
diff --git a/packages/server-commands/src/bulk/bulk-command.ts b/packages/server-commands/src/bulk/bulk-command.ts new file mode 100644 index 000000000..784836e19 --- /dev/null +++ b/packages/server-commands/src/bulk/bulk-command.ts | |||
@@ -0,0 +1,20 @@ | |||
1 | import { BulkRemoveCommentsOfBody, HttpStatusCode } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class BulkCommand extends AbstractCommand { | ||
5 | |||
6 | removeCommentsOf (options: OverrideCommandOptions & { | ||
7 | attributes: BulkRemoveCommentsOfBody | ||
8 | }) { | ||
9 | const { attributes } = options | ||
10 | |||
11 | return this.postBodyRequest({ | ||
12 | ...options, | ||
13 | |||
14 | path: '/api/v1/bulk/remove-comments-of', | ||
15 | fields: attributes, | ||
16 | implicitToken: true, | ||
17 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
18 | }) | ||
19 | } | ||
20 | } | ||
diff --git a/packages/server-commands/src/bulk/index.ts b/packages/server-commands/src/bulk/index.ts new file mode 100644 index 000000000..903f7a282 --- /dev/null +++ b/packages/server-commands/src/bulk/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './bulk-command.js' | |||
diff --git a/packages/server-commands/src/cli/cli-command.ts b/packages/server-commands/src/cli/cli-command.ts new file mode 100644 index 000000000..8b9400c85 --- /dev/null +++ b/packages/server-commands/src/cli/cli-command.ts | |||
@@ -0,0 +1,27 @@ | |||
1 | import { exec } from 'child_process' | ||
2 | import { AbstractCommand } from '../shared/index.js' | ||
3 | |||
4 | export class CLICommand extends AbstractCommand { | ||
5 | |||
6 | static exec (command: string) { | ||
7 | return new Promise<string>((res, rej) => { | ||
8 | exec(command, (err, stdout, _stderr) => { | ||
9 | if (err) return rej(err) | ||
10 | |||
11 | return res(stdout) | ||
12 | }) | ||
13 | }) | ||
14 | } | ||
15 | |||
16 | getEnv () { | ||
17 | return `NODE_ENV=test NODE_APP_INSTANCE=${this.server.internalServerNumber}` | ||
18 | } | ||
19 | |||
20 | async execWithEnv (command: string, configOverride?: any) { | ||
21 | const prefix = configOverride | ||
22 | ? `NODE_CONFIG='${JSON.stringify(configOverride)}'` | ||
23 | : '' | ||
24 | |||
25 | return CLICommand.exec(`${prefix} ${this.getEnv()} ${command}`) | ||
26 | } | ||
27 | } | ||
diff --git a/packages/server-commands/src/cli/index.ts b/packages/server-commands/src/cli/index.ts new file mode 100644 index 000000000..d79b13a76 --- /dev/null +++ b/packages/server-commands/src/cli/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './cli-command.js' | |||
diff --git a/packages/server-commands/src/custom-pages/custom-pages-command.ts b/packages/server-commands/src/custom-pages/custom-pages-command.ts new file mode 100644 index 000000000..412f3f763 --- /dev/null +++ b/packages/server-commands/src/custom-pages/custom-pages-command.ts | |||
@@ -0,0 +1,33 @@ | |||
1 | import { CustomPage, HttpStatusCode } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class CustomPagesCommand extends AbstractCommand { | ||
5 | |||
6 | getInstanceHomepage (options: OverrideCommandOptions = {}) { | ||
7 | const path = '/api/v1/custom-pages/homepage/instance' | ||
8 | |||
9 | return this.getRequestBody<CustomPage>({ | ||
10 | ...options, | ||
11 | |||
12 | path, | ||
13 | implicitToken: false, | ||
14 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
15 | }) | ||
16 | } | ||
17 | |||
18 | updateInstanceHomepage (options: OverrideCommandOptions & { | ||
19 | content: string | ||
20 | }) { | ||
21 | const { content } = options | ||
22 | const path = '/api/v1/custom-pages/homepage/instance' | ||
23 | |||
24 | return this.putBodyRequest({ | ||
25 | ...options, | ||
26 | |||
27 | path, | ||
28 | fields: { content }, | ||
29 | implicitToken: true, | ||
30 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
31 | }) | ||
32 | } | ||
33 | } | ||
diff --git a/packages/server-commands/src/custom-pages/index.ts b/packages/server-commands/src/custom-pages/index.ts new file mode 100644 index 000000000..67f537f07 --- /dev/null +++ b/packages/server-commands/src/custom-pages/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './custom-pages-command.js' | |||
diff --git a/packages/server-commands/src/feeds/feeds-command.ts b/packages/server-commands/src/feeds/feeds-command.ts new file mode 100644 index 000000000..51bc45b7f --- /dev/null +++ b/packages/server-commands/src/feeds/feeds-command.ts | |||
@@ -0,0 +1,78 @@ | |||
1 | import { buildUUID } from '@peertube/peertube-node-utils' | ||
2 | import { HttpStatusCode } from '@peertube/peertube-models' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | type FeedType = 'videos' | 'video-comments' | 'subscriptions' | ||
6 | |||
7 | export class FeedCommand extends AbstractCommand { | ||
8 | |||
9 | getXML (options: OverrideCommandOptions & { | ||
10 | feed: FeedType | ||
11 | ignoreCache: boolean | ||
12 | format?: string | ||
13 | }) { | ||
14 | const { feed, format, ignoreCache } = options | ||
15 | const path = '/feeds/' + feed + '.xml' | ||
16 | |||
17 | const query: { [id: string]: string } = {} | ||
18 | |||
19 | if (ignoreCache) query.v = buildUUID() | ||
20 | if (format) query.format = format | ||
21 | |||
22 | return this.getRequestText({ | ||
23 | ...options, | ||
24 | |||
25 | path, | ||
26 | query, | ||
27 | accept: 'application/xml', | ||
28 | implicitToken: false, | ||
29 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
30 | }) | ||
31 | } | ||
32 | |||
33 | getPodcastXML (options: OverrideCommandOptions & { | ||
34 | ignoreCache: boolean | ||
35 | channelId: number | ||
36 | }) { | ||
37 | const { ignoreCache, channelId } = options | ||
38 | const path = `/feeds/podcast/videos.xml` | ||
39 | |||
40 | const query: { [id: string]: string } = {} | ||
41 | |||
42 | if (ignoreCache) query.v = buildUUID() | ||
43 | if (channelId) query.videoChannelId = channelId + '' | ||
44 | |||
45 | return this.getRequestText({ | ||
46 | ...options, | ||
47 | |||
48 | path, | ||
49 | query, | ||
50 | accept: 'application/xml', | ||
51 | implicitToken: false, | ||
52 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | getJSON (options: OverrideCommandOptions & { | ||
57 | feed: FeedType | ||
58 | ignoreCache: boolean | ||
59 | query?: { [ id: string ]: any } | ||
60 | }) { | ||
61 | const { feed, query = {}, ignoreCache } = options | ||
62 | const path = '/feeds/' + feed + '.json' | ||
63 | |||
64 | const cacheQuery = ignoreCache | ||
65 | ? { v: buildUUID() } | ||
66 | : {} | ||
67 | |||
68 | return this.getRequestText({ | ||
69 | ...options, | ||
70 | |||
71 | path, | ||
72 | query: { ...query, ...cacheQuery }, | ||
73 | accept: 'application/json', | ||
74 | implicitToken: false, | ||
75 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
76 | }) | ||
77 | } | ||
78 | } | ||
diff --git a/packages/server-commands/src/feeds/index.ts b/packages/server-commands/src/feeds/index.ts new file mode 100644 index 000000000..316ebb974 --- /dev/null +++ b/packages/server-commands/src/feeds/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './feeds-command.js' | |||
diff --git a/packages/server-commands/src/index.ts b/packages/server-commands/src/index.ts new file mode 100644 index 000000000..382fe966e --- /dev/null +++ b/packages/server-commands/src/index.ts | |||
@@ -0,0 +1,14 @@ | |||
1 | export * from './bulk/index.js' | ||
2 | export * from './cli/index.js' | ||
3 | export * from './custom-pages/index.js' | ||
4 | export * from './feeds/index.js' | ||
5 | export * from './logs/index.js' | ||
6 | export * from './moderation/index.js' | ||
7 | export * from './overviews/index.js' | ||
8 | export * from './requests/index.js' | ||
9 | export * from './runners/index.js' | ||
10 | export * from './search/index.js' | ||
11 | export * from './server/index.js' | ||
12 | export * from './socket/index.js' | ||
13 | export * from './users/index.js' | ||
14 | export * from './videos/index.js' | ||
diff --git a/packages/server-commands/src/logs/index.ts b/packages/server-commands/src/logs/index.ts new file mode 100644 index 000000000..37e77901c --- /dev/null +++ b/packages/server-commands/src/logs/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './logs-command.js' | |||
diff --git a/packages/server-commands/src/logs/logs-command.ts b/packages/server-commands/src/logs/logs-command.ts new file mode 100644 index 000000000..d5d11b997 --- /dev/null +++ b/packages/server-commands/src/logs/logs-command.ts | |||
@@ -0,0 +1,56 @@ | |||
1 | import { ClientLogCreate, HttpStatusCode, ServerLogLevel } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class LogsCommand extends AbstractCommand { | ||
5 | |||
6 | createLogClient (options: OverrideCommandOptions & { payload: ClientLogCreate }) { | ||
7 | const path = '/api/v1/server/logs/client' | ||
8 | |||
9 | return this.postBodyRequest({ | ||
10 | ...options, | ||
11 | |||
12 | path, | ||
13 | fields: options.payload, | ||
14 | implicitToken: true, | ||
15 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
16 | }) | ||
17 | } | ||
18 | |||
19 | getLogs (options: OverrideCommandOptions & { | ||
20 | startDate: Date | ||
21 | endDate?: Date | ||
22 | level?: ServerLogLevel | ||
23 | tagsOneOf?: string[] | ||
24 | }) { | ||
25 | const { startDate, endDate, tagsOneOf, level } = options | ||
26 | const path = '/api/v1/server/logs' | ||
27 | |||
28 | return this.getRequestBody<any[]>({ | ||
29 | ...options, | ||
30 | |||
31 | path, | ||
32 | query: { startDate, endDate, level, tagsOneOf }, | ||
33 | implicitToken: true, | ||
34 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
35 | }) | ||
36 | } | ||
37 | |||
38 | getAuditLogs (options: OverrideCommandOptions & { | ||
39 | startDate: Date | ||
40 | endDate?: Date | ||
41 | }) { | ||
42 | const { startDate, endDate } = options | ||
43 | |||
44 | const path = '/api/v1/server/audit-logs' | ||
45 | |||
46 | return this.getRequestBody({ | ||
47 | ...options, | ||
48 | |||
49 | path, | ||
50 | query: { startDate, endDate }, | ||
51 | implicitToken: true, | ||
52 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | } | ||
diff --git a/packages/server-commands/src/moderation/abuses-command.ts b/packages/server-commands/src/moderation/abuses-command.ts new file mode 100644 index 000000000..e267709e2 --- /dev/null +++ b/packages/server-commands/src/moderation/abuses-command.ts | |||
@@ -0,0 +1,228 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | AbuseFilter, | ||
4 | AbuseMessage, | ||
5 | AbusePredefinedReasonsString, | ||
6 | AbuseStateType, | ||
7 | AbuseUpdate, | ||
8 | AbuseVideoIs, | ||
9 | AdminAbuse, | ||
10 | HttpStatusCode, | ||
11 | ResultList, | ||
12 | UserAbuse | ||
13 | } from '@peertube/peertube-models' | ||
14 | import { unwrapBody } from '../requests/requests.js' | ||
15 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
16 | |||
17 | export class AbusesCommand extends AbstractCommand { | ||
18 | |||
19 | report (options: OverrideCommandOptions & { | ||
20 | reason: string | ||
21 | |||
22 | accountId?: number | ||
23 | videoId?: number | ||
24 | commentId?: number | ||
25 | |||
26 | predefinedReasons?: AbusePredefinedReasonsString[] | ||
27 | |||
28 | startAt?: number | ||
29 | endAt?: number | ||
30 | }) { | ||
31 | const path = '/api/v1/abuses' | ||
32 | |||
33 | const video = options.videoId | ||
34 | ? { | ||
35 | id: options.videoId, | ||
36 | startAt: options.startAt, | ||
37 | endAt: options.endAt | ||
38 | } | ||
39 | : undefined | ||
40 | |||
41 | const comment = options.commentId | ||
42 | ? { id: options.commentId } | ||
43 | : undefined | ||
44 | |||
45 | const account = options.accountId | ||
46 | ? { id: options.accountId } | ||
47 | : undefined | ||
48 | |||
49 | const body = { | ||
50 | account, | ||
51 | video, | ||
52 | comment, | ||
53 | |||
54 | reason: options.reason, | ||
55 | predefinedReasons: options.predefinedReasons | ||
56 | } | ||
57 | |||
58 | return unwrapBody<{ abuse: { id: number } }>(this.postBodyRequest({ | ||
59 | ...options, | ||
60 | |||
61 | path, | ||
62 | fields: body, | ||
63 | implicitToken: true, | ||
64 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
65 | })) | ||
66 | } | ||
67 | |||
68 | getAdminList (options: OverrideCommandOptions & { | ||
69 | start?: number | ||
70 | count?: number | ||
71 | sort?: string | ||
72 | |||
73 | id?: number | ||
74 | predefinedReason?: AbusePredefinedReasonsString | ||
75 | search?: string | ||
76 | filter?: AbuseFilter | ||
77 | state?: AbuseStateType | ||
78 | videoIs?: AbuseVideoIs | ||
79 | searchReporter?: string | ||
80 | searchReportee?: string | ||
81 | searchVideo?: string | ||
82 | searchVideoChannel?: string | ||
83 | } = {}) { | ||
84 | const toPick: (keyof typeof options)[] = [ | ||
85 | 'count', | ||
86 | 'filter', | ||
87 | 'id', | ||
88 | 'predefinedReason', | ||
89 | 'search', | ||
90 | 'searchReportee', | ||
91 | 'searchReporter', | ||
92 | 'searchVideo', | ||
93 | 'searchVideoChannel', | ||
94 | 'sort', | ||
95 | 'start', | ||
96 | 'state', | ||
97 | 'videoIs' | ||
98 | ] | ||
99 | |||
100 | const path = '/api/v1/abuses' | ||
101 | |||
102 | const defaultQuery = { sort: 'createdAt' } | ||
103 | const query = { ...defaultQuery, ...pick(options, toPick) } | ||
104 | |||
105 | return this.getRequestBody<ResultList<AdminAbuse>>({ | ||
106 | ...options, | ||
107 | |||
108 | path, | ||
109 | query, | ||
110 | implicitToken: true, | ||
111 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
112 | }) | ||
113 | } | ||
114 | |||
115 | getUserList (options: OverrideCommandOptions & { | ||
116 | start?: number | ||
117 | count?: number | ||
118 | sort?: string | ||
119 | |||
120 | id?: number | ||
121 | search?: string | ||
122 | state?: AbuseStateType | ||
123 | }) { | ||
124 | const toPick: (keyof typeof options)[] = [ | ||
125 | 'id', | ||
126 | 'search', | ||
127 | 'state', | ||
128 | 'start', | ||
129 | 'count', | ||
130 | 'sort' | ||
131 | ] | ||
132 | |||
133 | const path = '/api/v1/users/me/abuses' | ||
134 | |||
135 | const defaultQuery = { sort: 'createdAt' } | ||
136 | const query = { ...defaultQuery, ...pick(options, toPick) } | ||
137 | |||
138 | return this.getRequestBody<ResultList<UserAbuse>>({ | ||
139 | ...options, | ||
140 | |||
141 | path, | ||
142 | query, | ||
143 | implicitToken: true, | ||
144 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
145 | }) | ||
146 | } | ||
147 | |||
148 | update (options: OverrideCommandOptions & { | ||
149 | abuseId: number | ||
150 | body: AbuseUpdate | ||
151 | }) { | ||
152 | const { abuseId, body } = options | ||
153 | const path = '/api/v1/abuses/' + abuseId | ||
154 | |||
155 | return this.putBodyRequest({ | ||
156 | ...options, | ||
157 | |||
158 | path, | ||
159 | fields: body, | ||
160 | implicitToken: true, | ||
161 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
162 | }) | ||
163 | } | ||
164 | |||
165 | delete (options: OverrideCommandOptions & { | ||
166 | abuseId: number | ||
167 | }) { | ||
168 | const { abuseId } = options | ||
169 | const path = '/api/v1/abuses/' + abuseId | ||
170 | |||
171 | return this.deleteRequest({ | ||
172 | ...options, | ||
173 | |||
174 | path, | ||
175 | implicitToken: true, | ||
176 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
177 | }) | ||
178 | } | ||
179 | |||
180 | listMessages (options: OverrideCommandOptions & { | ||
181 | abuseId: number | ||
182 | }) { | ||
183 | const { abuseId } = options | ||
184 | const path = '/api/v1/abuses/' + abuseId + '/messages' | ||
185 | |||
186 | return this.getRequestBody<ResultList<AbuseMessage>>({ | ||
187 | ...options, | ||
188 | |||
189 | path, | ||
190 | implicitToken: true, | ||
191 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
192 | }) | ||
193 | } | ||
194 | |||
195 | deleteMessage (options: OverrideCommandOptions & { | ||
196 | abuseId: number | ||
197 | messageId: number | ||
198 | }) { | ||
199 | const { abuseId, messageId } = options | ||
200 | const path = '/api/v1/abuses/' + abuseId + '/messages/' + messageId | ||
201 | |||
202 | return this.deleteRequest({ | ||
203 | ...options, | ||
204 | |||
205 | path, | ||
206 | implicitToken: true, | ||
207 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
208 | }) | ||
209 | } | ||
210 | |||
211 | addMessage (options: OverrideCommandOptions & { | ||
212 | abuseId: number | ||
213 | message: string | ||
214 | }) { | ||
215 | const { abuseId, message } = options | ||
216 | const path = '/api/v1/abuses/' + abuseId + '/messages' | ||
217 | |||
218 | return this.postBodyRequest({ | ||
219 | ...options, | ||
220 | |||
221 | path, | ||
222 | fields: { message }, | ||
223 | implicitToken: true, | ||
224 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
225 | }) | ||
226 | } | ||
227 | |||
228 | } | ||
diff --git a/packages/server-commands/src/moderation/index.ts b/packages/server-commands/src/moderation/index.ts new file mode 100644 index 000000000..8164afd7c --- /dev/null +++ b/packages/server-commands/src/moderation/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './abuses-command.js' | |||
diff --git a/packages/server-commands/src/overviews/index.ts b/packages/server-commands/src/overviews/index.ts new file mode 100644 index 000000000..54c90705a --- /dev/null +++ b/packages/server-commands/src/overviews/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './overviews-command.js' | |||
diff --git a/packages/server-commands/src/overviews/overviews-command.ts b/packages/server-commands/src/overviews/overviews-command.ts new file mode 100644 index 000000000..decd2fd8e --- /dev/null +++ b/packages/server-commands/src/overviews/overviews-command.ts | |||
@@ -0,0 +1,23 @@ | |||
1 | import { HttpStatusCode, VideosOverview } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class OverviewsCommand extends AbstractCommand { | ||
5 | |||
6 | getVideos (options: OverrideCommandOptions & { | ||
7 | page: number | ||
8 | }) { | ||
9 | const { page } = options | ||
10 | const path = '/api/v1/overviews/videos' | ||
11 | |||
12 | const query = { page } | ||
13 | |||
14 | return this.getRequestBody<VideosOverview>({ | ||
15 | ...options, | ||
16 | |||
17 | path, | ||
18 | query, | ||
19 | implicitToken: false, | ||
20 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
21 | }) | ||
22 | } | ||
23 | } | ||
diff --git a/packages/server-commands/src/requests/index.ts b/packages/server-commands/src/requests/index.ts new file mode 100644 index 000000000..4c818659e --- /dev/null +++ b/packages/server-commands/src/requests/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './requests.js' | |||
diff --git a/packages/server-commands/src/requests/requests.ts b/packages/server-commands/src/requests/requests.ts new file mode 100644 index 000000000..ac143ea5d --- /dev/null +++ b/packages/server-commands/src/requests/requests.ts | |||
@@ -0,0 +1,260 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-floating-promises */ | ||
2 | |||
3 | import { decode } from 'querystring' | ||
4 | import request from 'supertest' | ||
5 | import { URL } from 'url' | ||
6 | import { pick } from '@peertube/peertube-core-utils' | ||
7 | import { HttpStatusCode, HttpStatusCodeType } from '@peertube/peertube-models' | ||
8 | import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils' | ||
9 | |||
10 | export type CommonRequestParams = { | ||
11 | url: string | ||
12 | path?: string | ||
13 | contentType?: string | ||
14 | responseType?: string | ||
15 | range?: string | ||
16 | redirects?: number | ||
17 | accept?: string | ||
18 | host?: string | ||
19 | token?: string | ||
20 | headers?: { [ name: string ]: string } | ||
21 | type?: string | ||
22 | xForwardedFor?: string | ||
23 | expectedStatus?: HttpStatusCodeType | ||
24 | } | ||
25 | |||
26 | function makeRawRequest (options: { | ||
27 | url: string | ||
28 | token?: string | ||
29 | expectedStatus?: HttpStatusCodeType | ||
30 | range?: string | ||
31 | query?: { [ id: string ]: string } | ||
32 | method?: 'GET' | 'POST' | ||
33 | headers?: { [ name: string ]: string } | ||
34 | }) { | ||
35 | const { host, protocol, pathname } = new URL(options.url) | ||
36 | |||
37 | const reqOptions = { | ||
38 | url: `${protocol}//${host}`, | ||
39 | path: pathname, | ||
40 | contentType: undefined, | ||
41 | |||
42 | ...pick(options, [ 'expectedStatus', 'range', 'token', 'query', 'headers' ]) | ||
43 | } | ||
44 | |||
45 | if (options.method === 'POST') { | ||
46 | return makePostBodyRequest(reqOptions) | ||
47 | } | ||
48 | |||
49 | return makeGetRequest(reqOptions) | ||
50 | } | ||
51 | |||
52 | function makeGetRequest (options: CommonRequestParams & { | ||
53 | query?: any | ||
54 | rawQuery?: string | ||
55 | }) { | ||
56 | const req = request(options.url).get(options.path) | ||
57 | |||
58 | if (options.query) req.query(options.query) | ||
59 | if (options.rawQuery) req.query(options.rawQuery) | ||
60 | |||
61 | return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) | ||
62 | } | ||
63 | |||
64 | function makeHTMLRequest (url: string, path: string) { | ||
65 | return makeGetRequest({ | ||
66 | url, | ||
67 | path, | ||
68 | accept: 'text/html', | ||
69 | expectedStatus: HttpStatusCode.OK_200 | ||
70 | }) | ||
71 | } | ||
72 | |||
73 | function makeActivityPubGetRequest (url: string, path: string, expectedStatus: HttpStatusCodeType = HttpStatusCode.OK_200) { | ||
74 | return makeGetRequest({ | ||
75 | url, | ||
76 | path, | ||
77 | expectedStatus, | ||
78 | accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8' | ||
79 | }) | ||
80 | } | ||
81 | |||
82 | function makeDeleteRequest (options: CommonRequestParams & { | ||
83 | query?: any | ||
84 | rawQuery?: string | ||
85 | }) { | ||
86 | const req = request(options.url).delete(options.path) | ||
87 | |||
88 | if (options.query) req.query(options.query) | ||
89 | if (options.rawQuery) req.query(options.rawQuery) | ||
90 | |||
91 | return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) | ||
92 | } | ||
93 | |||
94 | function makeUploadRequest (options: CommonRequestParams & { | ||
95 | method?: 'POST' | 'PUT' | ||
96 | |||
97 | fields: { [ fieldName: string ]: any } | ||
98 | attaches?: { [ attachName: string ]: any | any[] } | ||
99 | }) { | ||
100 | let req = options.method === 'PUT' | ||
101 | ? request(options.url).put(options.path) | ||
102 | : request(options.url).post(options.path) | ||
103 | |||
104 | req = buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) | ||
105 | |||
106 | buildFields(req, options.fields) | ||
107 | |||
108 | Object.keys(options.attaches || {}).forEach(attach => { | ||
109 | const value = options.attaches[attach] | ||
110 | if (!value) return | ||
111 | |||
112 | if (Array.isArray(value)) { | ||
113 | req.attach(attach, buildAbsoluteFixturePath(value[0]), value[1]) | ||
114 | } else { | ||
115 | req.attach(attach, buildAbsoluteFixturePath(value)) | ||
116 | } | ||
117 | }) | ||
118 | |||
119 | return req | ||
120 | } | ||
121 | |||
122 | function makePostBodyRequest (options: CommonRequestParams & { | ||
123 | fields?: { [ fieldName: string ]: any } | ||
124 | }) { | ||
125 | const req = request(options.url).post(options.path) | ||
126 | .send(options.fields) | ||
127 | |||
128 | return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) | ||
129 | } | ||
130 | |||
131 | function makePutBodyRequest (options: { | ||
132 | url: string | ||
133 | path: string | ||
134 | token?: string | ||
135 | fields: { [ fieldName: string ]: any } | ||
136 | expectedStatus?: HttpStatusCodeType | ||
137 | headers?: { [name: string]: string } | ||
138 | }) { | ||
139 | const req = request(options.url).put(options.path) | ||
140 | .send(options.fields) | ||
141 | |||
142 | return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) | ||
143 | } | ||
144 | |||
145 | function decodeQueryString (path: string) { | ||
146 | return decode(path.split('?')[1]) | ||
147 | } | ||
148 | |||
149 | // --------------------------------------------------------------------------- | ||
150 | |||
151 | function unwrapBody <T> (test: request.Test): Promise<T> { | ||
152 | return test.then(res => res.body) | ||
153 | } | ||
154 | |||
155 | function unwrapText (test: request.Test): Promise<string> { | ||
156 | return test.then(res => res.text) | ||
157 | } | ||
158 | |||
159 | function unwrapBodyOrDecodeToJSON <T> (test: request.Test): Promise<T> { | ||
160 | return test.then(res => { | ||
161 | if (res.body instanceof Buffer) { | ||
162 | try { | ||
163 | return JSON.parse(new TextDecoder().decode(res.body)) | ||
164 | } catch (err) { | ||
165 | console.error('Cannot decode JSON.', { res, body: res.body instanceof Buffer ? res.body.toString() : res.body }) | ||
166 | throw err | ||
167 | } | ||
168 | } | ||
169 | |||
170 | if (res.text) { | ||
171 | try { | ||
172 | return JSON.parse(res.text) | ||
173 | } catch (err) { | ||
174 | console.error('Cannot decode json', { res, text: res.text }) | ||
175 | throw err | ||
176 | } | ||
177 | } | ||
178 | |||
179 | return res.body | ||
180 | }) | ||
181 | } | ||
182 | |||
183 | function unwrapTextOrDecode (test: request.Test): Promise<string> { | ||
184 | return test.then(res => res.text || new TextDecoder().decode(res.body)) | ||
185 | } | ||
186 | |||
187 | // --------------------------------------------------------------------------- | ||
188 | |||
189 | export { | ||
190 | makeHTMLRequest, | ||
191 | makeGetRequest, | ||
192 | decodeQueryString, | ||
193 | makeUploadRequest, | ||
194 | makePostBodyRequest, | ||
195 | makePutBodyRequest, | ||
196 | makeDeleteRequest, | ||
197 | makeRawRequest, | ||
198 | makeActivityPubGetRequest, | ||
199 | unwrapBody, | ||
200 | unwrapTextOrDecode, | ||
201 | unwrapBodyOrDecodeToJSON, | ||
202 | unwrapText | ||
203 | } | ||
204 | |||
205 | // --------------------------------------------------------------------------- | ||
206 | |||
207 | function buildRequest (req: request.Test, options: CommonRequestParams) { | ||
208 | if (options.contentType) req.set('Accept', options.contentType) | ||
209 | if (options.responseType) req.responseType(options.responseType) | ||
210 | if (options.token) req.set('Authorization', 'Bearer ' + options.token) | ||
211 | if (options.range) req.set('Range', options.range) | ||
212 | if (options.accept) req.set('Accept', options.accept) | ||
213 | if (options.host) req.set('Host', options.host) | ||
214 | if (options.redirects) req.redirects(options.redirects) | ||
215 | if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor) | ||
216 | if (options.type) req.type(options.type) | ||
217 | |||
218 | Object.keys(options.headers || {}).forEach(name => { | ||
219 | req.set(name, options.headers[name]) | ||
220 | }) | ||
221 | |||
222 | return req.expect(res => { | ||
223 | if (options.expectedStatus && res.status !== options.expectedStatus) { | ||
224 | const err = new Error(`Expected status ${options.expectedStatus}, got ${res.status}. ` + | ||
225 | `\nThe server responded: "${res.body?.error ?? res.text}".\n` + | ||
226 | 'You may take a closer look at the logs. To see how to do so, check out this page: ' + | ||
227 | 'https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/development/tests.md#debug-server-logs'); | ||
228 | |||
229 | (err as any).res = res | ||
230 | |||
231 | throw err | ||
232 | } | ||
233 | |||
234 | return res | ||
235 | }) | ||
236 | } | ||
237 | |||
238 | function buildFields (req: request.Test, fields: { [ fieldName: string ]: any }, namespace?: string) { | ||
239 | if (!fields) return | ||
240 | |||
241 | let formKey: string | ||
242 | |||
243 | for (const key of Object.keys(fields)) { | ||
244 | if (namespace) formKey = `${namespace}[${key}]` | ||
245 | else formKey = key | ||
246 | |||
247 | if (fields[key] === undefined) continue | ||
248 | |||
249 | if (Array.isArray(fields[key]) && fields[key].length === 0) { | ||
250 | req.field(key, []) | ||
251 | continue | ||
252 | } | ||
253 | |||
254 | if (fields[key] !== null && typeof fields[key] === 'object') { | ||
255 | buildFields(req, fields[key], formKey) | ||
256 | } else { | ||
257 | req.field(formKey, fields[key]) | ||
258 | } | ||
259 | } | ||
260 | } | ||
diff --git a/packages/server-commands/src/runners/index.ts b/packages/server-commands/src/runners/index.ts new file mode 100644 index 000000000..c868fa78e --- /dev/null +++ b/packages/server-commands/src/runners/index.ts | |||
@@ -0,0 +1,3 @@ | |||
1 | export * from './runner-jobs-command.js' | ||
2 | export * from './runner-registration-tokens-command.js' | ||
3 | export * from './runners-command.js' | ||
diff --git a/packages/server-commands/src/runners/runner-jobs-command.ts b/packages/server-commands/src/runners/runner-jobs-command.ts new file mode 100644 index 000000000..4e702199f --- /dev/null +++ b/packages/server-commands/src/runners/runner-jobs-command.ts | |||
@@ -0,0 +1,297 @@ | |||
1 | import { omit, pick, wait } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | AbortRunnerJobBody, | ||
4 | AcceptRunnerJobBody, | ||
5 | AcceptRunnerJobResult, | ||
6 | ErrorRunnerJobBody, | ||
7 | HttpStatusCode, | ||
8 | isHLSTranscodingPayloadSuccess, | ||
9 | isLiveRTMPHLSTranscodingUpdatePayload, | ||
10 | isWebVideoOrAudioMergeTranscodingPayloadSuccess, | ||
11 | ListRunnerJobsQuery, | ||
12 | RequestRunnerJobBody, | ||
13 | RequestRunnerJobResult, | ||
14 | ResultList, | ||
15 | RunnerJobAdmin, | ||
16 | RunnerJobLiveRTMPHLSTranscodingPayload, | ||
17 | RunnerJobPayload, | ||
18 | RunnerJobState, | ||
19 | RunnerJobStateType, | ||
20 | RunnerJobSuccessBody, | ||
21 | RunnerJobSuccessPayload, | ||
22 | RunnerJobType, | ||
23 | RunnerJobUpdateBody, | ||
24 | RunnerJobVODPayload, | ||
25 | VODHLSTranscodingSuccess, | ||
26 | VODWebVideoTranscodingSuccess | ||
27 | } from '@peertube/peertube-models' | ||
28 | import { unwrapBody } from '../requests/index.js' | ||
29 | import { waitJobs } from '../server/jobs.js' | ||
30 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
31 | |||
32 | export class RunnerJobsCommand extends AbstractCommand { | ||
33 | |||
34 | list (options: OverrideCommandOptions & ListRunnerJobsQuery = {}) { | ||
35 | const path = '/api/v1/runners/jobs' | ||
36 | |||
37 | return this.getRequestBody<ResultList<RunnerJobAdmin>>({ | ||
38 | ...options, | ||
39 | |||
40 | path, | ||
41 | query: pick(options, [ 'start', 'count', 'sort', 'search', 'stateOneOf' ]), | ||
42 | implicitToken: true, | ||
43 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
44 | }) | ||
45 | } | ||
46 | |||
47 | cancelByAdmin (options: OverrideCommandOptions & { jobUUID: string }) { | ||
48 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/cancel' | ||
49 | |||
50 | return this.postBodyRequest({ | ||
51 | ...options, | ||
52 | |||
53 | path, | ||
54 | implicitToken: true, | ||
55 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
56 | }) | ||
57 | } | ||
58 | |||
59 | deleteByAdmin (options: OverrideCommandOptions & { jobUUID: string }) { | ||
60 | const path = '/api/v1/runners/jobs/' + options.jobUUID | ||
61 | |||
62 | return this.deleteRequest({ | ||
63 | ...options, | ||
64 | |||
65 | path, | ||
66 | implicitToken: true, | ||
67 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
68 | }) | ||
69 | } | ||
70 | |||
71 | // --------------------------------------------------------------------------- | ||
72 | |||
73 | request (options: OverrideCommandOptions & RequestRunnerJobBody) { | ||
74 | const path = '/api/v1/runners/jobs/request' | ||
75 | |||
76 | return unwrapBody<RequestRunnerJobResult>(this.postBodyRequest({ | ||
77 | ...options, | ||
78 | |||
79 | path, | ||
80 | fields: pick(options, [ 'runnerToken' ]), | ||
81 | implicitToken: false, | ||
82 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
83 | })) | ||
84 | } | ||
85 | |||
86 | async requestVOD (options: OverrideCommandOptions & RequestRunnerJobBody) { | ||
87 | const vodTypes = new Set<RunnerJobType>([ 'vod-audio-merge-transcoding', 'vod-hls-transcoding', 'vod-web-video-transcoding' ]) | ||
88 | |||
89 | const { availableJobs } = await this.request(options) | ||
90 | |||
91 | return { | ||
92 | availableJobs: availableJobs.filter(j => vodTypes.has(j.type)) | ||
93 | } as RequestRunnerJobResult<RunnerJobVODPayload> | ||
94 | } | ||
95 | |||
96 | async requestLive (options: OverrideCommandOptions & RequestRunnerJobBody) { | ||
97 | const vodTypes = new Set<RunnerJobType>([ 'live-rtmp-hls-transcoding' ]) | ||
98 | |||
99 | const { availableJobs } = await this.request(options) | ||
100 | |||
101 | return { | ||
102 | availableJobs: availableJobs.filter(j => vodTypes.has(j.type)) | ||
103 | } as RequestRunnerJobResult<RunnerJobLiveRTMPHLSTranscodingPayload> | ||
104 | } | ||
105 | |||
106 | // --------------------------------------------------------------------------- | ||
107 | |||
108 | accept <T extends RunnerJobPayload = RunnerJobPayload> (options: OverrideCommandOptions & AcceptRunnerJobBody & { jobUUID: string }) { | ||
109 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/accept' | ||
110 | |||
111 | return unwrapBody<AcceptRunnerJobResult<T>>(this.postBodyRequest({ | ||
112 | ...options, | ||
113 | |||
114 | path, | ||
115 | fields: pick(options, [ 'runnerToken' ]), | ||
116 | implicitToken: false, | ||
117 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
118 | })) | ||
119 | } | ||
120 | |||
121 | abort (options: OverrideCommandOptions & AbortRunnerJobBody & { jobUUID: string }) { | ||
122 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/abort' | ||
123 | |||
124 | return this.postBodyRequest({ | ||
125 | ...options, | ||
126 | |||
127 | path, | ||
128 | fields: pick(options, [ 'reason', 'jobToken', 'runnerToken' ]), | ||
129 | implicitToken: false, | ||
130 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
131 | }) | ||
132 | } | ||
133 | |||
134 | update (options: OverrideCommandOptions & RunnerJobUpdateBody & { jobUUID: string }) { | ||
135 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/update' | ||
136 | |||
137 | const { payload } = options | ||
138 | const attaches: { [id: string]: any } = {} | ||
139 | let payloadWithoutFiles = payload | ||
140 | |||
141 | if (isLiveRTMPHLSTranscodingUpdatePayload(payload)) { | ||
142 | if (payload.masterPlaylistFile) { | ||
143 | attaches[`payload[masterPlaylistFile]`] = payload.masterPlaylistFile | ||
144 | } | ||
145 | |||
146 | attaches[`payload[resolutionPlaylistFile]`] = payload.resolutionPlaylistFile | ||
147 | attaches[`payload[videoChunkFile]`] = payload.videoChunkFile | ||
148 | |||
149 | payloadWithoutFiles = omit(payloadWithoutFiles, [ 'masterPlaylistFile', 'resolutionPlaylistFile', 'videoChunkFile' ]) | ||
150 | } | ||
151 | |||
152 | return this.postUploadRequest({ | ||
153 | ...options, | ||
154 | |||
155 | path, | ||
156 | fields: { | ||
157 | ...pick(options, [ 'progress', 'jobToken', 'runnerToken' ]), | ||
158 | |||
159 | payload: payloadWithoutFiles | ||
160 | }, | ||
161 | attaches, | ||
162 | implicitToken: false, | ||
163 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
164 | }) | ||
165 | } | ||
166 | |||
167 | error (options: OverrideCommandOptions & ErrorRunnerJobBody & { jobUUID: string }) { | ||
168 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/error' | ||
169 | |||
170 | return this.postBodyRequest({ | ||
171 | ...options, | ||
172 | |||
173 | path, | ||
174 | fields: pick(options, [ 'message', 'jobToken', 'runnerToken' ]), | ||
175 | implicitToken: false, | ||
176 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
177 | }) | ||
178 | } | ||
179 | |||
180 | success (options: OverrideCommandOptions & RunnerJobSuccessBody & { jobUUID: string }) { | ||
181 | const { payload } = options | ||
182 | |||
183 | const path = '/api/v1/runners/jobs/' + options.jobUUID + '/success' | ||
184 | const attaches: { [id: string]: any } = {} | ||
185 | let payloadWithoutFiles = payload | ||
186 | |||
187 | if ((isWebVideoOrAudioMergeTranscodingPayloadSuccess(payload) || isHLSTranscodingPayloadSuccess(payload)) && payload.videoFile) { | ||
188 | attaches[`payload[videoFile]`] = payload.videoFile | ||
189 | |||
190 | payloadWithoutFiles = omit(payloadWithoutFiles as VODWebVideoTranscodingSuccess, [ 'videoFile' ]) | ||
191 | } | ||
192 | |||
193 | if (isHLSTranscodingPayloadSuccess(payload) && payload.resolutionPlaylistFile) { | ||
194 | attaches[`payload[resolutionPlaylistFile]`] = payload.resolutionPlaylistFile | ||
195 | |||
196 | payloadWithoutFiles = omit(payloadWithoutFiles as VODHLSTranscodingSuccess, [ 'resolutionPlaylistFile' ]) | ||
197 | } | ||
198 | |||
199 | return this.postUploadRequest({ | ||
200 | ...options, | ||
201 | |||
202 | path, | ||
203 | attaches, | ||
204 | fields: { | ||
205 | ...pick(options, [ 'jobToken', 'runnerToken' ]), | ||
206 | |||
207 | payload: payloadWithoutFiles | ||
208 | }, | ||
209 | implicitToken: false, | ||
210 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
211 | }) | ||
212 | } | ||
213 | |||
214 | getJobFile (options: OverrideCommandOptions & { url: string, jobToken: string, runnerToken: string }) { | ||
215 | const { host, protocol, pathname } = new URL(options.url) | ||
216 | |||
217 | return this.postBodyRequest({ | ||
218 | url: `${protocol}//${host}`, | ||
219 | path: pathname, | ||
220 | |||
221 | fields: pick(options, [ 'jobToken', 'runnerToken' ]), | ||
222 | implicitToken: false, | ||
223 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
224 | }) | ||
225 | } | ||
226 | |||
227 | // --------------------------------------------------------------------------- | ||
228 | |||
229 | async autoAccept (options: OverrideCommandOptions & RequestRunnerJobBody & { type?: RunnerJobType }) { | ||
230 | const { availableJobs } = await this.request(options) | ||
231 | |||
232 | const job = options.type | ||
233 | ? availableJobs.find(j => j.type === options.type) | ||
234 | : availableJobs[0] | ||
235 | |||
236 | return this.accept({ ...options, jobUUID: job.uuid }) | ||
237 | } | ||
238 | |||
239 | async autoProcessWebVideoJob (runnerToken: string, jobUUIDToProcess?: string) { | ||
240 | let jobUUID = jobUUIDToProcess | ||
241 | |||
242 | if (!jobUUID) { | ||
243 | const { availableJobs } = await this.request({ runnerToken }) | ||
244 | jobUUID = availableJobs[0].uuid | ||
245 | } | ||
246 | |||
247 | const { job } = await this.accept({ runnerToken, jobUUID }) | ||
248 | const jobToken = job.jobToken | ||
249 | |||
250 | const payload: RunnerJobSuccessPayload = { videoFile: 'video_short.mp4' } | ||
251 | await this.success({ runnerToken, jobUUID, jobToken, payload }) | ||
252 | |||
253 | await waitJobs([ this.server ]) | ||
254 | |||
255 | return job | ||
256 | } | ||
257 | |||
258 | async cancelAllJobs (options: { state?: RunnerJobStateType } = {}) { | ||
259 | const { state } = options | ||
260 | |||
261 | const { data } = await this.list({ count: 100 }) | ||
262 | |||
263 | const allowedStates = new Set<RunnerJobStateType>([ | ||
264 | RunnerJobState.PENDING, | ||
265 | RunnerJobState.PROCESSING, | ||
266 | RunnerJobState.WAITING_FOR_PARENT_JOB | ||
267 | ]) | ||
268 | |||
269 | for (const job of data) { | ||
270 | if (state && job.state.id !== state) continue | ||
271 | else if (allowedStates.has(job.state.id) !== true) continue | ||
272 | |||
273 | await this.cancelByAdmin({ jobUUID: job.uuid }) | ||
274 | } | ||
275 | } | ||
276 | |||
277 | async getJob (options: OverrideCommandOptions & { uuid: string }) { | ||
278 | const { data } = await this.list({ ...options, count: 100, sort: '-updatedAt' }) | ||
279 | |||
280 | return data.find(j => j.uuid === options.uuid) | ||
281 | } | ||
282 | |||
283 | async requestLiveJob (runnerToken: string) { | ||
284 | let availableJobs: RequestRunnerJobResult<RunnerJobLiveRTMPHLSTranscodingPayload>['availableJobs'] = [] | ||
285 | |||
286 | while (availableJobs.length === 0) { | ||
287 | const result = await this.requestLive({ runnerToken }) | ||
288 | availableJobs = result.availableJobs | ||
289 | |||
290 | if (availableJobs.length === 1) break | ||
291 | |||
292 | await wait(150) | ||
293 | } | ||
294 | |||
295 | return availableJobs[0] | ||
296 | } | ||
297 | } | ||
diff --git a/packages/server-commands/src/runners/runner-registration-tokens-command.ts b/packages/server-commands/src/runners/runner-registration-tokens-command.ts new file mode 100644 index 000000000..86b6e5f93 --- /dev/null +++ b/packages/server-commands/src/runners/runner-registration-tokens-command.ts | |||
@@ -0,0 +1,55 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { HttpStatusCode, ResultList, RunnerRegistrationToken } from '@peertube/peertube-models' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | export class RunnerRegistrationTokensCommand extends AbstractCommand { | ||
6 | |||
7 | list (options: OverrideCommandOptions & { | ||
8 | start?: number | ||
9 | count?: number | ||
10 | sort?: string | ||
11 | } = {}) { | ||
12 | const path = '/api/v1/runners/registration-tokens' | ||
13 | |||
14 | return this.getRequestBody<ResultList<RunnerRegistrationToken>>({ | ||
15 | ...options, | ||
16 | |||
17 | path, | ||
18 | query: pick(options, [ 'start', 'count', 'sort' ]), | ||
19 | implicitToken: true, | ||
20 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
21 | }) | ||
22 | } | ||
23 | |||
24 | generate (options: OverrideCommandOptions = {}) { | ||
25 | const path = '/api/v1/runners/registration-tokens/generate' | ||
26 | |||
27 | return this.postBodyRequest({ | ||
28 | ...options, | ||
29 | |||
30 | path, | ||
31 | implicitToken: true, | ||
32 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
33 | }) | ||
34 | } | ||
35 | |||
36 | delete (options: OverrideCommandOptions & { | ||
37 | id: number | ||
38 | }) { | ||
39 | const path = '/api/v1/runners/registration-tokens/' + options.id | ||
40 | |||
41 | return this.deleteRequest({ | ||
42 | ...options, | ||
43 | |||
44 | path, | ||
45 | implicitToken: true, | ||
46 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
47 | }) | ||
48 | } | ||
49 | |||
50 | async getFirstRegistrationToken (options: OverrideCommandOptions = {}) { | ||
51 | const { data } = await this.list(options) | ||
52 | |||
53 | return data[0].registrationToken | ||
54 | } | ||
55 | } | ||
diff --git a/packages/server-commands/src/runners/runners-command.ts b/packages/server-commands/src/runners/runners-command.ts new file mode 100644 index 000000000..376a1dff9 --- /dev/null +++ b/packages/server-commands/src/runners/runners-command.ts | |||
@@ -0,0 +1,85 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | HttpStatusCode, | ||
4 | RegisterRunnerBody, | ||
5 | RegisterRunnerResult, | ||
6 | ResultList, | ||
7 | Runner, | ||
8 | UnregisterRunnerBody | ||
9 | } from '@peertube/peertube-models' | ||
10 | import { buildUUID } from '@peertube/peertube-node-utils' | ||
11 | import { unwrapBody } from '../requests/index.js' | ||
12 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
13 | |||
14 | export class RunnersCommand extends AbstractCommand { | ||
15 | |||
16 | list (options: OverrideCommandOptions & { | ||
17 | start?: number | ||
18 | count?: number | ||
19 | sort?: string | ||
20 | } = {}) { | ||
21 | const path = '/api/v1/runners' | ||
22 | |||
23 | return this.getRequestBody<ResultList<Runner>>({ | ||
24 | ...options, | ||
25 | |||
26 | path, | ||
27 | query: pick(options, [ 'start', 'count', 'sort' ]), | ||
28 | implicitToken: true, | ||
29 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
30 | }) | ||
31 | } | ||
32 | |||
33 | register (options: OverrideCommandOptions & RegisterRunnerBody) { | ||
34 | const path = '/api/v1/runners/register' | ||
35 | |||
36 | return unwrapBody<RegisterRunnerResult>(this.postBodyRequest({ | ||
37 | ...options, | ||
38 | |||
39 | path, | ||
40 | fields: pick(options, [ 'name', 'registrationToken', 'description' ]), | ||
41 | implicitToken: true, | ||
42 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
43 | })) | ||
44 | } | ||
45 | |||
46 | unregister (options: OverrideCommandOptions & UnregisterRunnerBody) { | ||
47 | const path = '/api/v1/runners/unregister' | ||
48 | |||
49 | return this.postBodyRequest({ | ||
50 | ...options, | ||
51 | |||
52 | path, | ||
53 | fields: pick(options, [ 'runnerToken' ]), | ||
54 | implicitToken: false, | ||
55 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
56 | }) | ||
57 | } | ||
58 | |||
59 | delete (options: OverrideCommandOptions & { | ||
60 | id: number | ||
61 | }) { | ||
62 | const path = '/api/v1/runners/' + options.id | ||
63 | |||
64 | return this.deleteRequest({ | ||
65 | ...options, | ||
66 | |||
67 | path, | ||
68 | implicitToken: true, | ||
69 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
70 | }) | ||
71 | } | ||
72 | |||
73 | // --------------------------------------------------------------------------- | ||
74 | |||
75 | async autoRegisterRunner () { | ||
76 | const { data } = await this.server.runnerRegistrationTokens.list({ sort: 'createdAt' }) | ||
77 | |||
78 | const { runnerToken } = await this.register({ | ||
79 | name: 'runner ' + buildUUID(), | ||
80 | registrationToken: data[0].registrationToken | ||
81 | }) | ||
82 | |||
83 | return runnerToken | ||
84 | } | ||
85 | } | ||
diff --git a/packages/server-commands/src/search/index.ts b/packages/server-commands/src/search/index.ts new file mode 100644 index 000000000..ca56fc669 --- /dev/null +++ b/packages/server-commands/src/search/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './search-command.js' | |||
diff --git a/packages/server-commands/src/search/search-command.ts b/packages/server-commands/src/search/search-command.ts new file mode 100644 index 000000000..e766a2861 --- /dev/null +++ b/packages/server-commands/src/search/search-command.ts | |||
@@ -0,0 +1,98 @@ | |||
1 | import { | ||
2 | HttpStatusCode, | ||
3 | ResultList, | ||
4 | Video, | ||
5 | VideoChannel, | ||
6 | VideoChannelsSearchQuery, | ||
7 | VideoPlaylist, | ||
8 | VideoPlaylistsSearchQuery, | ||
9 | VideosSearchQuery | ||
10 | } from '@peertube/peertube-models' | ||
11 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
12 | |||
13 | export class SearchCommand extends AbstractCommand { | ||
14 | |||
15 | searchChannels (options: OverrideCommandOptions & { | ||
16 | search: string | ||
17 | }) { | ||
18 | return this.advancedChannelSearch({ | ||
19 | ...options, | ||
20 | |||
21 | search: { search: options.search } | ||
22 | }) | ||
23 | } | ||
24 | |||
25 | advancedChannelSearch (options: OverrideCommandOptions & { | ||
26 | search: VideoChannelsSearchQuery | ||
27 | }) { | ||
28 | const { search } = options | ||
29 | const path = '/api/v1/search/video-channels' | ||
30 | |||
31 | return this.getRequestBody<ResultList<VideoChannel>>({ | ||
32 | ...options, | ||
33 | |||
34 | path, | ||
35 | query: search, | ||
36 | implicitToken: false, | ||
37 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | searchPlaylists (options: OverrideCommandOptions & { | ||
42 | search: string | ||
43 | }) { | ||
44 | return this.advancedPlaylistSearch({ | ||
45 | ...options, | ||
46 | |||
47 | search: { search: options.search } | ||
48 | }) | ||
49 | } | ||
50 | |||
51 | advancedPlaylistSearch (options: OverrideCommandOptions & { | ||
52 | search: VideoPlaylistsSearchQuery | ||
53 | }) { | ||
54 | const { search } = options | ||
55 | const path = '/api/v1/search/video-playlists' | ||
56 | |||
57 | return this.getRequestBody<ResultList<VideoPlaylist>>({ | ||
58 | ...options, | ||
59 | |||
60 | path, | ||
61 | query: search, | ||
62 | implicitToken: false, | ||
63 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
64 | }) | ||
65 | } | ||
66 | |||
67 | searchVideos (options: OverrideCommandOptions & { | ||
68 | search: string | ||
69 | sort?: string | ||
70 | }) { | ||
71 | const { search, sort } = options | ||
72 | |||
73 | return this.advancedVideoSearch({ | ||
74 | ...options, | ||
75 | |||
76 | search: { | ||
77 | search, | ||
78 | sort: sort ?? '-publishedAt' | ||
79 | } | ||
80 | }) | ||
81 | } | ||
82 | |||
83 | advancedVideoSearch (options: OverrideCommandOptions & { | ||
84 | search: VideosSearchQuery | ||
85 | }) { | ||
86 | const { search } = options | ||
87 | const path = '/api/v1/search/videos' | ||
88 | |||
89 | return this.getRequestBody<ResultList<Video>>({ | ||
90 | ...options, | ||
91 | |||
92 | path, | ||
93 | query: search, | ||
94 | implicitToken: false, | ||
95 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
96 | }) | ||
97 | } | ||
98 | } | ||
diff --git a/packages/server-commands/src/server/config-command.ts b/packages/server-commands/src/server/config-command.ts new file mode 100644 index 000000000..8fcf0bd51 --- /dev/null +++ b/packages/server-commands/src/server/config-command.ts | |||
@@ -0,0 +1,576 @@ | |||
1 | import merge from 'lodash-es/merge.js' | ||
2 | import { About, CustomConfig, HttpStatusCode, ServerConfig } from '@peertube/peertube-models' | ||
3 | import { DeepPartial } from '@peertube/peertube-typescript-utils' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/abstract-command.js' | ||
5 | |||
6 | export class ConfigCommand extends AbstractCommand { | ||
7 | |||
8 | static getCustomConfigResolutions (enabled: boolean, with0p = false) { | ||
9 | return { | ||
10 | '0p': enabled && with0p, | ||
11 | '144p': enabled, | ||
12 | '240p': enabled, | ||
13 | '360p': enabled, | ||
14 | '480p': enabled, | ||
15 | '720p': enabled, | ||
16 | '1080p': enabled, | ||
17 | '1440p': enabled, | ||
18 | '2160p': enabled | ||
19 | } | ||
20 | } | ||
21 | |||
22 | // --------------------------------------------------------------------------- | ||
23 | |||
24 | static getEmailOverrideConfig (emailPort: number) { | ||
25 | return { | ||
26 | smtp: { | ||
27 | hostname: '127.0.0.1', | ||
28 | port: emailPort | ||
29 | } | ||
30 | } | ||
31 | } | ||
32 | |||
33 | // --------------------------------------------------------------------------- | ||
34 | |||
35 | enableSignup (requiresApproval: boolean, limit = -1) { | ||
36 | return this.updateExistingSubConfig({ | ||
37 | newConfig: { | ||
38 | signup: { | ||
39 | enabled: true, | ||
40 | requiresApproval, | ||
41 | limit | ||
42 | } | ||
43 | } | ||
44 | }) | ||
45 | } | ||
46 | |||
47 | // --------------------------------------------------------------------------- | ||
48 | |||
49 | disableImports () { | ||
50 | return this.setImportsEnabled(false) | ||
51 | } | ||
52 | |||
53 | enableImports () { | ||
54 | return this.setImportsEnabled(true) | ||
55 | } | ||
56 | |||
57 | private setImportsEnabled (enabled: boolean) { | ||
58 | return this.updateExistingSubConfig({ | ||
59 | newConfig: { | ||
60 | import: { | ||
61 | videos: { | ||
62 | http: { | ||
63 | enabled | ||
64 | }, | ||
65 | |||
66 | torrent: { | ||
67 | enabled | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 | } | ||
72 | }) | ||
73 | } | ||
74 | |||
75 | // --------------------------------------------------------------------------- | ||
76 | |||
77 | disableFileUpdate () { | ||
78 | return this.setFileUpdateEnabled(false) | ||
79 | } | ||
80 | |||
81 | enableFileUpdate () { | ||
82 | return this.setFileUpdateEnabled(true) | ||
83 | } | ||
84 | |||
85 | private setFileUpdateEnabled (enabled: boolean) { | ||
86 | return this.updateExistingSubConfig({ | ||
87 | newConfig: { | ||
88 | videoFile: { | ||
89 | update: { | ||
90 | enabled | ||
91 | } | ||
92 | } | ||
93 | } | ||
94 | }) | ||
95 | } | ||
96 | |||
97 | // --------------------------------------------------------------------------- | ||
98 | |||
99 | enableChannelSync () { | ||
100 | return this.setChannelSyncEnabled(true) | ||
101 | } | ||
102 | |||
103 | disableChannelSync () { | ||
104 | return this.setChannelSyncEnabled(false) | ||
105 | } | ||
106 | |||
107 | private setChannelSyncEnabled (enabled: boolean) { | ||
108 | return this.updateExistingSubConfig({ | ||
109 | newConfig: { | ||
110 | import: { | ||
111 | videoChannelSynchronization: { | ||
112 | enabled | ||
113 | } | ||
114 | } | ||
115 | } | ||
116 | }) | ||
117 | } | ||
118 | |||
119 | // --------------------------------------------------------------------------- | ||
120 | |||
121 | enableLive (options: { | ||
122 | allowReplay?: boolean | ||
123 | transcoding?: boolean | ||
124 | resolutions?: 'min' | 'max' // Default max | ||
125 | } = {}) { | ||
126 | const { allowReplay, transcoding, resolutions = 'max' } = options | ||
127 | |||
128 | return this.updateExistingSubConfig({ | ||
129 | newConfig: { | ||
130 | live: { | ||
131 | enabled: true, | ||
132 | allowReplay: allowReplay ?? true, | ||
133 | transcoding: { | ||
134 | enabled: transcoding ?? true, | ||
135 | resolutions: ConfigCommand.getCustomConfigResolutions(resolutions === 'max') | ||
136 | } | ||
137 | } | ||
138 | } | ||
139 | }) | ||
140 | } | ||
141 | |||
142 | disableTranscoding () { | ||
143 | return this.updateExistingSubConfig({ | ||
144 | newConfig: { | ||
145 | transcoding: { | ||
146 | enabled: false | ||
147 | }, | ||
148 | videoStudio: { | ||
149 | enabled: false | ||
150 | } | ||
151 | } | ||
152 | }) | ||
153 | } | ||
154 | |||
155 | enableTranscoding (options: { | ||
156 | webVideo?: boolean // default true | ||
157 | hls?: boolean // default true | ||
158 | with0p?: boolean // default false | ||
159 | } = {}) { | ||
160 | const { webVideo = true, hls = true, with0p = false } = options | ||
161 | |||
162 | return this.updateExistingSubConfig({ | ||
163 | newConfig: { | ||
164 | transcoding: { | ||
165 | enabled: true, | ||
166 | |||
167 | allowAudioFiles: true, | ||
168 | allowAdditionalExtensions: true, | ||
169 | |||
170 | resolutions: ConfigCommand.getCustomConfigResolutions(true, with0p), | ||
171 | |||
172 | webVideos: { | ||
173 | enabled: webVideo | ||
174 | }, | ||
175 | hls: { | ||
176 | enabled: hls | ||
177 | } | ||
178 | } | ||
179 | } | ||
180 | }) | ||
181 | } | ||
182 | |||
183 | enableMinimumTranscoding (options: { | ||
184 | webVideo?: boolean // default true | ||
185 | hls?: boolean // default true | ||
186 | } = {}) { | ||
187 | const { webVideo = true, hls = true } = options | ||
188 | |||
189 | return this.updateExistingSubConfig({ | ||
190 | newConfig: { | ||
191 | transcoding: { | ||
192 | enabled: true, | ||
193 | |||
194 | allowAudioFiles: true, | ||
195 | allowAdditionalExtensions: true, | ||
196 | |||
197 | resolutions: { | ||
198 | ...ConfigCommand.getCustomConfigResolutions(false), | ||
199 | |||
200 | '240p': true | ||
201 | }, | ||
202 | |||
203 | webVideos: { | ||
204 | enabled: webVideo | ||
205 | }, | ||
206 | hls: { | ||
207 | enabled: hls | ||
208 | } | ||
209 | } | ||
210 | } | ||
211 | }) | ||
212 | } | ||
213 | |||
214 | enableRemoteTranscoding () { | ||
215 | return this.updateExistingSubConfig({ | ||
216 | newConfig: { | ||
217 | transcoding: { | ||
218 | remoteRunners: { | ||
219 | enabled: true | ||
220 | } | ||
221 | }, | ||
222 | live: { | ||
223 | transcoding: { | ||
224 | remoteRunners: { | ||
225 | enabled: true | ||
226 | } | ||
227 | } | ||
228 | } | ||
229 | } | ||
230 | }) | ||
231 | } | ||
232 | |||
233 | enableRemoteStudio () { | ||
234 | return this.updateExistingSubConfig({ | ||
235 | newConfig: { | ||
236 | videoStudio: { | ||
237 | remoteRunners: { | ||
238 | enabled: true | ||
239 | } | ||
240 | } | ||
241 | } | ||
242 | }) | ||
243 | } | ||
244 | |||
245 | // --------------------------------------------------------------------------- | ||
246 | |||
247 | enableStudio () { | ||
248 | return this.updateExistingSubConfig({ | ||
249 | newConfig: { | ||
250 | videoStudio: { | ||
251 | enabled: true | ||
252 | } | ||
253 | } | ||
254 | }) | ||
255 | } | ||
256 | |||
257 | // --------------------------------------------------------------------------- | ||
258 | |||
259 | getConfig (options: OverrideCommandOptions = {}) { | ||
260 | const path = '/api/v1/config' | ||
261 | |||
262 | return this.getRequestBody<ServerConfig>({ | ||
263 | ...options, | ||
264 | |||
265 | path, | ||
266 | implicitToken: false, | ||
267 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
268 | }) | ||
269 | } | ||
270 | |||
271 | async getIndexHTMLConfig (options: OverrideCommandOptions = {}) { | ||
272 | const text = await this.getRequestText({ | ||
273 | ...options, | ||
274 | |||
275 | path: '/', | ||
276 | implicitToken: false, | ||
277 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
278 | }) | ||
279 | |||
280 | const match = text.match('<script type="application/javascript">window.PeerTubeServerConfig = (".+?")</script>') | ||
281 | |||
282 | // We parse the string twice, first to extract the string and then to extract the JSON | ||
283 | return JSON.parse(JSON.parse(match[1])) as ServerConfig | ||
284 | } | ||
285 | |||
286 | getAbout (options: OverrideCommandOptions = {}) { | ||
287 | const path = '/api/v1/config/about' | ||
288 | |||
289 | return this.getRequestBody<About>({ | ||
290 | ...options, | ||
291 | |||
292 | path, | ||
293 | implicitToken: false, | ||
294 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
295 | }) | ||
296 | } | ||
297 | |||
298 | getCustomConfig (options: OverrideCommandOptions = {}) { | ||
299 | const path = '/api/v1/config/custom' | ||
300 | |||
301 | return this.getRequestBody<CustomConfig>({ | ||
302 | ...options, | ||
303 | |||
304 | path, | ||
305 | implicitToken: true, | ||
306 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
307 | }) | ||
308 | } | ||
309 | |||
310 | updateCustomConfig (options: OverrideCommandOptions & { | ||
311 | newCustomConfig: CustomConfig | ||
312 | }) { | ||
313 | const path = '/api/v1/config/custom' | ||
314 | |||
315 | return this.putBodyRequest({ | ||
316 | ...options, | ||
317 | |||
318 | path, | ||
319 | fields: options.newCustomConfig, | ||
320 | implicitToken: true, | ||
321 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
322 | }) | ||
323 | } | ||
324 | |||
325 | deleteCustomConfig (options: OverrideCommandOptions = {}) { | ||
326 | const path = '/api/v1/config/custom' | ||
327 | |||
328 | return this.deleteRequest({ | ||
329 | ...options, | ||
330 | |||
331 | path, | ||
332 | implicitToken: true, | ||
333 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
334 | }) | ||
335 | } | ||
336 | |||
337 | async updateExistingSubConfig (options: OverrideCommandOptions & { | ||
338 | newConfig: DeepPartial<CustomConfig> | ||
339 | }) { | ||
340 | const existing = await this.getCustomConfig({ ...options, expectedStatus: HttpStatusCode.OK_200 }) | ||
341 | |||
342 | return this.updateCustomConfig({ ...options, newCustomConfig: merge({}, existing, options.newConfig) }) | ||
343 | } | ||
344 | |||
345 | updateCustomSubConfig (options: OverrideCommandOptions & { | ||
346 | newConfig: DeepPartial<CustomConfig> | ||
347 | }) { | ||
348 | const newCustomConfig: CustomConfig = { | ||
349 | instance: { | ||
350 | name: 'PeerTube updated', | ||
351 | shortDescription: 'my short description', | ||
352 | description: 'my super description', | ||
353 | terms: 'my super terms', | ||
354 | codeOfConduct: 'my super coc', | ||
355 | |||
356 | creationReason: 'my super creation reason', | ||
357 | moderationInformation: 'my super moderation information', | ||
358 | administrator: 'Kuja', | ||
359 | maintenanceLifetime: 'forever', | ||
360 | businessModel: 'my super business model', | ||
361 | hardwareInformation: '2vCore 3GB RAM', | ||
362 | |||
363 | languages: [ 'en', 'es' ], | ||
364 | categories: [ 1, 2 ], | ||
365 | |||
366 | isNSFW: true, | ||
367 | defaultNSFWPolicy: 'blur', | ||
368 | |||
369 | defaultClientRoute: '/videos/recently-added', | ||
370 | |||
371 | customizations: { | ||
372 | javascript: 'alert("coucou")', | ||
373 | css: 'body { background-color: red; }' | ||
374 | } | ||
375 | }, | ||
376 | theme: { | ||
377 | default: 'default' | ||
378 | }, | ||
379 | services: { | ||
380 | twitter: { | ||
381 | username: '@MySuperUsername', | ||
382 | whitelisted: true | ||
383 | } | ||
384 | }, | ||
385 | client: { | ||
386 | videos: { | ||
387 | miniature: { | ||
388 | preferAuthorDisplayName: false | ||
389 | } | ||
390 | }, | ||
391 | menu: { | ||
392 | login: { | ||
393 | redirectOnSingleExternalAuth: false | ||
394 | } | ||
395 | } | ||
396 | }, | ||
397 | cache: { | ||
398 | previews: { | ||
399 | size: 2 | ||
400 | }, | ||
401 | captions: { | ||
402 | size: 3 | ||
403 | }, | ||
404 | torrents: { | ||
405 | size: 4 | ||
406 | }, | ||
407 | storyboards: { | ||
408 | size: 5 | ||
409 | } | ||
410 | }, | ||
411 | signup: { | ||
412 | enabled: false, | ||
413 | limit: 5, | ||
414 | requiresApproval: true, | ||
415 | requiresEmailVerification: false, | ||
416 | minimumAge: 16 | ||
417 | }, | ||
418 | admin: { | ||
419 | email: 'superadmin1@example.com' | ||
420 | }, | ||
421 | contactForm: { | ||
422 | enabled: true | ||
423 | }, | ||
424 | user: { | ||
425 | history: { | ||
426 | videos: { | ||
427 | enabled: true | ||
428 | } | ||
429 | }, | ||
430 | videoQuota: 5242881, | ||
431 | videoQuotaDaily: 318742 | ||
432 | }, | ||
433 | videoChannels: { | ||
434 | maxPerUser: 20 | ||
435 | }, | ||
436 | transcoding: { | ||
437 | enabled: true, | ||
438 | remoteRunners: { | ||
439 | enabled: false | ||
440 | }, | ||
441 | allowAdditionalExtensions: true, | ||
442 | allowAudioFiles: true, | ||
443 | threads: 1, | ||
444 | concurrency: 3, | ||
445 | profile: 'default', | ||
446 | resolutions: { | ||
447 | '0p': false, | ||
448 | '144p': false, | ||
449 | '240p': false, | ||
450 | '360p': true, | ||
451 | '480p': true, | ||
452 | '720p': false, | ||
453 | '1080p': false, | ||
454 | '1440p': false, | ||
455 | '2160p': false | ||
456 | }, | ||
457 | alwaysTranscodeOriginalResolution: true, | ||
458 | webVideos: { | ||
459 | enabled: true | ||
460 | }, | ||
461 | hls: { | ||
462 | enabled: false | ||
463 | } | ||
464 | }, | ||
465 | live: { | ||
466 | enabled: true, | ||
467 | allowReplay: false, | ||
468 | latencySetting: { | ||
469 | enabled: false | ||
470 | }, | ||
471 | maxDuration: -1, | ||
472 | maxInstanceLives: -1, | ||
473 | maxUserLives: 50, | ||
474 | transcoding: { | ||
475 | enabled: true, | ||
476 | remoteRunners: { | ||
477 | enabled: false | ||
478 | }, | ||
479 | threads: 4, | ||
480 | profile: 'default', | ||
481 | resolutions: { | ||
482 | '144p': true, | ||
483 | '240p': true, | ||
484 | '360p': true, | ||
485 | '480p': true, | ||
486 | '720p': true, | ||
487 | '1080p': true, | ||
488 | '1440p': true, | ||
489 | '2160p': true | ||
490 | }, | ||
491 | alwaysTranscodeOriginalResolution: true | ||
492 | } | ||
493 | }, | ||
494 | videoStudio: { | ||
495 | enabled: false, | ||
496 | remoteRunners: { | ||
497 | enabled: false | ||
498 | } | ||
499 | }, | ||
500 | videoFile: { | ||
501 | update: { | ||
502 | enabled: false | ||
503 | } | ||
504 | }, | ||
505 | import: { | ||
506 | videos: { | ||
507 | concurrency: 3, | ||
508 | http: { | ||
509 | enabled: false | ||
510 | }, | ||
511 | torrent: { | ||
512 | enabled: false | ||
513 | } | ||
514 | }, | ||
515 | videoChannelSynchronization: { | ||
516 | enabled: false, | ||
517 | maxPerUser: 10 | ||
518 | } | ||
519 | }, | ||
520 | trending: { | ||
521 | videos: { | ||
522 | algorithms: { | ||
523 | enabled: [ 'hot', 'most-viewed', 'most-liked' ], | ||
524 | default: 'hot' | ||
525 | } | ||
526 | } | ||
527 | }, | ||
528 | autoBlacklist: { | ||
529 | videos: { | ||
530 | ofUsers: { | ||
531 | enabled: false | ||
532 | } | ||
533 | } | ||
534 | }, | ||
535 | followers: { | ||
536 | instance: { | ||
537 | enabled: true, | ||
538 | manualApproval: false | ||
539 | } | ||
540 | }, | ||
541 | followings: { | ||
542 | instance: { | ||
543 | autoFollowBack: { | ||
544 | enabled: false | ||
545 | }, | ||
546 | autoFollowIndex: { | ||
547 | indexUrl: 'https://instances.joinpeertube.org/api/v1/instances/hosts', | ||
548 | enabled: false | ||
549 | } | ||
550 | } | ||
551 | }, | ||
552 | broadcastMessage: { | ||
553 | enabled: true, | ||
554 | level: 'warning', | ||
555 | message: 'hello', | ||
556 | dismissable: true | ||
557 | }, | ||
558 | search: { | ||
559 | remoteUri: { | ||
560 | users: true, | ||
561 | anonymous: true | ||
562 | }, | ||
563 | searchIndex: { | ||
564 | enabled: true, | ||
565 | url: 'https://search.joinpeertube.org', | ||
566 | disableLocalSearch: true, | ||
567 | isDefaultSearch: true | ||
568 | } | ||
569 | } | ||
570 | } | ||
571 | |||
572 | merge(newCustomConfig, options.newConfig) | ||
573 | |||
574 | return this.updateCustomConfig({ ...options, newCustomConfig }) | ||
575 | } | ||
576 | } | ||
diff --git a/packages/server-commands/src/server/contact-form-command.ts b/packages/server-commands/src/server/contact-form-command.ts new file mode 100644 index 000000000..399e06d2f --- /dev/null +++ b/packages/server-commands/src/server/contact-form-command.ts | |||
@@ -0,0 +1,30 @@ | |||
1 | import { ContactForm, HttpStatusCode } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class ContactFormCommand extends AbstractCommand { | ||
5 | |||
6 | send (options: OverrideCommandOptions & { | ||
7 | fromEmail: string | ||
8 | fromName: string | ||
9 | subject: string | ||
10 | body: string | ||
11 | }) { | ||
12 | const path = '/api/v1/server/contact' | ||
13 | |||
14 | const body: ContactForm = { | ||
15 | fromEmail: options.fromEmail, | ||
16 | fromName: options.fromName, | ||
17 | subject: options.subject, | ||
18 | body: options.body | ||
19 | } | ||
20 | |||
21 | return this.postBodyRequest({ | ||
22 | ...options, | ||
23 | |||
24 | path, | ||
25 | fields: body, | ||
26 | implicitToken: false, | ||
27 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
28 | }) | ||
29 | } | ||
30 | } | ||
diff --git a/packages/server-commands/src/server/debug-command.ts b/packages/server-commands/src/server/debug-command.ts new file mode 100644 index 000000000..9bb7fda10 --- /dev/null +++ b/packages/server-commands/src/server/debug-command.ts | |||
@@ -0,0 +1,33 @@ | |||
1 | import { Debug, HttpStatusCode, SendDebugCommand } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class DebugCommand extends AbstractCommand { | ||
5 | |||
6 | getDebug (options: OverrideCommandOptions = {}) { | ||
7 | const path = '/api/v1/server/debug' | ||
8 | |||
9 | return this.getRequestBody<Debug>({ | ||
10 | ...options, | ||
11 | |||
12 | path, | ||
13 | implicitToken: true, | ||
14 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
15 | }) | ||
16 | } | ||
17 | |||
18 | sendCommand (options: OverrideCommandOptions & { | ||
19 | body: SendDebugCommand | ||
20 | }) { | ||
21 | const { body } = options | ||
22 | const path = '/api/v1/server/debug/run-command' | ||
23 | |||
24 | return this.postBodyRequest({ | ||
25 | ...options, | ||
26 | |||
27 | path, | ||
28 | fields: body, | ||
29 | implicitToken: true, | ||
30 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
31 | }) | ||
32 | } | ||
33 | } | ||
diff --git a/packages/server-commands/src/server/follows-command.ts b/packages/server-commands/src/server/follows-command.ts new file mode 100644 index 000000000..cdc263982 --- /dev/null +++ b/packages/server-commands/src/server/follows-command.ts | |||
@@ -0,0 +1,139 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList, ServerFollowCreate } from '@peertube/peertube-models' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | import { PeerTubeServer } from './server.js' | ||
5 | |||
6 | export class FollowsCommand extends AbstractCommand { | ||
7 | |||
8 | getFollowers (options: OverrideCommandOptions & { | ||
9 | start?: number | ||
10 | count?: number | ||
11 | sort?: string | ||
12 | search?: string | ||
13 | actorType?: ActivityPubActorType | ||
14 | state?: FollowState | ||
15 | } = {}) { | ||
16 | const path = '/api/v1/server/followers' | ||
17 | |||
18 | const query = pick(options, [ 'start', 'count', 'sort', 'search', 'state', 'actorType' ]) | ||
19 | |||
20 | return this.getRequestBody<ResultList<ActorFollow>>({ | ||
21 | ...options, | ||
22 | |||
23 | path, | ||
24 | query, | ||
25 | implicitToken: false, | ||
26 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
27 | }) | ||
28 | } | ||
29 | |||
30 | getFollowings (options: OverrideCommandOptions & { | ||
31 | start?: number | ||
32 | count?: number | ||
33 | sort?: string | ||
34 | search?: string | ||
35 | actorType?: ActivityPubActorType | ||
36 | state?: FollowState | ||
37 | } = {}) { | ||
38 | const path = '/api/v1/server/following' | ||
39 | |||
40 | const query = pick(options, [ 'start', 'count', 'sort', 'search', 'state', 'actorType' ]) | ||
41 | |||
42 | return this.getRequestBody<ResultList<ActorFollow>>({ | ||
43 | ...options, | ||
44 | |||
45 | path, | ||
46 | query, | ||
47 | implicitToken: false, | ||
48 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
49 | }) | ||
50 | } | ||
51 | |||
52 | follow (options: OverrideCommandOptions & { | ||
53 | hosts?: string[] | ||
54 | handles?: string[] | ||
55 | }) { | ||
56 | const path = '/api/v1/server/following' | ||
57 | |||
58 | const fields: ServerFollowCreate = {} | ||
59 | |||
60 | if (options.hosts) { | ||
61 | fields.hosts = options.hosts.map(f => f.replace(/^http:\/\//, '')) | ||
62 | } | ||
63 | |||
64 | if (options.handles) { | ||
65 | fields.handles = options.handles | ||
66 | } | ||
67 | |||
68 | return this.postBodyRequest({ | ||
69 | ...options, | ||
70 | |||
71 | path, | ||
72 | fields, | ||
73 | implicitToken: true, | ||
74 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
75 | }) | ||
76 | } | ||
77 | |||
78 | async unfollow (options: OverrideCommandOptions & { | ||
79 | target: PeerTubeServer | string | ||
80 | }) { | ||
81 | const { target } = options | ||
82 | |||
83 | const handle = typeof target === 'string' | ||
84 | ? target | ||
85 | : target.host | ||
86 | |||
87 | const path = '/api/v1/server/following/' + handle | ||
88 | |||
89 | return this.deleteRequest({ | ||
90 | ...options, | ||
91 | |||
92 | path, | ||
93 | implicitToken: true, | ||
94 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
95 | }) | ||
96 | } | ||
97 | |||
98 | acceptFollower (options: OverrideCommandOptions & { | ||
99 | follower: string | ||
100 | }) { | ||
101 | const path = '/api/v1/server/followers/' + options.follower + '/accept' | ||
102 | |||
103 | return this.postBodyRequest({ | ||
104 | ...options, | ||
105 | |||
106 | path, | ||
107 | implicitToken: true, | ||
108 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
109 | }) | ||
110 | } | ||
111 | |||
112 | rejectFollower (options: OverrideCommandOptions & { | ||
113 | follower: string | ||
114 | }) { | ||
115 | const path = '/api/v1/server/followers/' + options.follower + '/reject' | ||
116 | |||
117 | return this.postBodyRequest({ | ||
118 | ...options, | ||
119 | |||
120 | path, | ||
121 | implicitToken: true, | ||
122 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
123 | }) | ||
124 | } | ||
125 | |||
126 | removeFollower (options: OverrideCommandOptions & { | ||
127 | follower: PeerTubeServer | ||
128 | }) { | ||
129 | const path = '/api/v1/server/followers/peertube@' + options.follower.host | ||
130 | |||
131 | return this.deleteRequest({ | ||
132 | ...options, | ||
133 | |||
134 | path, | ||
135 | implicitToken: true, | ||
136 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
137 | }) | ||
138 | } | ||
139 | } | ||
diff --git a/packages/server-commands/src/server/follows.ts b/packages/server-commands/src/server/follows.ts new file mode 100644 index 000000000..32304495a --- /dev/null +++ b/packages/server-commands/src/server/follows.ts | |||
@@ -0,0 +1,20 @@ | |||
1 | import { waitJobs } from './jobs.js' | ||
2 | import { PeerTubeServer } from './server.js' | ||
3 | |||
4 | async function doubleFollow (server1: PeerTubeServer, server2: PeerTubeServer) { | ||
5 | await Promise.all([ | ||
6 | server1.follows.follow({ hosts: [ server2.url ] }), | ||
7 | server2.follows.follow({ hosts: [ server1.url ] }) | ||
8 | ]) | ||
9 | |||
10 | // Wait request propagation | ||
11 | await waitJobs([ server1, server2 ]) | ||
12 | |||
13 | return true | ||
14 | } | ||
15 | |||
16 | // --------------------------------------------------------------------------- | ||
17 | |||
18 | export { | ||
19 | doubleFollow | ||
20 | } | ||
diff --git a/packages/server-commands/src/server/index.ts b/packages/server-commands/src/server/index.ts new file mode 100644 index 000000000..c13972eca --- /dev/null +++ b/packages/server-commands/src/server/index.ts | |||
@@ -0,0 +1,15 @@ | |||
1 | export * from './config-command.js' | ||
2 | export * from './contact-form-command.js' | ||
3 | export * from './debug-command.js' | ||
4 | export * from './follows-command.js' | ||
5 | export * from './follows.js' | ||
6 | export * from './jobs.js' | ||
7 | export * from './jobs-command.js' | ||
8 | export * from './metrics-command.js' | ||
9 | export * from './object-storage-command.js' | ||
10 | export * from './plugins-command.js' | ||
11 | export * from './redundancy-command.js' | ||
12 | export * from './server.js' | ||
13 | export * from './servers-command.js' | ||
14 | export * from './servers.js' | ||
15 | export * from './stats-command.js' | ||
diff --git a/packages/server-commands/src/server/jobs-command.ts b/packages/server-commands/src/server/jobs-command.ts new file mode 100644 index 000000000..18aa0cd95 --- /dev/null +++ b/packages/server-commands/src/server/jobs-command.ts | |||
@@ -0,0 +1,84 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { HttpStatusCode, Job, JobState, JobType, ResultList } from '@peertube/peertube-models' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | export class JobsCommand extends AbstractCommand { | ||
6 | |||
7 | async getLatest (options: OverrideCommandOptions & { | ||
8 | jobType: JobType | ||
9 | }) { | ||
10 | const { data } = await this.list({ ...options, start: 0, count: 1, sort: '-createdAt' }) | ||
11 | |||
12 | if (data.length === 0) return undefined | ||
13 | |||
14 | return data[0] | ||
15 | } | ||
16 | |||
17 | pauseJobQueue (options: OverrideCommandOptions = {}) { | ||
18 | const path = '/api/v1/jobs/pause' | ||
19 | |||
20 | return this.postBodyRequest({ | ||
21 | ...options, | ||
22 | |||
23 | path, | ||
24 | implicitToken: true, | ||
25 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
26 | }) | ||
27 | } | ||
28 | |||
29 | resumeJobQueue (options: OverrideCommandOptions = {}) { | ||
30 | const path = '/api/v1/jobs/resume' | ||
31 | |||
32 | return this.postBodyRequest({ | ||
33 | ...options, | ||
34 | |||
35 | path, | ||
36 | implicitToken: true, | ||
37 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | list (options: OverrideCommandOptions & { | ||
42 | state?: JobState | ||
43 | jobType?: JobType | ||
44 | start?: number | ||
45 | count?: number | ||
46 | sort?: string | ||
47 | } = {}) { | ||
48 | const path = this.buildJobsUrl(options.state) | ||
49 | |||
50 | const query = pick(options, [ 'start', 'count', 'sort', 'jobType' ]) | ||
51 | |||
52 | return this.getRequestBody<ResultList<Job>>({ | ||
53 | ...options, | ||
54 | |||
55 | path, | ||
56 | query, | ||
57 | implicitToken: true, | ||
58 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
59 | }) | ||
60 | } | ||
61 | |||
62 | listFailed (options: OverrideCommandOptions & { | ||
63 | jobType?: JobType | ||
64 | }) { | ||
65 | const path = this.buildJobsUrl('failed') | ||
66 | |||
67 | return this.getRequestBody<ResultList<Job>>({ | ||
68 | ...options, | ||
69 | |||
70 | path, | ||
71 | query: { start: 0, count: 50 }, | ||
72 | implicitToken: true, | ||
73 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
74 | }) | ||
75 | } | ||
76 | |||
77 | private buildJobsUrl (state?: JobState) { | ||
78 | let path = '/api/v1/jobs' | ||
79 | |||
80 | if (state) path += '/' + state | ||
81 | |||
82 | return path | ||
83 | } | ||
84 | } | ||
diff --git a/packages/server-commands/src/server/jobs.ts b/packages/server-commands/src/server/jobs.ts new file mode 100644 index 000000000..1f3b1f745 --- /dev/null +++ b/packages/server-commands/src/server/jobs.ts | |||
@@ -0,0 +1,117 @@ | |||
1 | import { expect } from 'chai' | ||
2 | import { wait } from '@peertube/peertube-core-utils' | ||
3 | import { JobState, JobType, RunnerJobState } from '@peertube/peertube-models' | ||
4 | import { PeerTubeServer } from './server.js' | ||
5 | |||
6 | async function waitJobs ( | ||
7 | serversArg: PeerTubeServer[] | PeerTubeServer, | ||
8 | options: { | ||
9 | skipDelayed?: boolean // default false | ||
10 | runnerJobs?: boolean // default false | ||
11 | } = {} | ||
12 | ) { | ||
13 | const { skipDelayed = false, runnerJobs = false } = options | ||
14 | |||
15 | const pendingJobWait = process.env.NODE_PENDING_JOB_WAIT | ||
16 | ? parseInt(process.env.NODE_PENDING_JOB_WAIT, 10) | ||
17 | : 250 | ||
18 | |||
19 | let servers: PeerTubeServer[] | ||
20 | |||
21 | if (Array.isArray(serversArg) === false) servers = [ serversArg as PeerTubeServer ] | ||
22 | else servers = serversArg as PeerTubeServer[] | ||
23 | |||
24 | const states: JobState[] = [ 'waiting', 'active' ] | ||
25 | if (!skipDelayed) states.push('delayed') | ||
26 | |||
27 | const repeatableJobs: JobType[] = [ 'videos-views-stats', 'activitypub-cleaner' ] | ||
28 | let pendingRequests: boolean | ||
29 | |||
30 | function tasksBuilder () { | ||
31 | const tasks: Promise<any>[] = [] | ||
32 | |||
33 | // Check if each server has pending request | ||
34 | for (const server of servers) { | ||
35 | if (process.env.DEBUG) console.log('Checking ' + server.url) | ||
36 | |||
37 | for (const state of states) { | ||
38 | |||
39 | const jobPromise = server.jobs.list({ | ||
40 | state, | ||
41 | start: 0, | ||
42 | count: 10, | ||
43 | sort: '-createdAt' | ||
44 | }).then(body => body.data) | ||
45 | .then(jobs => jobs.filter(j => !repeatableJobs.includes(j.type))) | ||
46 | .then(jobs => { | ||
47 | if (jobs.length !== 0) { | ||
48 | pendingRequests = true | ||
49 | |||
50 | if (process.env.DEBUG) { | ||
51 | console.log(jobs) | ||
52 | } | ||
53 | } | ||
54 | }) | ||
55 | |||
56 | tasks.push(jobPromise) | ||
57 | } | ||
58 | |||
59 | const debugPromise = server.debug.getDebug() | ||
60 | .then(obj => { | ||
61 | if (obj.activityPubMessagesWaiting !== 0) { | ||
62 | pendingRequests = true | ||
63 | |||
64 | if (process.env.DEBUG) { | ||
65 | console.log('AP messages waiting: ' + obj.activityPubMessagesWaiting) | ||
66 | } | ||
67 | } | ||
68 | }) | ||
69 | tasks.push(debugPromise) | ||
70 | |||
71 | if (runnerJobs) { | ||
72 | const runnerJobsPromise = server.runnerJobs.list({ count: 100 }) | ||
73 | .then(({ data }) => { | ||
74 | for (const job of data) { | ||
75 | if (job.state.id !== RunnerJobState.COMPLETED) { | ||
76 | pendingRequests = true | ||
77 | |||
78 | if (process.env.DEBUG) { | ||
79 | console.log(job) | ||
80 | } | ||
81 | } | ||
82 | } | ||
83 | }) | ||
84 | tasks.push(runnerJobsPromise) | ||
85 | } | ||
86 | } | ||
87 | |||
88 | return tasks | ||
89 | } | ||
90 | |||
91 | do { | ||
92 | pendingRequests = false | ||
93 | await Promise.all(tasksBuilder()) | ||
94 | |||
95 | // Retry, in case of new jobs were created | ||
96 | if (pendingRequests === false) { | ||
97 | await wait(pendingJobWait) | ||
98 | await Promise.all(tasksBuilder()) | ||
99 | } | ||
100 | |||
101 | if (pendingRequests) { | ||
102 | await wait(pendingJobWait) | ||
103 | } | ||
104 | } while (pendingRequests) | ||
105 | } | ||
106 | |||
107 | async function expectNoFailedTranscodingJob (server: PeerTubeServer) { | ||
108 | const { data } = await server.jobs.listFailed({ jobType: 'video-transcoding' }) | ||
109 | expect(data).to.have.lengthOf(0) | ||
110 | } | ||
111 | |||
112 | // --------------------------------------------------------------------------- | ||
113 | |||
114 | export { | ||
115 | waitJobs, | ||
116 | expectNoFailedTranscodingJob | ||
117 | } | ||
diff --git a/packages/server-commands/src/server/metrics-command.ts b/packages/server-commands/src/server/metrics-command.ts new file mode 100644 index 000000000..1f969a024 --- /dev/null +++ b/packages/server-commands/src/server/metrics-command.ts | |||
@@ -0,0 +1,18 @@ | |||
1 | import { HttpStatusCode, PlaybackMetricCreate } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class MetricsCommand extends AbstractCommand { | ||
5 | |||
6 | addPlaybackMetric (options: OverrideCommandOptions & { metrics: PlaybackMetricCreate }) { | ||
7 | const path = '/api/v1/metrics/playback' | ||
8 | |||
9 | return this.postBodyRequest({ | ||
10 | ...options, | ||
11 | |||
12 | path, | ||
13 | fields: options.metrics, | ||
14 | implicitToken: false, | ||
15 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
16 | }) | ||
17 | } | ||
18 | } | ||
diff --git a/packages/server-commands/src/server/object-storage-command.ts b/packages/server-commands/src/server/object-storage-command.ts new file mode 100644 index 000000000..ff8d5d75c --- /dev/null +++ b/packages/server-commands/src/server/object-storage-command.ts | |||
@@ -0,0 +1,165 @@ | |||
1 | import { randomInt } from 'crypto' | ||
2 | import { HttpStatusCode } from '@peertube/peertube-models' | ||
3 | import { makePostBodyRequest } from '../requests/index.js' | ||
4 | |||
5 | export class ObjectStorageCommand { | ||
6 | static readonly DEFAULT_SCALEWAY_BUCKET = 'peertube-ci-test' | ||
7 | |||
8 | private readonly bucketsCreated: string[] = [] | ||
9 | private readonly seed: number | ||
10 | |||
11 | // --------------------------------------------------------------------------- | ||
12 | |||
13 | constructor () { | ||
14 | this.seed = randomInt(0, 10000) | ||
15 | } | ||
16 | |||
17 | static getMockCredentialsConfig () { | ||
18 | return { | ||
19 | access_key_id: 'AKIAIOSFODNN7EXAMPLE', | ||
20 | secret_access_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' | ||
21 | } | ||
22 | } | ||
23 | |||
24 | static getMockEndpointHost () { | ||
25 | return 'localhost:9444' | ||
26 | } | ||
27 | |||
28 | static getMockRegion () { | ||
29 | return 'us-east-1' | ||
30 | } | ||
31 | |||
32 | getDefaultMockConfig () { | ||
33 | return { | ||
34 | object_storage: { | ||
35 | enabled: true, | ||
36 | endpoint: 'http://' + ObjectStorageCommand.getMockEndpointHost(), | ||
37 | region: ObjectStorageCommand.getMockRegion(), | ||
38 | |||
39 | credentials: ObjectStorageCommand.getMockCredentialsConfig(), | ||
40 | |||
41 | streaming_playlists: { | ||
42 | bucket_name: this.getMockStreamingPlaylistsBucketName() | ||
43 | }, | ||
44 | |||
45 | web_videos: { | ||
46 | bucket_name: this.getMockWebVideosBucketName() | ||
47 | } | ||
48 | } | ||
49 | } | ||
50 | } | ||
51 | |||
52 | getMockWebVideosBaseUrl () { | ||
53 | return `http://${this.getMockWebVideosBucketName()}.${ObjectStorageCommand.getMockEndpointHost()}/` | ||
54 | } | ||
55 | |||
56 | getMockPlaylistBaseUrl () { | ||
57 | return `http://${this.getMockStreamingPlaylistsBucketName()}.${ObjectStorageCommand.getMockEndpointHost()}/` | ||
58 | } | ||
59 | |||
60 | async prepareDefaultMockBuckets () { | ||
61 | await this.createMockBucket(this.getMockStreamingPlaylistsBucketName()) | ||
62 | await this.createMockBucket(this.getMockWebVideosBucketName()) | ||
63 | } | ||
64 | |||
65 | async createMockBucket (name: string) { | ||
66 | this.bucketsCreated.push(name) | ||
67 | |||
68 | await this.deleteMockBucket(name) | ||
69 | |||
70 | await makePostBodyRequest({ | ||
71 | url: ObjectStorageCommand.getMockEndpointHost(), | ||
72 | path: '/ui/' + name + '?create', | ||
73 | expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 | ||
74 | }) | ||
75 | |||
76 | await makePostBodyRequest({ | ||
77 | url: ObjectStorageCommand.getMockEndpointHost(), | ||
78 | path: '/ui/' + name + '?make-public', | ||
79 | expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 | ||
80 | }) | ||
81 | } | ||
82 | |||
83 | async cleanupMock () { | ||
84 | for (const name of this.bucketsCreated) { | ||
85 | await this.deleteMockBucket(name) | ||
86 | } | ||
87 | } | ||
88 | |||
89 | getMockStreamingPlaylistsBucketName (name = 'streaming-playlists') { | ||
90 | return this.getMockBucketName(name) | ||
91 | } | ||
92 | |||
93 | getMockWebVideosBucketName (name = 'web-videos') { | ||
94 | return this.getMockBucketName(name) | ||
95 | } | ||
96 | |||
97 | getMockBucketName (name: string) { | ||
98 | return `${this.seed}-${name}` | ||
99 | } | ||
100 | |||
101 | private async deleteMockBucket (name: string) { | ||
102 | await makePostBodyRequest({ | ||
103 | url: ObjectStorageCommand.getMockEndpointHost(), | ||
104 | path: '/ui/' + name + '?delete', | ||
105 | expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 | ||
106 | }) | ||
107 | } | ||
108 | |||
109 | // --------------------------------------------------------------------------- | ||
110 | |||
111 | static getDefaultScalewayConfig (options: { | ||
112 | serverNumber: number | ||
113 | enablePrivateProxy?: boolean // default true | ||
114 | privateACL?: 'private' | 'public-read' // default 'private' | ||
115 | }) { | ||
116 | const { serverNumber, enablePrivateProxy = true, privateACL = 'private' } = options | ||
117 | |||
118 | return { | ||
119 | object_storage: { | ||
120 | enabled: true, | ||
121 | endpoint: this.getScalewayEndpointHost(), | ||
122 | region: this.getScalewayRegion(), | ||
123 | |||
124 | credentials: this.getScalewayCredentialsConfig(), | ||
125 | |||
126 | upload_acl: { | ||
127 | private: privateACL | ||
128 | }, | ||
129 | |||
130 | proxy: { | ||
131 | proxify_private_files: enablePrivateProxy | ||
132 | }, | ||
133 | |||
134 | streaming_playlists: { | ||
135 | bucket_name: this.DEFAULT_SCALEWAY_BUCKET, | ||
136 | prefix: `test:server-${serverNumber}-streaming-playlists:` | ||
137 | }, | ||
138 | |||
139 | web_videos: { | ||
140 | bucket_name: this.DEFAULT_SCALEWAY_BUCKET, | ||
141 | prefix: `test:server-${serverNumber}-web-videos:` | ||
142 | } | ||
143 | } | ||
144 | } | ||
145 | } | ||
146 | |||
147 | static getScalewayCredentialsConfig () { | ||
148 | return { | ||
149 | access_key_id: process.env.OBJECT_STORAGE_SCALEWAY_KEY_ID, | ||
150 | secret_access_key: process.env.OBJECT_STORAGE_SCALEWAY_ACCESS_KEY | ||
151 | } | ||
152 | } | ||
153 | |||
154 | static getScalewayEndpointHost () { | ||
155 | return 's3.fr-par.scw.cloud' | ||
156 | } | ||
157 | |||
158 | static getScalewayRegion () { | ||
159 | return 'fr-par' | ||
160 | } | ||
161 | |||
162 | static getScalewayBaseUrl () { | ||
163 | return `https://${this.DEFAULT_SCALEWAY_BUCKET}.${this.getScalewayEndpointHost()}/` | ||
164 | } | ||
165 | } | ||
diff --git a/packages/server-commands/src/server/plugins-command.ts b/packages/server-commands/src/server/plugins-command.ts new file mode 100644 index 000000000..f85ef0330 --- /dev/null +++ b/packages/server-commands/src/server/plugins-command.ts | |||
@@ -0,0 +1,258 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ | ||
2 | |||
3 | import { readJSON, writeJSON } from 'fs-extra/esm' | ||
4 | import { join } from 'path' | ||
5 | import { | ||
6 | HttpStatusCode, | ||
7 | HttpStatusCodeType, | ||
8 | PeerTubePlugin, | ||
9 | PeerTubePluginIndex, | ||
10 | PeertubePluginIndexList, | ||
11 | PluginPackageJSON, | ||
12 | PluginTranslation, | ||
13 | PluginType_Type, | ||
14 | PublicServerSetting, | ||
15 | RegisteredServerSettings, | ||
16 | ResultList | ||
17 | } from '@peertube/peertube-models' | ||
18 | import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils' | ||
19 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
20 | |||
21 | export class PluginsCommand extends AbstractCommand { | ||
22 | |||
23 | static getPluginTestPath (suffix = '') { | ||
24 | return buildAbsoluteFixturePath('peertube-plugin-test' + suffix) | ||
25 | } | ||
26 | |||
27 | list (options: OverrideCommandOptions & { | ||
28 | start?: number | ||
29 | count?: number | ||
30 | sort?: string | ||
31 | pluginType?: PluginType_Type | ||
32 | uninstalled?: boolean | ||
33 | }) { | ||
34 | const { start, count, sort, pluginType, uninstalled } = options | ||
35 | const path = '/api/v1/plugins' | ||
36 | |||
37 | return this.getRequestBody<ResultList<PeerTubePlugin>>({ | ||
38 | ...options, | ||
39 | |||
40 | path, | ||
41 | query: { | ||
42 | start, | ||
43 | count, | ||
44 | sort, | ||
45 | pluginType, | ||
46 | uninstalled | ||
47 | }, | ||
48 | implicitToken: true, | ||
49 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
50 | }) | ||
51 | } | ||
52 | |||
53 | listAvailable (options: OverrideCommandOptions & { | ||
54 | start?: number | ||
55 | count?: number | ||
56 | sort?: string | ||
57 | pluginType?: PluginType_Type | ||
58 | currentPeerTubeEngine?: string | ||
59 | search?: string | ||
60 | expectedStatus?: HttpStatusCodeType | ||
61 | }) { | ||
62 | const { start, count, sort, pluginType, search, currentPeerTubeEngine } = options | ||
63 | const path = '/api/v1/plugins/available' | ||
64 | |||
65 | const query: PeertubePluginIndexList = { | ||
66 | start, | ||
67 | count, | ||
68 | sort, | ||
69 | pluginType, | ||
70 | currentPeerTubeEngine, | ||
71 | search | ||
72 | } | ||
73 | |||
74 | return this.getRequestBody<ResultList<PeerTubePluginIndex>>({ | ||
75 | ...options, | ||
76 | |||
77 | path, | ||
78 | query, | ||
79 | implicitToken: true, | ||
80 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
81 | }) | ||
82 | } | ||
83 | |||
84 | get (options: OverrideCommandOptions & { | ||
85 | npmName: string | ||
86 | }) { | ||
87 | const path = '/api/v1/plugins/' + options.npmName | ||
88 | |||
89 | return this.getRequestBody<PeerTubePlugin>({ | ||
90 | ...options, | ||
91 | |||
92 | path, | ||
93 | implicitToken: true, | ||
94 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
95 | }) | ||
96 | } | ||
97 | |||
98 | updateSettings (options: OverrideCommandOptions & { | ||
99 | npmName: string | ||
100 | settings: any | ||
101 | }) { | ||
102 | const { npmName, settings } = options | ||
103 | const path = '/api/v1/plugins/' + npmName + '/settings' | ||
104 | |||
105 | return this.putBodyRequest({ | ||
106 | ...options, | ||
107 | |||
108 | path, | ||
109 | fields: { settings }, | ||
110 | implicitToken: true, | ||
111 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
112 | }) | ||
113 | } | ||
114 | |||
115 | getRegisteredSettings (options: OverrideCommandOptions & { | ||
116 | npmName: string | ||
117 | }) { | ||
118 | const path = '/api/v1/plugins/' + options.npmName + '/registered-settings' | ||
119 | |||
120 | return this.getRequestBody<RegisteredServerSettings>({ | ||
121 | ...options, | ||
122 | |||
123 | path, | ||
124 | implicitToken: true, | ||
125 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
126 | }) | ||
127 | } | ||
128 | |||
129 | getPublicSettings (options: OverrideCommandOptions & { | ||
130 | npmName: string | ||
131 | }) { | ||
132 | const { npmName } = options | ||
133 | const path = '/api/v1/plugins/' + npmName + '/public-settings' | ||
134 | |||
135 | return this.getRequestBody<PublicServerSetting>({ | ||
136 | ...options, | ||
137 | |||
138 | path, | ||
139 | implicitToken: false, | ||
140 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
141 | }) | ||
142 | } | ||
143 | |||
144 | getTranslations (options: OverrideCommandOptions & { | ||
145 | locale: string | ||
146 | }) { | ||
147 | const { locale } = options | ||
148 | const path = '/plugins/translations/' + locale + '.json' | ||
149 | |||
150 | return this.getRequestBody<PluginTranslation>({ | ||
151 | ...options, | ||
152 | |||
153 | path, | ||
154 | implicitToken: false, | ||
155 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
156 | }) | ||
157 | } | ||
158 | |||
159 | install (options: OverrideCommandOptions & { | ||
160 | path?: string | ||
161 | npmName?: string | ||
162 | pluginVersion?: string | ||
163 | }) { | ||
164 | const { npmName, path, pluginVersion } = options | ||
165 | const apiPath = '/api/v1/plugins/install' | ||
166 | |||
167 | return this.postBodyRequest({ | ||
168 | ...options, | ||
169 | |||
170 | path: apiPath, | ||
171 | fields: { npmName, path, pluginVersion }, | ||
172 | implicitToken: true, | ||
173 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
174 | }) | ||
175 | } | ||
176 | |||
177 | update (options: OverrideCommandOptions & { | ||
178 | path?: string | ||
179 | npmName?: string | ||
180 | }) { | ||
181 | const { npmName, path } = options | ||
182 | const apiPath = '/api/v1/plugins/update' | ||
183 | |||
184 | return this.postBodyRequest({ | ||
185 | ...options, | ||
186 | |||
187 | path: apiPath, | ||
188 | fields: { npmName, path }, | ||
189 | implicitToken: true, | ||
190 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
191 | }) | ||
192 | } | ||
193 | |||
194 | uninstall (options: OverrideCommandOptions & { | ||
195 | npmName: string | ||
196 | }) { | ||
197 | const { npmName } = options | ||
198 | const apiPath = '/api/v1/plugins/uninstall' | ||
199 | |||
200 | return this.postBodyRequest({ | ||
201 | ...options, | ||
202 | |||
203 | path: apiPath, | ||
204 | fields: { npmName }, | ||
205 | implicitToken: true, | ||
206 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
207 | }) | ||
208 | } | ||
209 | |||
210 | getCSS (options: OverrideCommandOptions = {}) { | ||
211 | const path = '/plugins/global.css' | ||
212 | |||
213 | return this.getRequestText({ | ||
214 | ...options, | ||
215 | |||
216 | path, | ||
217 | implicitToken: false, | ||
218 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
219 | }) | ||
220 | } | ||
221 | |||
222 | getExternalAuth (options: OverrideCommandOptions & { | ||
223 | npmName: string | ||
224 | npmVersion: string | ||
225 | authName: string | ||
226 | query?: any | ||
227 | }) { | ||
228 | const { npmName, npmVersion, authName, query } = options | ||
229 | |||
230 | const path = '/plugins/' + npmName + '/' + npmVersion + '/auth/' + authName | ||
231 | |||
232 | return this.getRequest({ | ||
233 | ...options, | ||
234 | |||
235 | path, | ||
236 | query, | ||
237 | implicitToken: false, | ||
238 | defaultExpectedStatus: HttpStatusCode.OK_200, | ||
239 | redirects: 0 | ||
240 | }) | ||
241 | } | ||
242 | |||
243 | updatePackageJSON (npmName: string, json: any) { | ||
244 | const path = this.getPackageJSONPath(npmName) | ||
245 | |||
246 | return writeJSON(path, json) | ||
247 | } | ||
248 | |||
249 | getPackageJSON (npmName: string): Promise<PluginPackageJSON> { | ||
250 | const path = this.getPackageJSONPath(npmName) | ||
251 | |||
252 | return readJSON(path) | ||
253 | } | ||
254 | |||
255 | private getPackageJSONPath (npmName: string) { | ||
256 | return this.server.servers.buildDirectory(join('plugins', 'node_modules', npmName, 'package.json')) | ||
257 | } | ||
258 | } | ||
diff --git a/packages/server-commands/src/server/redundancy-command.ts b/packages/server-commands/src/server/redundancy-command.ts new file mode 100644 index 000000000..a0ec3e80e --- /dev/null +++ b/packages/server-commands/src/server/redundancy-command.ts | |||
@@ -0,0 +1,80 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class RedundancyCommand extends AbstractCommand { | ||
5 | |||
6 | updateRedundancy (options: OverrideCommandOptions & { | ||
7 | host: string | ||
8 | redundancyAllowed: boolean | ||
9 | }) { | ||
10 | const { host, redundancyAllowed } = options | ||
11 | const path = '/api/v1/server/redundancy/' + host | ||
12 | |||
13 | return this.putBodyRequest({ | ||
14 | ...options, | ||
15 | |||
16 | path, | ||
17 | fields: { redundancyAllowed }, | ||
18 | implicitToken: true, | ||
19 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
20 | }) | ||
21 | } | ||
22 | |||
23 | listVideos (options: OverrideCommandOptions & { | ||
24 | target: VideoRedundanciesTarget | ||
25 | start?: number | ||
26 | count?: number | ||
27 | sort?: string | ||
28 | }) { | ||
29 | const path = '/api/v1/server/redundancy/videos' | ||
30 | |||
31 | const { target, start, count, sort } = options | ||
32 | |||
33 | return this.getRequestBody<ResultList<VideoRedundancy>>({ | ||
34 | ...options, | ||
35 | |||
36 | path, | ||
37 | |||
38 | query: { | ||
39 | start: start ?? 0, | ||
40 | count: count ?? 5, | ||
41 | sort: sort ?? 'name', | ||
42 | target | ||
43 | }, | ||
44 | |||
45 | implicitToken: true, | ||
46 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
47 | }) | ||
48 | } | ||
49 | |||
50 | addVideo (options: OverrideCommandOptions & { | ||
51 | videoId: number | ||
52 | }) { | ||
53 | const path = '/api/v1/server/redundancy/videos' | ||
54 | const { videoId } = options | ||
55 | |||
56 | return this.postBodyRequest({ | ||
57 | ...options, | ||
58 | |||
59 | path, | ||
60 | fields: { videoId }, | ||
61 | implicitToken: true, | ||
62 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
63 | }) | ||
64 | } | ||
65 | |||
66 | removeVideo (options: OverrideCommandOptions & { | ||
67 | redundancyId: number | ||
68 | }) { | ||
69 | const { redundancyId } = options | ||
70 | const path = '/api/v1/server/redundancy/videos/' + redundancyId | ||
71 | |||
72 | return this.deleteRequest({ | ||
73 | ...options, | ||
74 | |||
75 | path, | ||
76 | implicitToken: true, | ||
77 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
78 | }) | ||
79 | } | ||
80 | } | ||
diff --git a/packages/server-commands/src/server/server.ts b/packages/server-commands/src/server/server.ts new file mode 100644 index 000000000..57a897c17 --- /dev/null +++ b/packages/server-commands/src/server/server.ts | |||
@@ -0,0 +1,451 @@ | |||
1 | import { ChildProcess, fork } from 'child_process' | ||
2 | import { copy } from 'fs-extra/esm' | ||
3 | import { join } from 'path' | ||
4 | import { randomInt } from '@peertube/peertube-core-utils' | ||
5 | import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@peertube/peertube-models' | ||
6 | import { parallelTests, root } from '@peertube/peertube-node-utils' | ||
7 | import { BulkCommand } from '../bulk/index.js' | ||
8 | import { CLICommand } from '../cli/index.js' | ||
9 | import { CustomPagesCommand } from '../custom-pages/index.js' | ||
10 | import { FeedCommand } from '../feeds/index.js' | ||
11 | import { LogsCommand } from '../logs/index.js' | ||
12 | import { AbusesCommand } from '../moderation/index.js' | ||
13 | import { OverviewsCommand } from '../overviews/index.js' | ||
14 | import { RunnerJobsCommand, RunnerRegistrationTokensCommand, RunnersCommand } from '../runners/index.js' | ||
15 | import { SearchCommand } from '../search/index.js' | ||
16 | import { SocketIOCommand } from '../socket/index.js' | ||
17 | import { | ||
18 | AccountsCommand, | ||
19 | BlocklistCommand, | ||
20 | LoginCommand, | ||
21 | NotificationsCommand, | ||
22 | RegistrationsCommand, | ||
23 | SubscriptionsCommand, | ||
24 | TwoFactorCommand, | ||
25 | UsersCommand | ||
26 | } from '../users/index.js' | ||
27 | import { | ||
28 | BlacklistCommand, | ||
29 | CaptionsCommand, | ||
30 | ChangeOwnershipCommand, | ||
31 | ChannelsCommand, | ||
32 | ChannelSyncsCommand, | ||
33 | CommentsCommand, | ||
34 | HistoryCommand, | ||
35 | ImportsCommand, | ||
36 | LiveCommand, | ||
37 | PlaylistsCommand, | ||
38 | ServicesCommand, | ||
39 | StoryboardCommand, | ||
40 | StreamingPlaylistsCommand, | ||
41 | VideoPasswordsCommand, | ||
42 | VideosCommand, | ||
43 | VideoStatsCommand, | ||
44 | VideoStudioCommand, | ||
45 | VideoTokenCommand, | ||
46 | ViewsCommand | ||
47 | } from '../videos/index.js' | ||
48 | import { ConfigCommand } from './config-command.js' | ||
49 | import { ContactFormCommand } from './contact-form-command.js' | ||
50 | import { DebugCommand } from './debug-command.js' | ||
51 | import { FollowsCommand } from './follows-command.js' | ||
52 | import { JobsCommand } from './jobs-command.js' | ||
53 | import { MetricsCommand } from './metrics-command.js' | ||
54 | import { PluginsCommand } from './plugins-command.js' | ||
55 | import { RedundancyCommand } from './redundancy-command.js' | ||
56 | import { ServersCommand } from './servers-command.js' | ||
57 | import { StatsCommand } from './stats-command.js' | ||
58 | |||
59 | export type RunServerOptions = { | ||
60 | hideLogs?: boolean | ||
61 | nodeArgs?: string[] | ||
62 | peertubeArgs?: string[] | ||
63 | env?: { [ id: string ]: string } | ||
64 | } | ||
65 | |||
66 | export class PeerTubeServer { | ||
67 | app?: ChildProcess | ||
68 | |||
69 | url: string | ||
70 | host?: string | ||
71 | hostname?: string | ||
72 | port?: number | ||
73 | |||
74 | rtmpPort?: number | ||
75 | rtmpsPort?: number | ||
76 | |||
77 | parallel?: boolean | ||
78 | internalServerNumber: number | ||
79 | |||
80 | serverNumber?: number | ||
81 | customConfigFile?: string | ||
82 | |||
83 | store?: { | ||
84 | client?: { | ||
85 | id?: string | ||
86 | secret?: string | ||
87 | } | ||
88 | |||
89 | user?: { | ||
90 | username: string | ||
91 | password: string | ||
92 | email?: string | ||
93 | } | ||
94 | |||
95 | channel?: VideoChannel | ||
96 | videoChannelSync?: Partial<VideoChannelSync> | ||
97 | |||
98 | video?: Video | ||
99 | videoCreated?: VideoCreateResult | ||
100 | videoDetails?: VideoDetails | ||
101 | |||
102 | videos?: { id: number, uuid: string }[] | ||
103 | } | ||
104 | |||
105 | accessToken?: string | ||
106 | refreshToken?: string | ||
107 | |||
108 | bulk?: BulkCommand | ||
109 | cli?: CLICommand | ||
110 | customPage?: CustomPagesCommand | ||
111 | feed?: FeedCommand | ||
112 | logs?: LogsCommand | ||
113 | abuses?: AbusesCommand | ||
114 | overviews?: OverviewsCommand | ||
115 | search?: SearchCommand | ||
116 | contactForm?: ContactFormCommand | ||
117 | debug?: DebugCommand | ||
118 | follows?: FollowsCommand | ||
119 | jobs?: JobsCommand | ||
120 | metrics?: MetricsCommand | ||
121 | plugins?: PluginsCommand | ||
122 | redundancy?: RedundancyCommand | ||
123 | stats?: StatsCommand | ||
124 | config?: ConfigCommand | ||
125 | socketIO?: SocketIOCommand | ||
126 | accounts?: AccountsCommand | ||
127 | blocklist?: BlocklistCommand | ||
128 | subscriptions?: SubscriptionsCommand | ||
129 | live?: LiveCommand | ||
130 | services?: ServicesCommand | ||
131 | blacklist?: BlacklistCommand | ||
132 | captions?: CaptionsCommand | ||
133 | changeOwnership?: ChangeOwnershipCommand | ||
134 | playlists?: PlaylistsCommand | ||
135 | history?: HistoryCommand | ||
136 | imports?: ImportsCommand | ||
137 | channelSyncs?: ChannelSyncsCommand | ||
138 | streamingPlaylists?: StreamingPlaylistsCommand | ||
139 | channels?: ChannelsCommand | ||
140 | comments?: CommentsCommand | ||
141 | notifications?: NotificationsCommand | ||
142 | servers?: ServersCommand | ||
143 | login?: LoginCommand | ||
144 | users?: UsersCommand | ||
145 | videoStudio?: VideoStudioCommand | ||
146 | videos?: VideosCommand | ||
147 | videoStats?: VideoStatsCommand | ||
148 | views?: ViewsCommand | ||
149 | twoFactor?: TwoFactorCommand | ||
150 | videoToken?: VideoTokenCommand | ||
151 | registrations?: RegistrationsCommand | ||
152 | videoPasswords?: VideoPasswordsCommand | ||
153 | |||
154 | storyboard?: StoryboardCommand | ||
155 | |||
156 | runners?: RunnersCommand | ||
157 | runnerRegistrationTokens?: RunnerRegistrationTokensCommand | ||
158 | runnerJobs?: RunnerJobsCommand | ||
159 | |||
160 | constructor (options: { serverNumber: number } | { url: string }) { | ||
161 | if ((options as any).url) { | ||
162 | this.setUrl((options as any).url) | ||
163 | } else { | ||
164 | this.setServerNumber((options as any).serverNumber) | ||
165 | } | ||
166 | |||
167 | this.store = { | ||
168 | client: { | ||
169 | id: null, | ||
170 | secret: null | ||
171 | }, | ||
172 | user: { | ||
173 | username: null, | ||
174 | password: null | ||
175 | } | ||
176 | } | ||
177 | |||
178 | this.assignCommands() | ||
179 | } | ||
180 | |||
181 | setServerNumber (serverNumber: number) { | ||
182 | this.serverNumber = serverNumber | ||
183 | |||
184 | this.parallel = parallelTests() | ||
185 | |||
186 | this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber | ||
187 | this.rtmpPort = this.parallel ? this.randomRTMP() : 1936 | ||
188 | this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937 | ||
189 | this.port = 9000 + this.internalServerNumber | ||
190 | |||
191 | this.url = `http://127.0.0.1:${this.port}` | ||
192 | this.host = `127.0.0.1:${this.port}` | ||
193 | this.hostname = '127.0.0.1' | ||
194 | } | ||
195 | |||
196 | setUrl (url: string) { | ||
197 | const parsed = new URL(url) | ||
198 | |||
199 | this.url = url | ||
200 | this.host = parsed.host | ||
201 | this.hostname = parsed.hostname | ||
202 | this.port = parseInt(parsed.port) | ||
203 | } | ||
204 | |||
205 | getDirectoryPath (directoryName: string) { | ||
206 | const testDirectory = 'test' + this.internalServerNumber | ||
207 | |||
208 | return join(root(), testDirectory, directoryName) | ||
209 | } | ||
210 | |||
211 | async flushAndRun (configOverride?: object, options: RunServerOptions = {}) { | ||
212 | await ServersCommand.flushTests(this.internalServerNumber) | ||
213 | |||
214 | return this.run(configOverride, options) | ||
215 | } | ||
216 | |||
217 | async run (configOverrideArg?: any, options: RunServerOptions = {}) { | ||
218 | // These actions are async so we need to be sure that they have both been done | ||
219 | const serverRunString = { | ||
220 | 'HTTP server listening': false | ||
221 | } | ||
222 | const key = 'Database peertube_test' + this.internalServerNumber + ' is ready' | ||
223 | serverRunString[key] = false | ||
224 | |||
225 | const regexps = { | ||
226 | client_id: 'Client id: (.+)', | ||
227 | client_secret: 'Client secret: (.+)', | ||
228 | user_username: 'Username: (.+)', | ||
229 | user_password: 'User password: (.+)' | ||
230 | } | ||
231 | |||
232 | await this.assignCustomConfigFile() | ||
233 | |||
234 | const configOverride = this.buildConfigOverride() | ||
235 | |||
236 | if (configOverrideArg !== undefined) { | ||
237 | Object.assign(configOverride, configOverrideArg) | ||
238 | } | ||
239 | |||
240 | // Share the environment | ||
241 | const env = { ...process.env } | ||
242 | env['NODE_ENV'] = 'test' | ||
243 | env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString() | ||
244 | env['NODE_CONFIG'] = JSON.stringify(configOverride) | ||
245 | |||
246 | if (options.env) { | ||
247 | Object.assign(env, options.env) | ||
248 | } | ||
249 | |||
250 | const execArgv = options.nodeArgs || [] | ||
251 | // FIXME: too slow :/ | ||
252 | // execArgv.push('--enable-source-maps') | ||
253 | |||
254 | const forkOptions = { | ||
255 | silent: true, | ||
256 | env, | ||
257 | detached: false, | ||
258 | execArgv | ||
259 | } | ||
260 | |||
261 | const peertubeArgs = options.peertubeArgs || [] | ||
262 | |||
263 | return new Promise<void>((res, rej) => { | ||
264 | const self = this | ||
265 | let aggregatedLogs = '' | ||
266 | |||
267 | this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions) | ||
268 | |||
269 | const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs)) | ||
270 | const onParentExit = () => { | ||
271 | if (!this.app?.pid) return | ||
272 | |||
273 | try { | ||
274 | process.kill(self.app.pid) | ||
275 | } catch { /* empty */ } | ||
276 | } | ||
277 | |||
278 | this.app.on('exit', onPeerTubeExit) | ||
279 | process.on('exit', onParentExit) | ||
280 | |||
281 | this.app.stdout.on('data', function onStdout (data) { | ||
282 | let dontContinue = false | ||
283 | |||
284 | const log: string = data.toString() | ||
285 | aggregatedLogs += log | ||
286 | |||
287 | // Capture things if we want to | ||
288 | for (const key of Object.keys(regexps)) { | ||
289 | const regexp = regexps[key] | ||
290 | const matches = log.match(regexp) | ||
291 | if (matches !== null) { | ||
292 | if (key === 'client_id') self.store.client.id = matches[1] | ||
293 | else if (key === 'client_secret') self.store.client.secret = matches[1] | ||
294 | else if (key === 'user_username') self.store.user.username = matches[1] | ||
295 | else if (key === 'user_password') self.store.user.password = matches[1] | ||
296 | } | ||
297 | } | ||
298 | |||
299 | // Check if all required sentences are here | ||
300 | for (const key of Object.keys(serverRunString)) { | ||
301 | if (log.includes(key)) serverRunString[key] = true | ||
302 | if (serverRunString[key] === false) dontContinue = true | ||
303 | } | ||
304 | |||
305 | // If no, there is maybe one thing not already initialized (client/user credentials generation...) | ||
306 | if (dontContinue === true) return | ||
307 | |||
308 | if (options.hideLogs === false) { | ||
309 | console.log(log) | ||
310 | } else { | ||
311 | process.removeListener('exit', onParentExit) | ||
312 | self.app.stdout.removeListener('data', onStdout) | ||
313 | self.app.removeListener('exit', onPeerTubeExit) | ||
314 | } | ||
315 | |||
316 | res() | ||
317 | }) | ||
318 | }) | ||
319 | } | ||
320 | |||
321 | kill () { | ||
322 | if (!this.app) return Promise.resolve() | ||
323 | |||
324 | process.kill(this.app.pid) | ||
325 | |||
326 | this.app = null | ||
327 | |||
328 | return Promise.resolve() | ||
329 | } | ||
330 | |||
331 | private randomServer () { | ||
332 | const low = 2500 | ||
333 | const high = 10000 | ||
334 | |||
335 | return randomInt(low, high) | ||
336 | } | ||
337 | |||
338 | private randomRTMP () { | ||
339 | const low = 1900 | ||
340 | const high = 2100 | ||
341 | |||
342 | return randomInt(low, high) | ||
343 | } | ||
344 | |||
345 | private async assignCustomConfigFile () { | ||
346 | if (this.internalServerNumber === this.serverNumber) return | ||
347 | |||
348 | const basePath = join(root(), 'config') | ||
349 | |||
350 | const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`) | ||
351 | await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile) | ||
352 | |||
353 | this.customConfigFile = tmpConfigFile | ||
354 | } | ||
355 | |||
356 | private buildConfigOverride () { | ||
357 | if (!this.parallel) return {} | ||
358 | |||
359 | return { | ||
360 | listen: { | ||
361 | port: this.port | ||
362 | }, | ||
363 | webserver: { | ||
364 | port: this.port | ||
365 | }, | ||
366 | database: { | ||
367 | suffix: '_test' + this.internalServerNumber | ||
368 | }, | ||
369 | storage: { | ||
370 | tmp: this.getDirectoryPath('tmp') + '/', | ||
371 | tmp_persistent: this.getDirectoryPath('tmp-persistent') + '/', | ||
372 | bin: this.getDirectoryPath('bin') + '/', | ||
373 | avatars: this.getDirectoryPath('avatars') + '/', | ||
374 | web_videos: this.getDirectoryPath('web-videos') + '/', | ||
375 | streaming_playlists: this.getDirectoryPath('streaming-playlists') + '/', | ||
376 | redundancy: this.getDirectoryPath('redundancy') + '/', | ||
377 | logs: this.getDirectoryPath('logs') + '/', | ||
378 | previews: this.getDirectoryPath('previews') + '/', | ||
379 | thumbnails: this.getDirectoryPath('thumbnails') + '/', | ||
380 | storyboards: this.getDirectoryPath('storyboards') + '/', | ||
381 | torrents: this.getDirectoryPath('torrents') + '/', | ||
382 | captions: this.getDirectoryPath('captions') + '/', | ||
383 | cache: this.getDirectoryPath('cache') + '/', | ||
384 | plugins: this.getDirectoryPath('plugins') + '/', | ||
385 | well_known: this.getDirectoryPath('well-known') + '/' | ||
386 | }, | ||
387 | admin: { | ||
388 | email: `admin${this.internalServerNumber}@example.com` | ||
389 | }, | ||
390 | live: { | ||
391 | rtmp: { | ||
392 | port: this.rtmpPort | ||
393 | } | ||
394 | } | ||
395 | } | ||
396 | } | ||
397 | |||
398 | private assignCommands () { | ||
399 | this.bulk = new BulkCommand(this) | ||
400 | this.cli = new CLICommand(this) | ||
401 | this.customPage = new CustomPagesCommand(this) | ||
402 | this.feed = new FeedCommand(this) | ||
403 | this.logs = new LogsCommand(this) | ||
404 | this.abuses = new AbusesCommand(this) | ||
405 | this.overviews = new OverviewsCommand(this) | ||
406 | this.search = new SearchCommand(this) | ||
407 | this.contactForm = new ContactFormCommand(this) | ||
408 | this.debug = new DebugCommand(this) | ||
409 | this.follows = new FollowsCommand(this) | ||
410 | this.jobs = new JobsCommand(this) | ||
411 | this.metrics = new MetricsCommand(this) | ||
412 | this.plugins = new PluginsCommand(this) | ||
413 | this.redundancy = new RedundancyCommand(this) | ||
414 | this.stats = new StatsCommand(this) | ||
415 | this.config = new ConfigCommand(this) | ||
416 | this.socketIO = new SocketIOCommand(this) | ||
417 | this.accounts = new AccountsCommand(this) | ||
418 | this.blocklist = new BlocklistCommand(this) | ||
419 | this.subscriptions = new SubscriptionsCommand(this) | ||
420 | this.live = new LiveCommand(this) | ||
421 | this.services = new ServicesCommand(this) | ||
422 | this.blacklist = new BlacklistCommand(this) | ||
423 | this.captions = new CaptionsCommand(this) | ||
424 | this.changeOwnership = new ChangeOwnershipCommand(this) | ||
425 | this.playlists = new PlaylistsCommand(this) | ||
426 | this.history = new HistoryCommand(this) | ||
427 | this.imports = new ImportsCommand(this) | ||
428 | this.channelSyncs = new ChannelSyncsCommand(this) | ||
429 | this.streamingPlaylists = new StreamingPlaylistsCommand(this) | ||
430 | this.channels = new ChannelsCommand(this) | ||
431 | this.comments = new CommentsCommand(this) | ||
432 | this.notifications = new NotificationsCommand(this) | ||
433 | this.servers = new ServersCommand(this) | ||
434 | this.login = new LoginCommand(this) | ||
435 | this.users = new UsersCommand(this) | ||
436 | this.videos = new VideosCommand(this) | ||
437 | this.videoStudio = new VideoStudioCommand(this) | ||
438 | this.videoStats = new VideoStatsCommand(this) | ||
439 | this.views = new ViewsCommand(this) | ||
440 | this.twoFactor = new TwoFactorCommand(this) | ||
441 | this.videoToken = new VideoTokenCommand(this) | ||
442 | this.registrations = new RegistrationsCommand(this) | ||
443 | |||
444 | this.storyboard = new StoryboardCommand(this) | ||
445 | |||
446 | this.runners = new RunnersCommand(this) | ||
447 | this.runnerRegistrationTokens = new RunnerRegistrationTokensCommand(this) | ||
448 | this.runnerJobs = new RunnerJobsCommand(this) | ||
449 | this.videoPasswords = new VideoPasswordsCommand(this) | ||
450 | } | ||
451 | } | ||
diff --git a/packages/server-commands/src/server/servers-command.ts b/packages/server-commands/src/server/servers-command.ts new file mode 100644 index 000000000..0b722b62f --- /dev/null +++ b/packages/server-commands/src/server/servers-command.ts | |||
@@ -0,0 +1,104 @@ | |||
1 | import { exec } from 'child_process' | ||
2 | import { copy, ensureDir, remove } from 'fs-extra/esm' | ||
3 | import { readdir, readFile } from 'fs/promises' | ||
4 | import { basename, join } from 'path' | ||
5 | import { wait } from '@peertube/peertube-core-utils' | ||
6 | import { HttpStatusCode } from '@peertube/peertube-models' | ||
7 | import { getFileSize, isGithubCI, root } from '@peertube/peertube-node-utils' | ||
8 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
9 | |||
10 | export class ServersCommand extends AbstractCommand { | ||
11 | |||
12 | static flushTests (internalServerNumber: number) { | ||
13 | return new Promise<void>((res, rej) => { | ||
14 | const suffix = ` -- ${internalServerNumber}` | ||
15 | |||
16 | return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => { | ||
17 | if (err || stderr) return rej(err || new Error(stderr)) | ||
18 | |||
19 | return res() | ||
20 | }) | ||
21 | }) | ||
22 | } | ||
23 | |||
24 | ping (options: OverrideCommandOptions = {}) { | ||
25 | return this.getRequestBody({ | ||
26 | ...options, | ||
27 | |||
28 | path: '/api/v1/ping', | ||
29 | implicitToken: false, | ||
30 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
31 | }) | ||
32 | } | ||
33 | |||
34 | cleanupTests () { | ||
35 | const promises: Promise<any>[] = [] | ||
36 | |||
37 | const saveGithubLogsIfNeeded = async () => { | ||
38 | if (!isGithubCI()) return | ||
39 | |||
40 | await ensureDir('artifacts') | ||
41 | |||
42 | const origin = this.buildDirectory('logs/peertube.log') | ||
43 | const destname = `peertube-${this.server.internalServerNumber}.log` | ||
44 | console.log('Saving logs %s.', destname) | ||
45 | |||
46 | await copy(origin, join('artifacts', destname)) | ||
47 | } | ||
48 | |||
49 | if (this.server.parallel) { | ||
50 | const promise = saveGithubLogsIfNeeded() | ||
51 | .then(() => ServersCommand.flushTests(this.server.internalServerNumber)) | ||
52 | |||
53 | promises.push(promise) | ||
54 | } | ||
55 | |||
56 | if (this.server.customConfigFile) { | ||
57 | promises.push(remove(this.server.customConfigFile)) | ||
58 | } | ||
59 | |||
60 | return promises | ||
61 | } | ||
62 | |||
63 | async waitUntilLog (str: string, count = 1, strictCount = true) { | ||
64 | const logfile = this.buildDirectory('logs/peertube.log') | ||
65 | |||
66 | while (true) { | ||
67 | const buf = await readFile(logfile) | ||
68 | |||
69 | const matches = buf.toString().match(new RegExp(str, 'g')) | ||
70 | if (matches && matches.length === count) return | ||
71 | if (matches && strictCount === false && matches.length >= count) return | ||
72 | |||
73 | await wait(1000) | ||
74 | } | ||
75 | } | ||
76 | |||
77 | buildDirectory (directory: string) { | ||
78 | return join(root(), 'test' + this.server.internalServerNumber, directory) | ||
79 | } | ||
80 | |||
81 | async countFiles (directory: string) { | ||
82 | const files = await readdir(this.buildDirectory(directory)) | ||
83 | |||
84 | return files.length | ||
85 | } | ||
86 | |||
87 | buildWebVideoFilePath (fileUrl: string) { | ||
88 | return this.buildDirectory(join('web-videos', basename(fileUrl))) | ||
89 | } | ||
90 | |||
91 | buildFragmentedFilePath (videoUUID: string, fileUrl: string) { | ||
92 | return this.buildDirectory(join('streaming-playlists', 'hls', videoUUID, basename(fileUrl))) | ||
93 | } | ||
94 | |||
95 | getLogContent () { | ||
96 | return readFile(this.buildDirectory('logs/peertube.log')) | ||
97 | } | ||
98 | |||
99 | async getServerFileSize (subPath: string) { | ||
100 | const path = this.server.servers.buildDirectory(subPath) | ||
101 | |||
102 | return getFileSize(path) | ||
103 | } | ||
104 | } | ||
diff --git a/packages/server-commands/src/server/servers.ts b/packages/server-commands/src/server/servers.ts new file mode 100644 index 000000000..142973850 --- /dev/null +++ b/packages/server-commands/src/server/servers.ts | |||
@@ -0,0 +1,68 @@ | |||
1 | import { ensureDir } from 'fs-extra/esm' | ||
2 | import { isGithubCI } from '@peertube/peertube-node-utils' | ||
3 | import { PeerTubeServer, RunServerOptions } from './server.js' | ||
4 | |||
5 | async function createSingleServer (serverNumber: number, configOverride?: object, options: RunServerOptions = {}) { | ||
6 | const server = new PeerTubeServer({ serverNumber }) | ||
7 | |||
8 | await server.flushAndRun(configOverride, options) | ||
9 | |||
10 | return server | ||
11 | } | ||
12 | |||
13 | function createMultipleServers (totalServers: number, configOverride?: object, options: RunServerOptions = {}) { | ||
14 | const serverPromises: Promise<PeerTubeServer>[] = [] | ||
15 | |||
16 | for (let i = 1; i <= totalServers; i++) { | ||
17 | serverPromises.push(createSingleServer(i, configOverride, options)) | ||
18 | } | ||
19 | |||
20 | return Promise.all(serverPromises) | ||
21 | } | ||
22 | |||
23 | function killallServers (servers: PeerTubeServer[]) { | ||
24 | return Promise.all(servers.map(s => s.kill())) | ||
25 | } | ||
26 | |||
27 | async function cleanupTests (servers: PeerTubeServer[]) { | ||
28 | await killallServers(servers) | ||
29 | |||
30 | if (isGithubCI()) { | ||
31 | await ensureDir('artifacts') | ||
32 | } | ||
33 | |||
34 | let p: Promise<any>[] = [] | ||
35 | for (const server of servers) { | ||
36 | p = p.concat(server.servers.cleanupTests()) | ||
37 | } | ||
38 | |||
39 | return Promise.all(p) | ||
40 | } | ||
41 | |||
42 | function getServerImportConfig (mode: 'youtube-dl' | 'yt-dlp') { | ||
43 | return { | ||
44 | import: { | ||
45 | videos: { | ||
46 | http: { | ||
47 | youtube_dl_release: { | ||
48 | url: mode === 'youtube-dl' | ||
49 | ? 'https://api.github.com/repos/ytdl-org/youtube-dl/releases' | ||
50 | : 'https://api.github.com/repos/yt-dlp/yt-dlp/releases', | ||
51 | |||
52 | name: mode | ||
53 | } | ||
54 | } | ||
55 | } | ||
56 | } | ||
57 | } | ||
58 | } | ||
59 | |||
60 | // --------------------------------------------------------------------------- | ||
61 | |||
62 | export { | ||
63 | createSingleServer, | ||
64 | createMultipleServers, | ||
65 | cleanupTests, | ||
66 | killallServers, | ||
67 | getServerImportConfig | ||
68 | } | ||
diff --git a/packages/server-commands/src/server/stats-command.ts b/packages/server-commands/src/server/stats-command.ts new file mode 100644 index 000000000..80acd7bdc --- /dev/null +++ b/packages/server-commands/src/server/stats-command.ts | |||
@@ -0,0 +1,25 @@ | |||
1 | import { HttpStatusCode, ServerStats } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class StatsCommand extends AbstractCommand { | ||
5 | |||
6 | get (options: OverrideCommandOptions & { | ||
7 | useCache?: boolean // default false | ||
8 | } = {}) { | ||
9 | const { useCache = false } = options | ||
10 | const path = '/api/v1/server/stats' | ||
11 | |||
12 | const query = { | ||
13 | t: useCache ? undefined : new Date().getTime() | ||
14 | } | ||
15 | |||
16 | return this.getRequestBody<ServerStats>({ | ||
17 | ...options, | ||
18 | |||
19 | path, | ||
20 | query, | ||
21 | implicitToken: false, | ||
22 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
23 | }) | ||
24 | } | ||
25 | } | ||
diff --git a/packages/server-commands/src/shared/abstract-command.ts b/packages/server-commands/src/shared/abstract-command.ts new file mode 100644 index 000000000..bb6522e07 --- /dev/null +++ b/packages/server-commands/src/shared/abstract-command.ts | |||
@@ -0,0 +1,225 @@ | |||
1 | import { isAbsolute } from 'path' | ||
2 | import { HttpStatusCodeType } from '@peertube/peertube-models' | ||
3 | import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils' | ||
4 | import { | ||
5 | makeDeleteRequest, | ||
6 | makeGetRequest, | ||
7 | makePostBodyRequest, | ||
8 | makePutBodyRequest, | ||
9 | makeUploadRequest, | ||
10 | unwrapBody, | ||
11 | unwrapText | ||
12 | } from '../requests/requests.js' | ||
13 | |||
14 | import type { PeerTubeServer } from '../server/server.js' | ||
15 | |||
16 | export interface OverrideCommandOptions { | ||
17 | token?: string | ||
18 | expectedStatus?: HttpStatusCodeType | ||
19 | } | ||
20 | |||
21 | interface InternalCommonCommandOptions extends OverrideCommandOptions { | ||
22 | // Default to server.url | ||
23 | url?: string | ||
24 | |||
25 | path: string | ||
26 | // If we automatically send the server token if the token is not provided | ||
27 | implicitToken: boolean | ||
28 | defaultExpectedStatus: HttpStatusCodeType | ||
29 | |||
30 | // Common optional request parameters | ||
31 | contentType?: string | ||
32 | accept?: string | ||
33 | redirects?: number | ||
34 | range?: string | ||
35 | host?: string | ||
36 | headers?: { [ name: string ]: string } | ||
37 | requestType?: string | ||
38 | responseType?: string | ||
39 | xForwardedFor?: string | ||
40 | } | ||
41 | |||
42 | interface InternalGetCommandOptions extends InternalCommonCommandOptions { | ||
43 | query?: { [ id: string ]: any } | ||
44 | } | ||
45 | |||
46 | interface InternalDeleteCommandOptions extends InternalCommonCommandOptions { | ||
47 | query?: { [ id: string ]: any } | ||
48 | rawQuery?: string | ||
49 | } | ||
50 | |||
51 | abstract class AbstractCommand { | ||
52 | |||
53 | constructor ( | ||
54 | protected server: PeerTubeServer | ||
55 | ) { | ||
56 | |||
57 | } | ||
58 | |||
59 | protected getRequestBody <T> (options: InternalGetCommandOptions) { | ||
60 | return unwrapBody<T>(this.getRequest(options)) | ||
61 | } | ||
62 | |||
63 | protected getRequestText (options: InternalGetCommandOptions) { | ||
64 | return unwrapText(this.getRequest(options)) | ||
65 | } | ||
66 | |||
67 | protected getRawRequest (options: Omit<InternalGetCommandOptions, 'path'>) { | ||
68 | const { url, range } = options | ||
69 | const { host, protocol, pathname } = new URL(url) | ||
70 | |||
71 | return this.getRequest({ | ||
72 | ...options, | ||
73 | |||
74 | token: this.buildCommonRequestToken(options), | ||
75 | defaultExpectedStatus: this.buildExpectedStatus(options), | ||
76 | |||
77 | url: `${protocol}//${host}`, | ||
78 | path: pathname, | ||
79 | range | ||
80 | }) | ||
81 | } | ||
82 | |||
83 | protected getRequest (options: InternalGetCommandOptions) { | ||
84 | const { query } = options | ||
85 | |||
86 | return makeGetRequest({ | ||
87 | ...this.buildCommonRequestOptions(options), | ||
88 | |||
89 | query | ||
90 | }) | ||
91 | } | ||
92 | |||
93 | protected deleteRequest (options: InternalDeleteCommandOptions) { | ||
94 | const { query, rawQuery } = options | ||
95 | |||
96 | return makeDeleteRequest({ | ||
97 | ...this.buildCommonRequestOptions(options), | ||
98 | |||
99 | query, | ||
100 | rawQuery | ||
101 | }) | ||
102 | } | ||
103 | |||
104 | protected putBodyRequest (options: InternalCommonCommandOptions & { | ||
105 | fields?: { [ fieldName: string ]: any } | ||
106 | headers?: { [name: string]: string } | ||
107 | }) { | ||
108 | const { fields, headers } = options | ||
109 | |||
110 | return makePutBodyRequest({ | ||
111 | ...this.buildCommonRequestOptions(options), | ||
112 | |||
113 | fields, | ||
114 | headers | ||
115 | }) | ||
116 | } | ||
117 | |||
118 | protected postBodyRequest (options: InternalCommonCommandOptions & { | ||
119 | fields?: { [ fieldName: string ]: any } | ||
120 | headers?: { [name: string]: string } | ||
121 | }) { | ||
122 | const { fields, headers } = options | ||
123 | |||
124 | return makePostBodyRequest({ | ||
125 | ...this.buildCommonRequestOptions(options), | ||
126 | |||
127 | fields, | ||
128 | headers | ||
129 | }) | ||
130 | } | ||
131 | |||
132 | protected postUploadRequest (options: InternalCommonCommandOptions & { | ||
133 | fields?: { [ fieldName: string ]: any } | ||
134 | attaches?: { [ fieldName: string ]: any } | ||
135 | }) { | ||
136 | const { fields, attaches } = options | ||
137 | |||
138 | return makeUploadRequest({ | ||
139 | ...this.buildCommonRequestOptions(options), | ||
140 | |||
141 | method: 'POST', | ||
142 | fields, | ||
143 | attaches | ||
144 | }) | ||
145 | } | ||
146 | |||
147 | protected putUploadRequest (options: InternalCommonCommandOptions & { | ||
148 | fields?: { [ fieldName: string ]: any } | ||
149 | attaches?: { [ fieldName: string ]: any } | ||
150 | }) { | ||
151 | const { fields, attaches } = options | ||
152 | |||
153 | return makeUploadRequest({ | ||
154 | ...this.buildCommonRequestOptions(options), | ||
155 | |||
156 | method: 'PUT', | ||
157 | fields, | ||
158 | attaches | ||
159 | }) | ||
160 | } | ||
161 | |||
162 | protected updateImageRequest (options: InternalCommonCommandOptions & { | ||
163 | fixture: string | ||
164 | fieldname: string | ||
165 | }) { | ||
166 | const filePath = isAbsolute(options.fixture) | ||
167 | ? options.fixture | ||
168 | : buildAbsoluteFixturePath(options.fixture) | ||
169 | |||
170 | return this.postUploadRequest({ | ||
171 | ...options, | ||
172 | |||
173 | fields: {}, | ||
174 | attaches: { [options.fieldname]: filePath } | ||
175 | }) | ||
176 | } | ||
177 | |||
178 | protected buildCommonRequestOptions (options: InternalCommonCommandOptions) { | ||
179 | const { url, path, redirects, contentType, accept, range, host, headers, requestType, xForwardedFor, responseType } = options | ||
180 | |||
181 | return { | ||
182 | url: url ?? this.server.url, | ||
183 | path, | ||
184 | |||
185 | token: this.buildCommonRequestToken(options), | ||
186 | expectedStatus: this.buildExpectedStatus(options), | ||
187 | |||
188 | redirects, | ||
189 | contentType, | ||
190 | range, | ||
191 | host, | ||
192 | accept, | ||
193 | headers, | ||
194 | type: requestType, | ||
195 | responseType, | ||
196 | xForwardedFor | ||
197 | } | ||
198 | } | ||
199 | |||
200 | protected buildCommonRequestToken (options: Pick<InternalCommonCommandOptions, 'token' | 'implicitToken'>) { | ||
201 | const { token } = options | ||
202 | |||
203 | const fallbackToken = options.implicitToken | ||
204 | ? this.server.accessToken | ||
205 | : undefined | ||
206 | |||
207 | return token !== undefined ? token : fallbackToken | ||
208 | } | ||
209 | |||
210 | protected buildExpectedStatus (options: Pick<InternalCommonCommandOptions, 'expectedStatus' | 'defaultExpectedStatus'>) { | ||
211 | const { expectedStatus, defaultExpectedStatus } = options | ||
212 | |||
213 | return expectedStatus !== undefined ? expectedStatus : defaultExpectedStatus | ||
214 | } | ||
215 | |||
216 | protected buildVideoPasswordHeader (videoPassword: string) { | ||
217 | return videoPassword !== undefined && videoPassword !== null | ||
218 | ? { 'x-peertube-video-password': videoPassword } | ||
219 | : undefined | ||
220 | } | ||
221 | } | ||
222 | |||
223 | export { | ||
224 | AbstractCommand | ||
225 | } | ||
diff --git a/packages/server-commands/src/shared/index.ts b/packages/server-commands/src/shared/index.ts new file mode 100644 index 000000000..795db3d55 --- /dev/null +++ b/packages/server-commands/src/shared/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './abstract-command.js' | |||
diff --git a/packages/server-commands/src/socket/index.ts b/packages/server-commands/src/socket/index.ts new file mode 100644 index 000000000..24b8f4b46 --- /dev/null +++ b/packages/server-commands/src/socket/index.ts | |||
@@ -0,0 +1 @@ | |||
export * from './socket-io-command.js' | |||
diff --git a/packages/server-commands/src/socket/socket-io-command.ts b/packages/server-commands/src/socket/socket-io-command.ts new file mode 100644 index 000000000..9c18c2a1f --- /dev/null +++ b/packages/server-commands/src/socket/socket-io-command.ts | |||
@@ -0,0 +1,24 @@ | |||
1 | import { io } from 'socket.io-client' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class SocketIOCommand extends AbstractCommand { | ||
5 | |||
6 | getUserNotificationSocket (options: OverrideCommandOptions = {}) { | ||
7 | return io(this.server.url + '/user-notifications', { | ||
8 | query: { accessToken: options.token ?? this.server.accessToken } | ||
9 | }) | ||
10 | } | ||
11 | |||
12 | getLiveNotificationSocket () { | ||
13 | return io(this.server.url + '/live-videos') | ||
14 | } | ||
15 | |||
16 | getRunnersSocket (options: { | ||
17 | runnerToken: string | ||
18 | }) { | ||
19 | return io(this.server.url + '/runners', { | ||
20 | reconnection: false, | ||
21 | auth: { runnerToken: options.runnerToken } | ||
22 | }) | ||
23 | } | ||
24 | } | ||
diff --git a/packages/server-commands/src/users/accounts-command.ts b/packages/server-commands/src/users/accounts-command.ts new file mode 100644 index 000000000..fd98b7eea --- /dev/null +++ b/packages/server-commands/src/users/accounts-command.ts | |||
@@ -0,0 +1,76 @@ | |||
1 | import { Account, AccountVideoRate, ActorFollow, HttpStatusCode, ResultList, VideoRateType } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class AccountsCommand extends AbstractCommand { | ||
5 | |||
6 | list (options: OverrideCommandOptions & { | ||
7 | sort?: string // default -createdAt | ||
8 | } = {}) { | ||
9 | const { sort = '-createdAt' } = options | ||
10 | const path = '/api/v1/accounts' | ||
11 | |||
12 | return this.getRequestBody<ResultList<Account>>({ | ||
13 | ...options, | ||
14 | |||
15 | path, | ||
16 | query: { sort }, | ||
17 | implicitToken: false, | ||
18 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
19 | }) | ||
20 | } | ||
21 | |||
22 | get (options: OverrideCommandOptions & { | ||
23 | accountName: string | ||
24 | }) { | ||
25 | const path = '/api/v1/accounts/' + options.accountName | ||
26 | |||
27 | return this.getRequestBody<Account>({ | ||
28 | ...options, | ||
29 | |||
30 | path, | ||
31 | implicitToken: false, | ||
32 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
33 | }) | ||
34 | } | ||
35 | |||
36 | listRatings (options: OverrideCommandOptions & { | ||
37 | accountName: string | ||
38 | rating?: VideoRateType | ||
39 | }) { | ||
40 | const { rating, accountName } = options | ||
41 | const path = '/api/v1/accounts/' + accountName + '/ratings' | ||
42 | |||
43 | const query = { rating } | ||
44 | |||
45 | return this.getRequestBody<ResultList<AccountVideoRate>>({ | ||
46 | ...options, | ||
47 | |||
48 | path, | ||
49 | query, | ||
50 | implicitToken: true, | ||
51 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
52 | }) | ||
53 | } | ||
54 | |||
55 | listFollowers (options: OverrideCommandOptions & { | ||
56 | accountName: string | ||
57 | start?: number | ||
58 | count?: number | ||
59 | sort?: string | ||
60 | search?: string | ||
61 | }) { | ||
62 | const { accountName, start, count, sort, search } = options | ||
63 | const path = '/api/v1/accounts/' + accountName + '/followers' | ||
64 | |||
65 | const query = { start, count, sort, search } | ||
66 | |||
67 | return this.getRequestBody<ResultList<ActorFollow>>({ | ||
68 | ...options, | ||
69 | |||
70 | path, | ||
71 | query, | ||
72 | implicitToken: true, | ||
73 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
74 | }) | ||
75 | } | ||
76 | } | ||
diff --git a/packages/server-commands/src/users/accounts.ts b/packages/server-commands/src/users/accounts.ts new file mode 100644 index 000000000..3b8b9d36a --- /dev/null +++ b/packages/server-commands/src/users/accounts.ts | |||
@@ -0,0 +1,15 @@ | |||
1 | import { PeerTubeServer } from '../server/server.js' | ||
2 | |||
3 | async function setDefaultAccountAvatar (serversArg: PeerTubeServer | PeerTubeServer[], token?: string) { | ||
4 | const servers = Array.isArray(serversArg) | ||
5 | ? serversArg | ||
6 | : [ serversArg ] | ||
7 | |||
8 | for (const server of servers) { | ||
9 | await server.users.updateMyAvatar({ fixture: 'avatar.png', token }) | ||
10 | } | ||
11 | } | ||
12 | |||
13 | export { | ||
14 | setDefaultAccountAvatar | ||
15 | } | ||
diff --git a/packages/server-commands/src/users/blocklist-command.ts b/packages/server-commands/src/users/blocklist-command.ts new file mode 100644 index 000000000..c77c56131 --- /dev/null +++ b/packages/server-commands/src/users/blocklist-command.ts | |||
@@ -0,0 +1,165 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ | ||
2 | |||
3 | import { AccountBlock, BlockStatus, HttpStatusCode, ResultList, ServerBlock } from '@peertube/peertube-models' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | type ListBlocklistOptions = OverrideCommandOptions & { | ||
7 | start: number | ||
8 | count: number | ||
9 | |||
10 | sort?: string // default -createdAt | ||
11 | |||
12 | search?: string | ||
13 | } | ||
14 | |||
15 | export class BlocklistCommand extends AbstractCommand { | ||
16 | |||
17 | listMyAccountBlocklist (options: ListBlocklistOptions) { | ||
18 | const path = '/api/v1/users/me/blocklist/accounts' | ||
19 | |||
20 | return this.listBlocklist<AccountBlock>(options, path) | ||
21 | } | ||
22 | |||
23 | listMyServerBlocklist (options: ListBlocklistOptions) { | ||
24 | const path = '/api/v1/users/me/blocklist/servers' | ||
25 | |||
26 | return this.listBlocklist<ServerBlock>(options, path) | ||
27 | } | ||
28 | |||
29 | listServerAccountBlocklist (options: ListBlocklistOptions) { | ||
30 | const path = '/api/v1/server/blocklist/accounts' | ||
31 | |||
32 | return this.listBlocklist<AccountBlock>(options, path) | ||
33 | } | ||
34 | |||
35 | listServerServerBlocklist (options: ListBlocklistOptions) { | ||
36 | const path = '/api/v1/server/blocklist/servers' | ||
37 | |||
38 | return this.listBlocklist<ServerBlock>(options, path) | ||
39 | } | ||
40 | |||
41 | // --------------------------------------------------------------------------- | ||
42 | |||
43 | getStatus (options: OverrideCommandOptions & { | ||
44 | accounts?: string[] | ||
45 | hosts?: string[] | ||
46 | }) { | ||
47 | const { accounts, hosts } = options | ||
48 | |||
49 | const path = '/api/v1/blocklist/status' | ||
50 | |||
51 | return this.getRequestBody<BlockStatus>({ | ||
52 | ...options, | ||
53 | |||
54 | path, | ||
55 | query: { | ||
56 | accounts, | ||
57 | hosts | ||
58 | }, | ||
59 | implicitToken: false, | ||
60 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
61 | }) | ||
62 | } | ||
63 | |||
64 | // --------------------------------------------------------------------------- | ||
65 | |||
66 | addToMyBlocklist (options: OverrideCommandOptions & { | ||
67 | account?: string | ||
68 | server?: string | ||
69 | }) { | ||
70 | const { account, server } = options | ||
71 | |||
72 | const path = account | ||
73 | ? '/api/v1/users/me/blocklist/accounts' | ||
74 | : '/api/v1/users/me/blocklist/servers' | ||
75 | |||
76 | return this.postBodyRequest({ | ||
77 | ...options, | ||
78 | |||
79 | path, | ||
80 | fields: { | ||
81 | accountName: account, | ||
82 | host: server | ||
83 | }, | ||
84 | implicitToken: true, | ||
85 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
86 | }) | ||
87 | } | ||
88 | |||
89 | addToServerBlocklist (options: OverrideCommandOptions & { | ||
90 | account?: string | ||
91 | server?: string | ||
92 | }) { | ||
93 | const { account, server } = options | ||
94 | |||
95 | const path = account | ||
96 | ? '/api/v1/server/blocklist/accounts' | ||
97 | : '/api/v1/server/blocklist/servers' | ||
98 | |||
99 | return this.postBodyRequest({ | ||
100 | ...options, | ||
101 | |||
102 | path, | ||
103 | fields: { | ||
104 | accountName: account, | ||
105 | host: server | ||
106 | }, | ||
107 | implicitToken: true, | ||
108 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
109 | }) | ||
110 | } | ||
111 | |||
112 | // --------------------------------------------------------------------------- | ||
113 | |||
114 | removeFromMyBlocklist (options: OverrideCommandOptions & { | ||
115 | account?: string | ||
116 | server?: string | ||
117 | }) { | ||
118 | const { account, server } = options | ||
119 | |||
120 | const path = account | ||
121 | ? '/api/v1/users/me/blocklist/accounts/' + account | ||
122 | : '/api/v1/users/me/blocklist/servers/' + server | ||
123 | |||
124 | return this.deleteRequest({ | ||
125 | ...options, | ||
126 | |||
127 | path, | ||
128 | implicitToken: true, | ||
129 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
130 | }) | ||
131 | } | ||
132 | |||
133 | removeFromServerBlocklist (options: OverrideCommandOptions & { | ||
134 | account?: string | ||
135 | server?: string | ||
136 | }) { | ||
137 | const { account, server } = options | ||
138 | |||
139 | const path = account | ||
140 | ? '/api/v1/server/blocklist/accounts/' + account | ||
141 | : '/api/v1/server/blocklist/servers/' + server | ||
142 | |||
143 | return this.deleteRequest({ | ||
144 | ...options, | ||
145 | |||
146 | path, | ||
147 | implicitToken: true, | ||
148 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
149 | }) | ||
150 | } | ||
151 | |||
152 | private listBlocklist <T> (options: ListBlocklistOptions, path: string) { | ||
153 | const { start, count, search, sort = '-createdAt' } = options | ||
154 | |||
155 | return this.getRequestBody<ResultList<T>>({ | ||
156 | ...options, | ||
157 | |||
158 | path, | ||
159 | query: { start, count, sort, search }, | ||
160 | implicitToken: true, | ||
161 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
162 | }) | ||
163 | } | ||
164 | |||
165 | } | ||
diff --git a/packages/server-commands/src/users/index.ts b/packages/server-commands/src/users/index.ts new file mode 100644 index 000000000..baa048a43 --- /dev/null +++ b/packages/server-commands/src/users/index.ts | |||
@@ -0,0 +1,10 @@ | |||
1 | export * from './accounts-command.js' | ||
2 | export * from './accounts.js' | ||
3 | export * from './blocklist-command.js' | ||
4 | export * from './login.js' | ||
5 | export * from './login-command.js' | ||
6 | export * from './notifications-command.js' | ||
7 | export * from './registrations-command.js' | ||
8 | export * from './subscriptions-command.js' | ||
9 | export * from './two-factor-command.js' | ||
10 | export * from './users-command.js' | ||
diff --git a/packages/server-commands/src/users/login-command.ts b/packages/server-commands/src/users/login-command.ts new file mode 100644 index 000000000..92d123dfc --- /dev/null +++ b/packages/server-commands/src/users/login-command.ts | |||
@@ -0,0 +1,159 @@ | |||
1 | import { HttpStatusCode, PeerTubeProblemDocument } from '@peertube/peertube-models' | ||
2 | import { unwrapBody } from '../requests/index.js' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | type LoginOptions = OverrideCommandOptions & { | ||
6 | client?: { id?: string, secret?: string } | ||
7 | user?: { username: string, password?: string } | ||
8 | otpToken?: string | ||
9 | } | ||
10 | |||
11 | export class LoginCommand extends AbstractCommand { | ||
12 | |||
13 | async login (options: LoginOptions = {}) { | ||
14 | const res = await this._login(options) | ||
15 | |||
16 | return this.unwrapLoginBody(res.body) | ||
17 | } | ||
18 | |||
19 | async loginAndGetResponse (options: LoginOptions = {}) { | ||
20 | const res = await this._login(options) | ||
21 | |||
22 | return { | ||
23 | res, | ||
24 | body: this.unwrapLoginBody(res.body) | ||
25 | } | ||
26 | } | ||
27 | |||
28 | getAccessToken (arg1?: { username: string, password?: string }): Promise<string> | ||
29 | getAccessToken (arg1: string, password?: string): Promise<string> | ||
30 | async getAccessToken (arg1?: { username: string, password?: string } | string, password?: string) { | ||
31 | let user: { username: string, password?: string } | ||
32 | |||
33 | if (!arg1) user = this.server.store.user | ||
34 | else if (typeof arg1 === 'object') user = arg1 | ||
35 | else user = { username: arg1, password } | ||
36 | |||
37 | try { | ||
38 | const body = await this.login({ user }) | ||
39 | |||
40 | return body.access_token | ||
41 | } catch (err) { | ||
42 | throw new Error(`Cannot authenticate. Please check your username/password. (${err})`) | ||
43 | } | ||
44 | } | ||
45 | |||
46 | loginUsingExternalToken (options: OverrideCommandOptions & { | ||
47 | username: string | ||
48 | externalAuthToken: string | ||
49 | }) { | ||
50 | const { username, externalAuthToken } = options | ||
51 | const path = '/api/v1/users/token' | ||
52 | |||
53 | const body = { | ||
54 | client_id: this.server.store.client.id, | ||
55 | client_secret: this.server.store.client.secret, | ||
56 | username, | ||
57 | response_type: 'code', | ||
58 | grant_type: 'password', | ||
59 | scope: 'upload', | ||
60 | externalAuthToken | ||
61 | } | ||
62 | |||
63 | return this.postBodyRequest({ | ||
64 | ...options, | ||
65 | |||
66 | path, | ||
67 | requestType: 'form', | ||
68 | fields: body, | ||
69 | implicitToken: false, | ||
70 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
71 | }) | ||
72 | } | ||
73 | |||
74 | logout (options: OverrideCommandOptions & { | ||
75 | token: string | ||
76 | }) { | ||
77 | const path = '/api/v1/users/revoke-token' | ||
78 | |||
79 | return unwrapBody<{ redirectUrl: string }>(this.postBodyRequest({ | ||
80 | ...options, | ||
81 | |||
82 | path, | ||
83 | requestType: 'form', | ||
84 | implicitToken: false, | ||
85 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
86 | })) | ||
87 | } | ||
88 | |||
89 | refreshToken (options: OverrideCommandOptions & { | ||
90 | refreshToken: string | ||
91 | }) { | ||
92 | const path = '/api/v1/users/token' | ||
93 | |||
94 | const body = { | ||
95 | client_id: this.server.store.client.id, | ||
96 | client_secret: this.server.store.client.secret, | ||
97 | refresh_token: options.refreshToken, | ||
98 | response_type: 'code', | ||
99 | grant_type: 'refresh_token' | ||
100 | } | ||
101 | |||
102 | return this.postBodyRequest({ | ||
103 | ...options, | ||
104 | |||
105 | path, | ||
106 | requestType: 'form', | ||
107 | fields: body, | ||
108 | implicitToken: false, | ||
109 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
110 | }) | ||
111 | } | ||
112 | |||
113 | getClient (options: OverrideCommandOptions = {}) { | ||
114 | const path = '/api/v1/oauth-clients/local' | ||
115 | |||
116 | return this.getRequestBody<{ client_id: string, client_secret: string }>({ | ||
117 | ...options, | ||
118 | |||
119 | path, | ||
120 | host: this.server.host, | ||
121 | implicitToken: false, | ||
122 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
123 | }) | ||
124 | } | ||
125 | |||
126 | private _login (options: LoginOptions) { | ||
127 | const { client = this.server.store.client, user = this.server.store.user, otpToken } = options | ||
128 | const path = '/api/v1/users/token' | ||
129 | |||
130 | const body = { | ||
131 | client_id: client.id, | ||
132 | client_secret: client.secret, | ||
133 | username: user.username, | ||
134 | password: user.password ?? 'password', | ||
135 | response_type: 'code', | ||
136 | grant_type: 'password', | ||
137 | scope: 'upload' | ||
138 | } | ||
139 | |||
140 | const headers = otpToken | ||
141 | ? { 'x-peertube-otp': otpToken } | ||
142 | : {} | ||
143 | |||
144 | return this.postBodyRequest({ | ||
145 | ...options, | ||
146 | |||
147 | path, | ||
148 | headers, | ||
149 | requestType: 'form', | ||
150 | fields: body, | ||
151 | implicitToken: false, | ||
152 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
153 | }) | ||
154 | } | ||
155 | |||
156 | private unwrapLoginBody (body: any) { | ||
157 | return body as { access_token: string, refresh_token: string } & PeerTubeProblemDocument | ||
158 | } | ||
159 | } | ||
diff --git a/packages/server-commands/src/users/login.ts b/packages/server-commands/src/users/login.ts new file mode 100644 index 000000000..c48c42c72 --- /dev/null +++ b/packages/server-commands/src/users/login.ts | |||
@@ -0,0 +1,19 @@ | |||
1 | import { PeerTubeServer } from '../server/server.js' | ||
2 | |||
3 | function setAccessTokensToServers (servers: PeerTubeServer[]) { | ||
4 | const tasks: Promise<any>[] = [] | ||
5 | |||
6 | for (const server of servers) { | ||
7 | const p = server.login.getAccessToken() | ||
8 | .then(t => { server.accessToken = t }) | ||
9 | tasks.push(p) | ||
10 | } | ||
11 | |||
12 | return Promise.all(tasks) | ||
13 | } | ||
14 | |||
15 | // --------------------------------------------------------------------------- | ||
16 | |||
17 | export { | ||
18 | setAccessTokensToServers | ||
19 | } | ||
diff --git a/packages/server-commands/src/users/notifications-command.ts b/packages/server-commands/src/users/notifications-command.ts new file mode 100644 index 000000000..d90d56900 --- /dev/null +++ b/packages/server-commands/src/users/notifications-command.ts | |||
@@ -0,0 +1,85 @@ | |||
1 | import { HttpStatusCode, ResultList, UserNotification, UserNotificationSetting } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class NotificationsCommand extends AbstractCommand { | ||
5 | |||
6 | updateMySettings (options: OverrideCommandOptions & { | ||
7 | settings: UserNotificationSetting | ||
8 | }) { | ||
9 | const path = '/api/v1/users/me/notification-settings' | ||
10 | |||
11 | return this.putBodyRequest({ | ||
12 | ...options, | ||
13 | |||
14 | path, | ||
15 | fields: options.settings, | ||
16 | implicitToken: true, | ||
17 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
18 | }) | ||
19 | } | ||
20 | |||
21 | list (options: OverrideCommandOptions & { | ||
22 | start?: number | ||
23 | count?: number | ||
24 | unread?: boolean | ||
25 | sort?: string | ||
26 | }) { | ||
27 | const { start, count, unread, sort = '-createdAt' } = options | ||
28 | const path = '/api/v1/users/me/notifications' | ||
29 | |||
30 | return this.getRequestBody<ResultList<UserNotification>>({ | ||
31 | ...options, | ||
32 | |||
33 | path, | ||
34 | query: { | ||
35 | start, | ||
36 | count, | ||
37 | sort, | ||
38 | unread | ||
39 | }, | ||
40 | implicitToken: true, | ||
41 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
42 | }) | ||
43 | } | ||
44 | |||
45 | markAsRead (options: OverrideCommandOptions & { | ||
46 | ids: number[] | ||
47 | }) { | ||
48 | const { ids } = options | ||
49 | const path = '/api/v1/users/me/notifications/read' | ||
50 | |||
51 | return this.postBodyRequest({ | ||
52 | ...options, | ||
53 | |||
54 | path, | ||
55 | fields: { ids }, | ||
56 | implicitToken: true, | ||
57 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
58 | }) | ||
59 | } | ||
60 | |||
61 | markAsReadAll (options: OverrideCommandOptions) { | ||
62 | const path = '/api/v1/users/me/notifications/read-all' | ||
63 | |||
64 | return this.postBodyRequest({ | ||
65 | ...options, | ||
66 | |||
67 | path, | ||
68 | implicitToken: true, | ||
69 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
70 | }) | ||
71 | } | ||
72 | |||
73 | async getLatest (options: OverrideCommandOptions = {}) { | ||
74 | const { total, data } = await this.list({ | ||
75 | ...options, | ||
76 | start: 0, | ||
77 | count: 1, | ||
78 | sort: '-createdAt' | ||
79 | }) | ||
80 | |||
81 | if (total === 0) return undefined | ||
82 | |||
83 | return data[0] | ||
84 | } | ||
85 | } | ||
diff --git a/packages/server-commands/src/users/registrations-command.ts b/packages/server-commands/src/users/registrations-command.ts new file mode 100644 index 000000000..2111fbd39 --- /dev/null +++ b/packages/server-commands/src/users/registrations-command.ts | |||
@@ -0,0 +1,157 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | HttpStatusCode, | ||
4 | ResultList, | ||
5 | UserRegistration, | ||
6 | UserRegistrationRequest, | ||
7 | UserRegistrationUpdateState | ||
8 | } from '@peertube/peertube-models' | ||
9 | import { unwrapBody } from '../requests/index.js' | ||
10 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
11 | |||
12 | export class RegistrationsCommand extends AbstractCommand { | ||
13 | |||
14 | register (options: OverrideCommandOptions & Partial<UserRegistrationRequest> & Pick<UserRegistrationRequest, 'username'>) { | ||
15 | const { password = 'password', email = options.username + '@example.com' } = options | ||
16 | const path = '/api/v1/users/register' | ||
17 | |||
18 | return this.postBodyRequest({ | ||
19 | ...options, | ||
20 | |||
21 | path, | ||
22 | fields: { | ||
23 | ...pick(options, [ 'username', 'displayName', 'channel' ]), | ||
24 | |||
25 | password, | ||
26 | |||
27 | }, | ||
28 | implicitToken: false, | ||
29 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
30 | }) | ||
31 | } | ||
32 | |||
33 | requestRegistration ( | ||
34 | options: OverrideCommandOptions & Partial<UserRegistrationRequest> & Pick<UserRegistrationRequest, 'username' | 'registrationReason'> | ||
35 | ) { | ||
36 | const { password = 'password', email = options.username + '@example.com' } = options | ||
37 | const path = '/api/v1/users/registrations/request' | ||
38 | |||
39 | return unwrapBody<UserRegistration>(this.postBodyRequest({ | ||
40 | ...options, | ||
41 | |||
42 | path, | ||
43 | fields: { | ||
44 | ...pick(options, [ 'username', 'displayName', 'channel', 'registrationReason' ]), | ||
45 | |||
46 | password, | ||
47 | |||
48 | }, | ||
49 | implicitToken: false, | ||
50 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
51 | })) | ||
52 | } | ||
53 | |||
54 | // --------------------------------------------------------------------------- | ||
55 | |||
56 | accept (options: OverrideCommandOptions & { id: number } & UserRegistrationUpdateState) { | ||
57 | const { id } = options | ||
58 | const path = '/api/v1/users/registrations/' + id + '/accept' | ||
59 | |||
60 | return this.postBodyRequest({ | ||
61 | ...options, | ||
62 | |||
63 | path, | ||
64 | fields: pick(options, [ 'moderationResponse', 'preventEmailDelivery' ]), | ||
65 | implicitToken: true, | ||
66 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
67 | }) | ||
68 | } | ||
69 | |||
70 | reject (options: OverrideCommandOptions & { id: number } & UserRegistrationUpdateState) { | ||
71 | const { id } = options | ||
72 | const path = '/api/v1/users/registrations/' + id + '/reject' | ||
73 | |||
74 | return this.postBodyRequest({ | ||
75 | ...options, | ||
76 | |||
77 | path, | ||
78 | fields: pick(options, [ 'moderationResponse', 'preventEmailDelivery' ]), | ||
79 | implicitToken: true, | ||
80 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
81 | }) | ||
82 | } | ||
83 | |||
84 | // --------------------------------------------------------------------------- | ||
85 | |||
86 | delete (options: OverrideCommandOptions & { | ||
87 | id: number | ||
88 | }) { | ||
89 | const { id } = options | ||
90 | const path = '/api/v1/users/registrations/' + id | ||
91 | |||
92 | return this.deleteRequest({ | ||
93 | ...options, | ||
94 | |||
95 | path, | ||
96 | implicitToken: true, | ||
97 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
98 | }) | ||
99 | } | ||
100 | |||
101 | // --------------------------------------------------------------------------- | ||
102 | |||
103 | list (options: OverrideCommandOptions & { | ||
104 | start?: number | ||
105 | count?: number | ||
106 | sort?: string | ||
107 | search?: string | ||
108 | } = {}) { | ||
109 | const path = '/api/v1/users/registrations' | ||
110 | |||
111 | return this.getRequestBody<ResultList<UserRegistration>>({ | ||
112 | ...options, | ||
113 | |||
114 | path, | ||
115 | query: pick(options, [ 'start', 'count', 'sort', 'search' ]), | ||
116 | implicitToken: true, | ||
117 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
118 | }) | ||
119 | } | ||
120 | |||
121 | // --------------------------------------------------------------------------- | ||
122 | |||
123 | askSendVerifyEmail (options: OverrideCommandOptions & { | ||
124 | email: string | ||
125 | }) { | ||
126 | const { email } = options | ||
127 | const path = '/api/v1/users/registrations/ask-send-verify-email' | ||
128 | |||
129 | return this.postBodyRequest({ | ||
130 | ...options, | ||
131 | |||
132 | path, | ||
133 | fields: { email }, | ||
134 | implicitToken: false, | ||
135 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
136 | }) | ||
137 | } | ||
138 | |||
139 | verifyEmail (options: OverrideCommandOptions & { | ||
140 | registrationId: number | ||
141 | verificationString: string | ||
142 | }) { | ||
143 | const { registrationId, verificationString } = options | ||
144 | const path = '/api/v1/users/registrations/' + registrationId + '/verify-email' | ||
145 | |||
146 | return this.postBodyRequest({ | ||
147 | ...options, | ||
148 | |||
149 | path, | ||
150 | fields: { | ||
151 | verificationString | ||
152 | }, | ||
153 | implicitToken: false, | ||
154 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
155 | }) | ||
156 | } | ||
157 | } | ||
diff --git a/packages/server-commands/src/users/subscriptions-command.ts b/packages/server-commands/src/users/subscriptions-command.ts new file mode 100644 index 000000000..52a1f0e51 --- /dev/null +++ b/packages/server-commands/src/users/subscriptions-command.ts | |||
@@ -0,0 +1,83 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoChannel } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class SubscriptionsCommand extends AbstractCommand { | ||
5 | |||
6 | add (options: OverrideCommandOptions & { | ||
7 | targetUri: string | ||
8 | }) { | ||
9 | const path = '/api/v1/users/me/subscriptions' | ||
10 | |||
11 | return this.postBodyRequest({ | ||
12 | ...options, | ||
13 | |||
14 | path, | ||
15 | fields: { uri: options.targetUri }, | ||
16 | implicitToken: true, | ||
17 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
18 | }) | ||
19 | } | ||
20 | |||
21 | list (options: OverrideCommandOptions & { | ||
22 | sort?: string // default -createdAt | ||
23 | search?: string | ||
24 | } = {}) { | ||
25 | const { sort = '-createdAt', search } = options | ||
26 | const path = '/api/v1/users/me/subscriptions' | ||
27 | |||
28 | return this.getRequestBody<ResultList<VideoChannel>>({ | ||
29 | ...options, | ||
30 | |||
31 | path, | ||
32 | query: { | ||
33 | sort, | ||
34 | search | ||
35 | }, | ||
36 | implicitToken: true, | ||
37 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | get (options: OverrideCommandOptions & { | ||
42 | uri: string | ||
43 | }) { | ||
44 | const path = '/api/v1/users/me/subscriptions/' + options.uri | ||
45 | |||
46 | return this.getRequestBody<VideoChannel>({ | ||
47 | ...options, | ||
48 | |||
49 | path, | ||
50 | implicitToken: true, | ||
51 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
52 | }) | ||
53 | } | ||
54 | |||
55 | remove (options: OverrideCommandOptions & { | ||
56 | uri: string | ||
57 | }) { | ||
58 | const path = '/api/v1/users/me/subscriptions/' + options.uri | ||
59 | |||
60 | return this.deleteRequest({ | ||
61 | ...options, | ||
62 | |||
63 | path, | ||
64 | implicitToken: true, | ||
65 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
66 | }) | ||
67 | } | ||
68 | |||
69 | exist (options: OverrideCommandOptions & { | ||
70 | uris: string[] | ||
71 | }) { | ||
72 | const path = '/api/v1/users/me/subscriptions/exist' | ||
73 | |||
74 | return this.getRequestBody<{ [id: string ]: boolean }>({ | ||
75 | ...options, | ||
76 | |||
77 | path, | ||
78 | query: { 'uris[]': options.uris }, | ||
79 | implicitToken: true, | ||
80 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
81 | }) | ||
82 | } | ||
83 | } | ||
diff --git a/packages/server-commands/src/users/two-factor-command.ts b/packages/server-commands/src/users/two-factor-command.ts new file mode 100644 index 000000000..cf3d6cb68 --- /dev/null +++ b/packages/server-commands/src/users/two-factor-command.ts | |||
@@ -0,0 +1,92 @@ | |||
1 | import { TOTP } from 'otpauth' | ||
2 | import { HttpStatusCode, TwoFactorEnableResult } from '@peertube/peertube-models' | ||
3 | import { unwrapBody } from '../requests/index.js' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | export class TwoFactorCommand extends AbstractCommand { | ||
7 | |||
8 | static buildOTP (options: { | ||
9 | secret: string | ||
10 | }) { | ||
11 | const { secret } = options | ||
12 | |||
13 | return new TOTP({ | ||
14 | issuer: 'PeerTube', | ||
15 | algorithm: 'SHA1', | ||
16 | digits: 6, | ||
17 | period: 30, | ||
18 | secret | ||
19 | }) | ||
20 | } | ||
21 | |||
22 | request (options: OverrideCommandOptions & { | ||
23 | userId: number | ||
24 | currentPassword?: string | ||
25 | }) { | ||
26 | const { currentPassword, userId } = options | ||
27 | |||
28 | const path = '/api/v1/users/' + userId + '/two-factor/request' | ||
29 | |||
30 | return unwrapBody<TwoFactorEnableResult>(this.postBodyRequest({ | ||
31 | ...options, | ||
32 | |||
33 | path, | ||
34 | fields: { currentPassword }, | ||
35 | implicitToken: true, | ||
36 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
37 | })) | ||
38 | } | ||
39 | |||
40 | confirmRequest (options: OverrideCommandOptions & { | ||
41 | userId: number | ||
42 | requestToken: string | ||
43 | otpToken: string | ||
44 | }) { | ||
45 | const { userId, requestToken, otpToken } = options | ||
46 | |||
47 | const path = '/api/v1/users/' + userId + '/two-factor/confirm-request' | ||
48 | |||
49 | return this.postBodyRequest({ | ||
50 | ...options, | ||
51 | |||
52 | path, | ||
53 | fields: { requestToken, otpToken }, | ||
54 | implicitToken: true, | ||
55 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
56 | }) | ||
57 | } | ||
58 | |||
59 | disable (options: OverrideCommandOptions & { | ||
60 | userId: number | ||
61 | currentPassword?: string | ||
62 | }) { | ||
63 | const { userId, currentPassword } = options | ||
64 | const path = '/api/v1/users/' + userId + '/two-factor/disable' | ||
65 | |||
66 | return this.postBodyRequest({ | ||
67 | ...options, | ||
68 | |||
69 | path, | ||
70 | fields: { currentPassword }, | ||
71 | implicitToken: true, | ||
72 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
73 | }) | ||
74 | } | ||
75 | |||
76 | async requestAndConfirm (options: OverrideCommandOptions & { | ||
77 | userId: number | ||
78 | currentPassword?: string | ||
79 | }) { | ||
80 | const { userId, currentPassword } = options | ||
81 | |||
82 | const { otpRequest } = await this.request({ userId, currentPassword }) | ||
83 | |||
84 | await this.confirmRequest({ | ||
85 | userId, | ||
86 | requestToken: otpRequest.requestToken, | ||
87 | otpToken: TwoFactorCommand.buildOTP({ secret: otpRequest.secret }).generate() | ||
88 | }) | ||
89 | |||
90 | return otpRequest | ||
91 | } | ||
92 | } | ||
diff --git a/packages/server-commands/src/users/users-command.ts b/packages/server-commands/src/users/users-command.ts new file mode 100644 index 000000000..d3b11939e --- /dev/null +++ b/packages/server-commands/src/users/users-command.ts | |||
@@ -0,0 +1,389 @@ | |||
1 | import { omit, pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | HttpStatusCode, | ||
4 | MyUser, | ||
5 | ResultList, | ||
6 | ScopedToken, | ||
7 | User, | ||
8 | UserAdminFlagType, | ||
9 | UserCreateResult, | ||
10 | UserRole, | ||
11 | UserRoleType, | ||
12 | UserUpdate, | ||
13 | UserUpdateMe, | ||
14 | UserVideoQuota, | ||
15 | UserVideoRate | ||
16 | } from '@peertube/peertube-models' | ||
17 | import { unwrapBody } from '../requests/index.js' | ||
18 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
19 | |||
20 | export class UsersCommand extends AbstractCommand { | ||
21 | |||
22 | askResetPassword (options: OverrideCommandOptions & { | ||
23 | email: string | ||
24 | }) { | ||
25 | const { email } = options | ||
26 | const path = '/api/v1/users/ask-reset-password' | ||
27 | |||
28 | return this.postBodyRequest({ | ||
29 | ...options, | ||
30 | |||
31 | path, | ||
32 | fields: { email }, | ||
33 | implicitToken: false, | ||
34 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
35 | }) | ||
36 | } | ||
37 | |||
38 | resetPassword (options: OverrideCommandOptions & { | ||
39 | userId: number | ||
40 | verificationString: string | ||
41 | password: string | ||
42 | }) { | ||
43 | const { userId, verificationString, password } = options | ||
44 | const path = '/api/v1/users/' + userId + '/reset-password' | ||
45 | |||
46 | return this.postBodyRequest({ | ||
47 | ...options, | ||
48 | |||
49 | path, | ||
50 | fields: { password, verificationString }, | ||
51 | implicitToken: false, | ||
52 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | // --------------------------------------------------------------------------- | ||
57 | |||
58 | askSendVerifyEmail (options: OverrideCommandOptions & { | ||
59 | email: string | ||
60 | }) { | ||
61 | const { email } = options | ||
62 | const path = '/api/v1/users/ask-send-verify-email' | ||
63 | |||
64 | return this.postBodyRequest({ | ||
65 | ...options, | ||
66 | |||
67 | path, | ||
68 | fields: { email }, | ||
69 | implicitToken: false, | ||
70 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
71 | }) | ||
72 | } | ||
73 | |||
74 | verifyEmail (options: OverrideCommandOptions & { | ||
75 | userId: number | ||
76 | verificationString: string | ||
77 | isPendingEmail?: boolean // default false | ||
78 | }) { | ||
79 | const { userId, verificationString, isPendingEmail = false } = options | ||
80 | const path = '/api/v1/users/' + userId + '/verify-email' | ||
81 | |||
82 | return this.postBodyRequest({ | ||
83 | ...options, | ||
84 | |||
85 | path, | ||
86 | fields: { | ||
87 | verificationString, | ||
88 | isPendingEmail | ||
89 | }, | ||
90 | implicitToken: false, | ||
91 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
92 | }) | ||
93 | } | ||
94 | |||
95 | // --------------------------------------------------------------------------- | ||
96 | |||
97 | banUser (options: OverrideCommandOptions & { | ||
98 | userId: number | ||
99 | reason?: string | ||
100 | }) { | ||
101 | const { userId, reason } = options | ||
102 | const path = '/api/v1/users' + '/' + userId + '/block' | ||
103 | |||
104 | return this.postBodyRequest({ | ||
105 | ...options, | ||
106 | |||
107 | path, | ||
108 | fields: { reason }, | ||
109 | implicitToken: true, | ||
110 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
111 | }) | ||
112 | } | ||
113 | |||
114 | unbanUser (options: OverrideCommandOptions & { | ||
115 | userId: number | ||
116 | }) { | ||
117 | const { userId } = options | ||
118 | const path = '/api/v1/users' + '/' + userId + '/unblock' | ||
119 | |||
120 | return this.postBodyRequest({ | ||
121 | ...options, | ||
122 | |||
123 | path, | ||
124 | implicitToken: true, | ||
125 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
126 | }) | ||
127 | } | ||
128 | |||
129 | // --------------------------------------------------------------------------- | ||
130 | |||
131 | getMyScopedTokens (options: OverrideCommandOptions = {}) { | ||
132 | const path = '/api/v1/users/scoped-tokens' | ||
133 | |||
134 | return this.getRequestBody<ScopedToken>({ | ||
135 | ...options, | ||
136 | |||
137 | path, | ||
138 | implicitToken: true, | ||
139 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
140 | }) | ||
141 | } | ||
142 | |||
143 | renewMyScopedTokens (options: OverrideCommandOptions = {}) { | ||
144 | const path = '/api/v1/users/scoped-tokens' | ||
145 | |||
146 | return this.postBodyRequest({ | ||
147 | ...options, | ||
148 | |||
149 | path, | ||
150 | implicitToken: true, | ||
151 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
152 | }) | ||
153 | } | ||
154 | |||
155 | // --------------------------------------------------------------------------- | ||
156 | |||
157 | create (options: OverrideCommandOptions & { | ||
158 | username: string | ||
159 | password?: string | ||
160 | videoQuota?: number | ||
161 | videoQuotaDaily?: number | ||
162 | role?: UserRoleType | ||
163 | adminFlags?: UserAdminFlagType | ||
164 | }) { | ||
165 | const { | ||
166 | username, | ||
167 | adminFlags, | ||
168 | password = 'password', | ||
169 | videoQuota, | ||
170 | videoQuotaDaily, | ||
171 | role = UserRole.USER | ||
172 | } = options | ||
173 | |||
174 | const path = '/api/v1/users' | ||
175 | |||
176 | return unwrapBody<{ user: UserCreateResult }>(this.postBodyRequest({ | ||
177 | ...options, | ||
178 | |||
179 | path, | ||
180 | fields: { | ||
181 | username, | ||
182 | password, | ||
183 | role, | ||
184 | adminFlags, | ||
185 | email: username + '@example.com', | ||
186 | videoQuota, | ||
187 | videoQuotaDaily | ||
188 | }, | ||
189 | implicitToken: true, | ||
190 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
191 | })).then(res => res.user) | ||
192 | } | ||
193 | |||
194 | async generate (username: string, role?: UserRoleType) { | ||
195 | const password = 'password' | ||
196 | const user = await this.create({ username, password, role }) | ||
197 | |||
198 | const token = await this.server.login.getAccessToken({ username, password }) | ||
199 | |||
200 | const me = await this.getMyInfo({ token }) | ||
201 | |||
202 | return { | ||
203 | token, | ||
204 | userId: user.id, | ||
205 | userChannelId: me.videoChannels[0].id, | ||
206 | userChannelName: me.videoChannels[0].name, | ||
207 | password | ||
208 | } | ||
209 | } | ||
210 | |||
211 | async generateUserAndToken (username: string, role?: UserRoleType) { | ||
212 | const password = 'password' | ||
213 | await this.create({ username, password, role }) | ||
214 | |||
215 | return this.server.login.getAccessToken({ username, password }) | ||
216 | } | ||
217 | |||
218 | // --------------------------------------------------------------------------- | ||
219 | |||
220 | getMyInfo (options: OverrideCommandOptions = {}) { | ||
221 | const path = '/api/v1/users/me' | ||
222 | |||
223 | return this.getRequestBody<MyUser>({ | ||
224 | ...options, | ||
225 | |||
226 | path, | ||
227 | implicitToken: true, | ||
228 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
229 | }) | ||
230 | } | ||
231 | |||
232 | getMyQuotaUsed (options: OverrideCommandOptions = {}) { | ||
233 | const path = '/api/v1/users/me/video-quota-used' | ||
234 | |||
235 | return this.getRequestBody<UserVideoQuota>({ | ||
236 | ...options, | ||
237 | |||
238 | path, | ||
239 | implicitToken: true, | ||
240 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
241 | }) | ||
242 | } | ||
243 | |||
244 | getMyRating (options: OverrideCommandOptions & { | ||
245 | videoId: number | string | ||
246 | }) { | ||
247 | const { videoId } = options | ||
248 | const path = '/api/v1/users/me/videos/' + videoId + '/rating' | ||
249 | |||
250 | return this.getRequestBody<UserVideoRate>({ | ||
251 | ...options, | ||
252 | |||
253 | path, | ||
254 | implicitToken: true, | ||
255 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
256 | }) | ||
257 | } | ||
258 | |||
259 | deleteMe (options: OverrideCommandOptions = {}) { | ||
260 | const path = '/api/v1/users/me' | ||
261 | |||
262 | return this.deleteRequest({ | ||
263 | ...options, | ||
264 | |||
265 | path, | ||
266 | implicitToken: true, | ||
267 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
268 | }) | ||
269 | } | ||
270 | |||
271 | updateMe (options: OverrideCommandOptions & UserUpdateMe) { | ||
272 | const path = '/api/v1/users/me' | ||
273 | |||
274 | const toSend: UserUpdateMe = omit(options, [ 'expectedStatus', 'token' ]) | ||
275 | |||
276 | return this.putBodyRequest({ | ||
277 | ...options, | ||
278 | |||
279 | path, | ||
280 | fields: toSend, | ||
281 | implicitToken: true, | ||
282 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
283 | }) | ||
284 | } | ||
285 | |||
286 | updateMyAvatar (options: OverrideCommandOptions & { | ||
287 | fixture: string | ||
288 | }) { | ||
289 | const { fixture } = options | ||
290 | const path = '/api/v1/users/me/avatar/pick' | ||
291 | |||
292 | return this.updateImageRequest({ | ||
293 | ...options, | ||
294 | |||
295 | path, | ||
296 | fixture, | ||
297 | fieldname: 'avatarfile', | ||
298 | |||
299 | implicitToken: true, | ||
300 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
301 | }) | ||
302 | } | ||
303 | |||
304 | // --------------------------------------------------------------------------- | ||
305 | |||
306 | get (options: OverrideCommandOptions & { | ||
307 | userId: number | ||
308 | withStats?: boolean // default false | ||
309 | }) { | ||
310 | const { userId, withStats } = options | ||
311 | const path = '/api/v1/users/' + userId | ||
312 | |||
313 | return this.getRequestBody<User>({ | ||
314 | ...options, | ||
315 | |||
316 | path, | ||
317 | query: { withStats }, | ||
318 | implicitToken: true, | ||
319 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
320 | }) | ||
321 | } | ||
322 | |||
323 | list (options: OverrideCommandOptions & { | ||
324 | start?: number | ||
325 | count?: number | ||
326 | sort?: string | ||
327 | search?: string | ||
328 | blocked?: boolean | ||
329 | } = {}) { | ||
330 | const path = '/api/v1/users' | ||
331 | |||
332 | return this.getRequestBody<ResultList<User>>({ | ||
333 | ...options, | ||
334 | |||
335 | path, | ||
336 | query: pick(options, [ 'start', 'count', 'sort', 'search', 'blocked' ]), | ||
337 | implicitToken: true, | ||
338 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
339 | }) | ||
340 | } | ||
341 | |||
342 | remove (options: OverrideCommandOptions & { | ||
343 | userId: number | ||
344 | }) { | ||
345 | const { userId } = options | ||
346 | const path = '/api/v1/users/' + userId | ||
347 | |||
348 | return this.deleteRequest({ | ||
349 | ...options, | ||
350 | |||
351 | path, | ||
352 | implicitToken: true, | ||
353 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
354 | }) | ||
355 | } | ||
356 | |||
357 | update (options: OverrideCommandOptions & { | ||
358 | userId: number | ||
359 | email?: string | ||
360 | emailVerified?: boolean | ||
361 | videoQuota?: number | ||
362 | videoQuotaDaily?: number | ||
363 | password?: string | ||
364 | adminFlags?: UserAdminFlagType | ||
365 | pluginAuth?: string | ||
366 | role?: UserRoleType | ||
367 | }) { | ||
368 | const path = '/api/v1/users/' + options.userId | ||
369 | |||
370 | const toSend: UserUpdate = {} | ||
371 | if (options.password !== undefined && options.password !== null) toSend.password = options.password | ||
372 | if (options.email !== undefined && options.email !== null) toSend.email = options.email | ||
373 | if (options.emailVerified !== undefined && options.emailVerified !== null) toSend.emailVerified = options.emailVerified | ||
374 | if (options.videoQuota !== undefined && options.videoQuota !== null) toSend.videoQuota = options.videoQuota | ||
375 | if (options.videoQuotaDaily !== undefined && options.videoQuotaDaily !== null) toSend.videoQuotaDaily = options.videoQuotaDaily | ||
376 | if (options.role !== undefined && options.role !== null) toSend.role = options.role | ||
377 | if (options.adminFlags !== undefined && options.adminFlags !== null) toSend.adminFlags = options.adminFlags | ||
378 | if (options.pluginAuth !== undefined) toSend.pluginAuth = options.pluginAuth | ||
379 | |||
380 | return this.putBodyRequest({ | ||
381 | ...options, | ||
382 | |||
383 | path, | ||
384 | fields: toSend, | ||
385 | implicitToken: true, | ||
386 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
387 | }) | ||
388 | } | ||
389 | } | ||
diff --git a/packages/server-commands/src/videos/blacklist-command.ts b/packages/server-commands/src/videos/blacklist-command.ts new file mode 100644 index 000000000..d41001e26 --- /dev/null +++ b/packages/server-commands/src/videos/blacklist-command.ts | |||
@@ -0,0 +1,74 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoBlacklist, VideoBlacklistType_Type } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class BlacklistCommand extends AbstractCommand { | ||
5 | |||
6 | add (options: OverrideCommandOptions & { | ||
7 | videoId: number | string | ||
8 | reason?: string | ||
9 | unfederate?: boolean | ||
10 | }) { | ||
11 | const { videoId, reason, unfederate } = options | ||
12 | const path = '/api/v1/videos/' + videoId + '/blacklist' | ||
13 | |||
14 | return this.postBodyRequest({ | ||
15 | ...options, | ||
16 | |||
17 | path, | ||
18 | fields: { reason, unfederate }, | ||
19 | implicitToken: true, | ||
20 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
21 | }) | ||
22 | } | ||
23 | |||
24 | update (options: OverrideCommandOptions & { | ||
25 | videoId: number | string | ||
26 | reason?: string | ||
27 | }) { | ||
28 | const { videoId, reason } = options | ||
29 | const path = '/api/v1/videos/' + videoId + '/blacklist' | ||
30 | |||
31 | return this.putBodyRequest({ | ||
32 | ...options, | ||
33 | |||
34 | path, | ||
35 | fields: { reason }, | ||
36 | implicitToken: true, | ||
37 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | remove (options: OverrideCommandOptions & { | ||
42 | videoId: number | string | ||
43 | }) { | ||
44 | const { videoId } = options | ||
45 | const path = '/api/v1/videos/' + videoId + '/blacklist' | ||
46 | |||
47 | return this.deleteRequest({ | ||
48 | ...options, | ||
49 | |||
50 | path, | ||
51 | implicitToken: true, | ||
52 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | list (options: OverrideCommandOptions & { | ||
57 | sort?: string | ||
58 | type?: VideoBlacklistType_Type | ||
59 | } = {}) { | ||
60 | const { sort, type } = options | ||
61 | const path = '/api/v1/videos/blacklist/' | ||
62 | |||
63 | const query = { sort, type } | ||
64 | |||
65 | return this.getRequestBody<ResultList<VideoBlacklist>>({ | ||
66 | ...options, | ||
67 | |||
68 | path, | ||
69 | query, | ||
70 | implicitToken: true, | ||
71 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
72 | }) | ||
73 | } | ||
74 | } | ||
diff --git a/packages/server-commands/src/videos/captions-command.ts b/packages/server-commands/src/videos/captions-command.ts new file mode 100644 index 000000000..a8336aa27 --- /dev/null +++ b/packages/server-commands/src/videos/captions-command.ts | |||
@@ -0,0 +1,67 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoCaption } from '@peertube/peertube-models' | ||
2 | import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | export class CaptionsCommand extends AbstractCommand { | ||
6 | |||
7 | add (options: OverrideCommandOptions & { | ||
8 | videoId: string | number | ||
9 | language: string | ||
10 | fixture: string | ||
11 | mimeType?: string | ||
12 | }) { | ||
13 | const { videoId, language, fixture, mimeType } = options | ||
14 | |||
15 | const path = '/api/v1/videos/' + videoId + '/captions/' + language | ||
16 | |||
17 | const captionfile = buildAbsoluteFixturePath(fixture) | ||
18 | const captionfileAttach = mimeType | ||
19 | ? [ captionfile, { contentType: mimeType } ] | ||
20 | : captionfile | ||
21 | |||
22 | return this.putUploadRequest({ | ||
23 | ...options, | ||
24 | |||
25 | path, | ||
26 | fields: {}, | ||
27 | attaches: { | ||
28 | captionfile: captionfileAttach | ||
29 | }, | ||
30 | implicitToken: true, | ||
31 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
32 | }) | ||
33 | } | ||
34 | |||
35 | list (options: OverrideCommandOptions & { | ||
36 | videoId: string | number | ||
37 | videoPassword?: string | ||
38 | }) { | ||
39 | const { videoId, videoPassword } = options | ||
40 | const path = '/api/v1/videos/' + videoId + '/captions' | ||
41 | |||
42 | return this.getRequestBody<ResultList<VideoCaption>>({ | ||
43 | ...options, | ||
44 | |||
45 | path, | ||
46 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
47 | implicitToken: false, | ||
48 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
49 | }) | ||
50 | } | ||
51 | |||
52 | delete (options: OverrideCommandOptions & { | ||
53 | videoId: string | number | ||
54 | language: string | ||
55 | }) { | ||
56 | const { videoId, language } = options | ||
57 | const path = '/api/v1/videos/' + videoId + '/captions/' + language | ||
58 | |||
59 | return this.deleteRequest({ | ||
60 | ...options, | ||
61 | |||
62 | path, | ||
63 | implicitToken: true, | ||
64 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
65 | }) | ||
66 | } | ||
67 | } | ||
diff --git a/packages/server-commands/src/videos/change-ownership-command.ts b/packages/server-commands/src/videos/change-ownership-command.ts new file mode 100644 index 000000000..1dc7c2c0f --- /dev/null +++ b/packages/server-commands/src/videos/change-ownership-command.ts | |||
@@ -0,0 +1,67 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoChangeOwnership } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class ChangeOwnershipCommand extends AbstractCommand { | ||
5 | |||
6 | create (options: OverrideCommandOptions & { | ||
7 | videoId: number | string | ||
8 | username: string | ||
9 | }) { | ||
10 | const { videoId, username } = options | ||
11 | const path = '/api/v1/videos/' + videoId + '/give-ownership' | ||
12 | |||
13 | return this.postBodyRequest({ | ||
14 | ...options, | ||
15 | |||
16 | path, | ||
17 | fields: { username }, | ||
18 | implicitToken: true, | ||
19 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
20 | }) | ||
21 | } | ||
22 | |||
23 | list (options: OverrideCommandOptions = {}) { | ||
24 | const path = '/api/v1/videos/ownership' | ||
25 | |||
26 | return this.getRequestBody<ResultList<VideoChangeOwnership>>({ | ||
27 | ...options, | ||
28 | |||
29 | path, | ||
30 | query: { sort: '-createdAt' }, | ||
31 | implicitToken: true, | ||
32 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
33 | }) | ||
34 | } | ||
35 | |||
36 | accept (options: OverrideCommandOptions & { | ||
37 | ownershipId: number | ||
38 | channelId: number | ||
39 | }) { | ||
40 | const { ownershipId, channelId } = options | ||
41 | const path = '/api/v1/videos/ownership/' + ownershipId + '/accept' | ||
42 | |||
43 | return this.postBodyRequest({ | ||
44 | ...options, | ||
45 | |||
46 | path, | ||
47 | fields: { channelId }, | ||
48 | implicitToken: true, | ||
49 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
50 | }) | ||
51 | } | ||
52 | |||
53 | refuse (options: OverrideCommandOptions & { | ||
54 | ownershipId: number | ||
55 | }) { | ||
56 | const { ownershipId } = options | ||
57 | const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse' | ||
58 | |||
59 | return this.postBodyRequest({ | ||
60 | ...options, | ||
61 | |||
62 | path, | ||
63 | implicitToken: true, | ||
64 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
65 | }) | ||
66 | } | ||
67 | } | ||
diff --git a/packages/server-commands/src/videos/channel-syncs-command.ts b/packages/server-commands/src/videos/channel-syncs-command.ts new file mode 100644 index 000000000..718000c8a --- /dev/null +++ b/packages/server-commands/src/videos/channel-syncs-command.ts | |||
@@ -0,0 +1,55 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@peertube/peertube-models' | ||
2 | import { pick } from '@peertube/peertube-core-utils' | ||
3 | import { unwrapBody } from '../requests/index.js' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | export class ChannelSyncsCommand extends AbstractCommand { | ||
7 | private static readonly API_PATH = '/api/v1/video-channel-syncs' | ||
8 | |||
9 | listByAccount (options: OverrideCommandOptions & { | ||
10 | accountName: string | ||
11 | start?: number | ||
12 | count?: number | ||
13 | sort?: string | ||
14 | }) { | ||
15 | const { accountName, sort = 'createdAt' } = options | ||
16 | |||
17 | const path = `/api/v1/accounts/${accountName}/video-channel-syncs` | ||
18 | |||
19 | return this.getRequestBody<ResultList<VideoChannelSync>>({ | ||
20 | ...options, | ||
21 | |||
22 | path, | ||
23 | query: { sort, ...pick(options, [ 'start', 'count' ]) }, | ||
24 | implicitToken: true, | ||
25 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
26 | }) | ||
27 | } | ||
28 | |||
29 | async create (options: OverrideCommandOptions & { | ||
30 | attributes: VideoChannelSyncCreate | ||
31 | }) { | ||
32 | return unwrapBody<{ videoChannelSync: VideoChannelSync }>(this.postBodyRequest({ | ||
33 | ...options, | ||
34 | |||
35 | path: ChannelSyncsCommand.API_PATH, | ||
36 | fields: options.attributes, | ||
37 | implicitToken: true, | ||
38 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
39 | })) | ||
40 | } | ||
41 | |||
42 | delete (options: OverrideCommandOptions & { | ||
43 | channelSyncId: number | ||
44 | }) { | ||
45 | const path = `${ChannelSyncsCommand.API_PATH}/${options.channelSyncId}` | ||
46 | |||
47 | return this.deleteRequest({ | ||
48 | ...options, | ||
49 | |||
50 | path, | ||
51 | implicitToken: true, | ||
52 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
53 | }) | ||
54 | } | ||
55 | } | ||
diff --git a/packages/server-commands/src/videos/channels-command.ts b/packages/server-commands/src/videos/channels-command.ts new file mode 100644 index 000000000..772677d39 --- /dev/null +++ b/packages/server-commands/src/videos/channels-command.ts | |||
@@ -0,0 +1,202 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | ActorFollow, | ||
4 | HttpStatusCode, | ||
5 | ResultList, | ||
6 | VideoChannel, | ||
7 | VideoChannelCreate, | ||
8 | VideoChannelCreateResult, | ||
9 | VideoChannelUpdate, | ||
10 | VideosImportInChannelCreate | ||
11 | } from '@peertube/peertube-models' | ||
12 | import { unwrapBody } from '../requests/index.js' | ||
13 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
14 | |||
15 | export class ChannelsCommand extends AbstractCommand { | ||
16 | |||
17 | list (options: OverrideCommandOptions & { | ||
18 | start?: number | ||
19 | count?: number | ||
20 | sort?: string | ||
21 | withStats?: boolean | ||
22 | } = {}) { | ||
23 | const path = '/api/v1/video-channels' | ||
24 | |||
25 | return this.getRequestBody<ResultList<VideoChannel>>({ | ||
26 | ...options, | ||
27 | |||
28 | path, | ||
29 | query: pick(options, [ 'start', 'count', 'sort', 'withStats' ]), | ||
30 | implicitToken: false, | ||
31 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
32 | }) | ||
33 | } | ||
34 | |||
35 | listByAccount (options: OverrideCommandOptions & { | ||
36 | accountName: string | ||
37 | start?: number | ||
38 | count?: number | ||
39 | sort?: string | ||
40 | withStats?: boolean | ||
41 | search?: string | ||
42 | }) { | ||
43 | const { accountName, sort = 'createdAt' } = options | ||
44 | const path = '/api/v1/accounts/' + accountName + '/video-channels' | ||
45 | |||
46 | return this.getRequestBody<ResultList<VideoChannel>>({ | ||
47 | ...options, | ||
48 | |||
49 | path, | ||
50 | query: { sort, ...pick(options, [ 'start', 'count', 'withStats', 'search' ]) }, | ||
51 | implicitToken: false, | ||
52 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | async create (options: OverrideCommandOptions & { | ||
57 | attributes: Partial<VideoChannelCreate> | ||
58 | }) { | ||
59 | const path = '/api/v1/video-channels/' | ||
60 | |||
61 | // Default attributes | ||
62 | const defaultAttributes = { | ||
63 | displayName: 'my super video channel', | ||
64 | description: 'my super channel description', | ||
65 | support: 'my super channel support' | ||
66 | } | ||
67 | const attributes = { ...defaultAttributes, ...options.attributes } | ||
68 | |||
69 | const body = await unwrapBody<{ videoChannel: VideoChannelCreateResult }>(this.postBodyRequest({ | ||
70 | ...options, | ||
71 | |||
72 | path, | ||
73 | fields: attributes, | ||
74 | implicitToken: true, | ||
75 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
76 | })) | ||
77 | |||
78 | return body.videoChannel | ||
79 | } | ||
80 | |||
81 | update (options: OverrideCommandOptions & { | ||
82 | channelName: string | ||
83 | attributes: VideoChannelUpdate | ||
84 | }) { | ||
85 | const { channelName, attributes } = options | ||
86 | const path = '/api/v1/video-channels/' + channelName | ||
87 | |||
88 | return this.putBodyRequest({ | ||
89 | ...options, | ||
90 | |||
91 | path, | ||
92 | fields: attributes, | ||
93 | implicitToken: true, | ||
94 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
95 | }) | ||
96 | } | ||
97 | |||
98 | delete (options: OverrideCommandOptions & { | ||
99 | channelName: string | ||
100 | }) { | ||
101 | const path = '/api/v1/video-channels/' + options.channelName | ||
102 | |||
103 | return this.deleteRequest({ | ||
104 | ...options, | ||
105 | |||
106 | path, | ||
107 | implicitToken: true, | ||
108 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
109 | }) | ||
110 | } | ||
111 | |||
112 | get (options: OverrideCommandOptions & { | ||
113 | channelName: string | ||
114 | }) { | ||
115 | const path = '/api/v1/video-channels/' + options.channelName | ||
116 | |||
117 | return this.getRequestBody<VideoChannel>({ | ||
118 | ...options, | ||
119 | |||
120 | path, | ||
121 | implicitToken: false, | ||
122 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
123 | }) | ||
124 | } | ||
125 | |||
126 | updateImage (options: OverrideCommandOptions & { | ||
127 | fixture: string | ||
128 | channelName: string | number | ||
129 | type: 'avatar' | 'banner' | ||
130 | }) { | ||
131 | const { channelName, fixture, type } = options | ||
132 | |||
133 | const path = `/api/v1/video-channels/${channelName}/${type}/pick` | ||
134 | |||
135 | return this.updateImageRequest({ | ||
136 | ...options, | ||
137 | |||
138 | path, | ||
139 | fixture, | ||
140 | fieldname: type + 'file', | ||
141 | |||
142 | implicitToken: true, | ||
143 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
144 | }) | ||
145 | } | ||
146 | |||
147 | deleteImage (options: OverrideCommandOptions & { | ||
148 | channelName: string | number | ||
149 | type: 'avatar' | 'banner' | ||
150 | }) { | ||
151 | const { channelName, type } = options | ||
152 | |||
153 | const path = `/api/v1/video-channels/${channelName}/${type}` | ||
154 | |||
155 | return this.deleteRequest({ | ||
156 | ...options, | ||
157 | |||
158 | path, | ||
159 | implicitToken: true, | ||
160 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
161 | }) | ||
162 | } | ||
163 | |||
164 | listFollowers (options: OverrideCommandOptions & { | ||
165 | channelName: string | ||
166 | start?: number | ||
167 | count?: number | ||
168 | sort?: string | ||
169 | search?: string | ||
170 | }) { | ||
171 | const { channelName, start, count, sort, search } = options | ||
172 | const path = '/api/v1/video-channels/' + channelName + '/followers' | ||
173 | |||
174 | const query = { start, count, sort, search } | ||
175 | |||
176 | return this.getRequestBody<ResultList<ActorFollow>>({ | ||
177 | ...options, | ||
178 | |||
179 | path, | ||
180 | query, | ||
181 | implicitToken: true, | ||
182 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
183 | }) | ||
184 | } | ||
185 | |||
186 | importVideos (options: OverrideCommandOptions & VideosImportInChannelCreate & { | ||
187 | channelName: string | ||
188 | }) { | ||
189 | const { channelName, externalChannelUrl, videoChannelSyncId } = options | ||
190 | |||
191 | const path = `/api/v1/video-channels/${channelName}/import-videos` | ||
192 | |||
193 | return this.postBodyRequest({ | ||
194 | ...options, | ||
195 | |||
196 | path, | ||
197 | fields: { externalChannelUrl, videoChannelSyncId }, | ||
198 | implicitToken: true, | ||
199 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
200 | }) | ||
201 | } | ||
202 | } | ||
diff --git a/packages/server-commands/src/videos/channels.ts b/packages/server-commands/src/videos/channels.ts new file mode 100644 index 000000000..e3487d024 --- /dev/null +++ b/packages/server-commands/src/videos/channels.ts | |||
@@ -0,0 +1,29 @@ | |||
1 | import { PeerTubeServer } from '../server/server.js' | ||
2 | |||
3 | function setDefaultVideoChannel (servers: PeerTubeServer[]) { | ||
4 | const tasks: Promise<any>[] = [] | ||
5 | |||
6 | for (const server of servers) { | ||
7 | const p = server.users.getMyInfo() | ||
8 | .then(user => { server.store.channel = user.videoChannels[0] }) | ||
9 | |||
10 | tasks.push(p) | ||
11 | } | ||
12 | |||
13 | return Promise.all(tasks) | ||
14 | } | ||
15 | |||
16 | async function setDefaultChannelAvatar (serversArg: PeerTubeServer | PeerTubeServer[], channelName: string = 'root_channel') { | ||
17 | const servers = Array.isArray(serversArg) | ||
18 | ? serversArg | ||
19 | : [ serversArg ] | ||
20 | |||
21 | for (const server of servers) { | ||
22 | await server.channels.updateImage({ channelName, fixture: 'avatar.png', type: 'avatar' }) | ||
23 | } | ||
24 | } | ||
25 | |||
26 | export { | ||
27 | setDefaultVideoChannel, | ||
28 | setDefaultChannelAvatar | ||
29 | } | ||
diff --git a/packages/server-commands/src/videos/comments-command.ts b/packages/server-commands/src/videos/comments-command.ts new file mode 100644 index 000000000..4835ae1fb --- /dev/null +++ b/packages/server-commands/src/videos/comments-command.ts | |||
@@ -0,0 +1,159 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { HttpStatusCode, ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@peertube/peertube-models' | ||
3 | import { unwrapBody } from '../requests/index.js' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | export class CommentsCommand extends AbstractCommand { | ||
7 | |||
8 | private lastVideoId: number | string | ||
9 | private lastThreadId: number | ||
10 | private lastReplyId: number | ||
11 | |||
12 | listForAdmin (options: OverrideCommandOptions & { | ||
13 | start?: number | ||
14 | count?: number | ||
15 | sort?: string | ||
16 | isLocal?: boolean | ||
17 | onLocalVideo?: boolean | ||
18 | search?: string | ||
19 | searchAccount?: string | ||
20 | searchVideo?: string | ||
21 | } = {}) { | ||
22 | const { sort = '-createdAt' } = options | ||
23 | const path = '/api/v1/videos/comments' | ||
24 | |||
25 | const query = { sort, ...pick(options, [ 'start', 'count', 'isLocal', 'onLocalVideo', 'search', 'searchAccount', 'searchVideo' ]) } | ||
26 | |||
27 | return this.getRequestBody<ResultList<VideoComment>>({ | ||
28 | ...options, | ||
29 | |||
30 | path, | ||
31 | query, | ||
32 | implicitToken: true, | ||
33 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
34 | }) | ||
35 | } | ||
36 | |||
37 | listThreads (options: OverrideCommandOptions & { | ||
38 | videoId: number | string | ||
39 | videoPassword?: string | ||
40 | start?: number | ||
41 | count?: number | ||
42 | sort?: string | ||
43 | }) { | ||
44 | const { start, count, sort, videoId, videoPassword } = options | ||
45 | const path = '/api/v1/videos/' + videoId + '/comment-threads' | ||
46 | |||
47 | return this.getRequestBody<VideoCommentThreads>({ | ||
48 | ...options, | ||
49 | |||
50 | path, | ||
51 | query: { start, count, sort }, | ||
52 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
53 | implicitToken: false, | ||
54 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
55 | }) | ||
56 | } | ||
57 | |||
58 | getThread (options: OverrideCommandOptions & { | ||
59 | videoId: number | string | ||
60 | threadId: number | ||
61 | }) { | ||
62 | const { videoId, threadId } = options | ||
63 | const path = '/api/v1/videos/' + videoId + '/comment-threads/' + threadId | ||
64 | |||
65 | return this.getRequestBody<VideoCommentThreadTree>({ | ||
66 | ...options, | ||
67 | |||
68 | path, | ||
69 | implicitToken: false, | ||
70 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
71 | }) | ||
72 | } | ||
73 | |||
74 | async createThread (options: OverrideCommandOptions & { | ||
75 | videoId: number | string | ||
76 | text: string | ||
77 | videoPassword?: string | ||
78 | }) { | ||
79 | const { videoId, text, videoPassword } = options | ||
80 | const path = '/api/v1/videos/' + videoId + '/comment-threads' | ||
81 | |||
82 | const body = await unwrapBody<{ comment: VideoComment }>(this.postBodyRequest({ | ||
83 | ...options, | ||
84 | |||
85 | path, | ||
86 | fields: { text }, | ||
87 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
88 | implicitToken: true, | ||
89 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
90 | })) | ||
91 | |||
92 | this.lastThreadId = body.comment?.id | ||
93 | this.lastVideoId = videoId | ||
94 | |||
95 | return body.comment | ||
96 | } | ||
97 | |||
98 | async addReply (options: OverrideCommandOptions & { | ||
99 | videoId: number | string | ||
100 | toCommentId: number | ||
101 | text: string | ||
102 | videoPassword?: string | ||
103 | }) { | ||
104 | const { videoId, toCommentId, text, videoPassword } = options | ||
105 | const path = '/api/v1/videos/' + videoId + '/comments/' + toCommentId | ||
106 | |||
107 | const body = await unwrapBody<{ comment: VideoComment }>(this.postBodyRequest({ | ||
108 | ...options, | ||
109 | |||
110 | path, | ||
111 | fields: { text }, | ||
112 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
113 | implicitToken: true, | ||
114 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
115 | })) | ||
116 | |||
117 | this.lastReplyId = body.comment?.id | ||
118 | |||
119 | return body.comment | ||
120 | } | ||
121 | |||
122 | async addReplyToLastReply (options: OverrideCommandOptions & { | ||
123 | text: string | ||
124 | }) { | ||
125 | return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastReplyId }) | ||
126 | } | ||
127 | |||
128 | async addReplyToLastThread (options: OverrideCommandOptions & { | ||
129 | text: string | ||
130 | }) { | ||
131 | return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastThreadId }) | ||
132 | } | ||
133 | |||
134 | async findCommentId (options: OverrideCommandOptions & { | ||
135 | videoId: number | string | ||
136 | text: string | ||
137 | }) { | ||
138 | const { videoId, text } = options | ||
139 | const { data } = await this.listThreads({ videoId, count: 25, sort: '-createdAt' }) | ||
140 | |||
141 | return data.find(c => c.text === text).id | ||
142 | } | ||
143 | |||
144 | delete (options: OverrideCommandOptions & { | ||
145 | videoId: number | string | ||
146 | commentId: number | ||
147 | }) { | ||
148 | const { videoId, commentId } = options | ||
149 | const path = '/api/v1/videos/' + videoId + '/comments/' + commentId | ||
150 | |||
151 | return this.deleteRequest({ | ||
152 | ...options, | ||
153 | |||
154 | path, | ||
155 | implicitToken: true, | ||
156 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
157 | }) | ||
158 | } | ||
159 | } | ||
diff --git a/packages/server-commands/src/videos/history-command.ts b/packages/server-commands/src/videos/history-command.ts new file mode 100644 index 000000000..fd032504a --- /dev/null +++ b/packages/server-commands/src/videos/history-command.ts | |||
@@ -0,0 +1,54 @@ | |||
1 | import { HttpStatusCode, ResultList, Video } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class HistoryCommand extends AbstractCommand { | ||
5 | |||
6 | list (options: OverrideCommandOptions & { | ||
7 | search?: string | ||
8 | } = {}) { | ||
9 | const { search } = options | ||
10 | const path = '/api/v1/users/me/history/videos' | ||
11 | |||
12 | return this.getRequestBody<ResultList<Video>>({ | ||
13 | ...options, | ||
14 | |||
15 | path, | ||
16 | query: { | ||
17 | search | ||
18 | }, | ||
19 | implicitToken: true, | ||
20 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
21 | }) | ||
22 | } | ||
23 | |||
24 | removeElement (options: OverrideCommandOptions & { | ||
25 | videoId: number | ||
26 | }) { | ||
27 | const { videoId } = options | ||
28 | const path = '/api/v1/users/me/history/videos/' + videoId | ||
29 | |||
30 | return this.deleteRequest({ | ||
31 | ...options, | ||
32 | |||
33 | path, | ||
34 | implicitToken: true, | ||
35 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
36 | }) | ||
37 | } | ||
38 | |||
39 | removeAll (options: OverrideCommandOptions & { | ||
40 | beforeDate?: string | ||
41 | } = {}) { | ||
42 | const { beforeDate } = options | ||
43 | const path = '/api/v1/users/me/history/videos/remove' | ||
44 | |||
45 | return this.postBodyRequest({ | ||
46 | ...options, | ||
47 | |||
48 | path, | ||
49 | fields: { beforeDate }, | ||
50 | implicitToken: true, | ||
51 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
52 | }) | ||
53 | } | ||
54 | } | ||
diff --git a/packages/server-commands/src/videos/imports-command.ts b/packages/server-commands/src/videos/imports-command.ts new file mode 100644 index 000000000..1a1931d64 --- /dev/null +++ b/packages/server-commands/src/videos/imports-command.ts | |||
@@ -0,0 +1,76 @@ | |||
1 | |||
2 | import { HttpStatusCode, ResultList, VideoImport, VideoImportCreate } from '@peertube/peertube-models' | ||
3 | import { unwrapBody } from '../requests/index.js' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | export class ImportsCommand extends AbstractCommand { | ||
7 | |||
8 | importVideo (options: OverrideCommandOptions & { | ||
9 | attributes: (VideoImportCreate | { torrentfile?: string, previewfile?: string, thumbnailfile?: string }) | ||
10 | }) { | ||
11 | const { attributes } = options | ||
12 | const path = '/api/v1/videos/imports' | ||
13 | |||
14 | let attaches: any = {} | ||
15 | if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile } | ||
16 | if (attributes.thumbnailfile) attaches = { thumbnailfile: attributes.thumbnailfile } | ||
17 | if (attributes.previewfile) attaches = { previewfile: attributes.previewfile } | ||
18 | |||
19 | return unwrapBody<VideoImport>(this.postUploadRequest({ | ||
20 | ...options, | ||
21 | |||
22 | path, | ||
23 | attaches, | ||
24 | fields: options.attributes, | ||
25 | implicitToken: true, | ||
26 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
27 | })) | ||
28 | } | ||
29 | |||
30 | delete (options: OverrideCommandOptions & { | ||
31 | importId: number | ||
32 | }) { | ||
33 | const path = '/api/v1/videos/imports/' + options.importId | ||
34 | |||
35 | return this.deleteRequest({ | ||
36 | ...options, | ||
37 | |||
38 | path, | ||
39 | implicitToken: true, | ||
40 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
41 | }) | ||
42 | } | ||
43 | |||
44 | cancel (options: OverrideCommandOptions & { | ||
45 | importId: number | ||
46 | }) { | ||
47 | const path = '/api/v1/videos/imports/' + options.importId + '/cancel' | ||
48 | |||
49 | return this.postBodyRequest({ | ||
50 | ...options, | ||
51 | |||
52 | path, | ||
53 | implicitToken: true, | ||
54 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
55 | }) | ||
56 | } | ||
57 | |||
58 | getMyVideoImports (options: OverrideCommandOptions & { | ||
59 | sort?: string | ||
60 | targetUrl?: string | ||
61 | videoChannelSyncId?: number | ||
62 | search?: string | ||
63 | } = {}) { | ||
64 | const { sort, targetUrl, videoChannelSyncId, search } = options | ||
65 | const path = '/api/v1/users/me/videos/imports' | ||
66 | |||
67 | return this.getRequestBody<ResultList<VideoImport>>({ | ||
68 | ...options, | ||
69 | |||
70 | path, | ||
71 | query: { sort, targetUrl, videoChannelSyncId, search }, | ||
72 | implicitToken: true, | ||
73 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
74 | }) | ||
75 | } | ||
76 | } | ||
diff --git a/packages/server-commands/src/videos/index.ts b/packages/server-commands/src/videos/index.ts new file mode 100644 index 000000000..970026d51 --- /dev/null +++ b/packages/server-commands/src/videos/index.ts | |||
@@ -0,0 +1,22 @@ | |||
1 | export * from './blacklist-command.js' | ||
2 | export * from './captions-command.js' | ||
3 | export * from './change-ownership-command.js' | ||
4 | export * from './channels.js' | ||
5 | export * from './channels-command.js' | ||
6 | export * from './channel-syncs-command.js' | ||
7 | export * from './comments-command.js' | ||
8 | export * from './history-command.js' | ||
9 | export * from './imports-command.js' | ||
10 | export * from './live-command.js' | ||
11 | export * from './live.js' | ||
12 | export * from './playlists-command.js' | ||
13 | export * from './services-command.js' | ||
14 | export * from './storyboard-command.js' | ||
15 | export * from './streaming-playlists-command.js' | ||
16 | export * from './comments-command.js' | ||
17 | export * from './video-studio-command.js' | ||
18 | export * from './video-token-command.js' | ||
19 | export * from './views-command.js' | ||
20 | export * from './videos-command.js' | ||
21 | export * from './video-passwords-command.js' | ||
22 | export * from './video-stats-command.js' | ||
diff --git a/packages/server-commands/src/videos/live-command.ts b/packages/server-commands/src/videos/live-command.ts new file mode 100644 index 000000000..793b64f40 --- /dev/null +++ b/packages/server-commands/src/videos/live-command.ts | |||
@@ -0,0 +1,339 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ | ||
2 | |||
3 | import { readdir } from 'fs/promises' | ||
4 | import { join } from 'path' | ||
5 | import { omit, wait } from '@peertube/peertube-core-utils' | ||
6 | import { | ||
7 | HttpStatusCode, | ||
8 | LiveVideo, | ||
9 | LiveVideoCreate, | ||
10 | LiveVideoSession, | ||
11 | LiveVideoUpdate, | ||
12 | ResultList, | ||
13 | VideoCreateResult, | ||
14 | VideoDetails, | ||
15 | VideoPrivacy, | ||
16 | VideoPrivacyType, | ||
17 | VideoState, | ||
18 | VideoStateType | ||
19 | } from '@peertube/peertube-models' | ||
20 | import { unwrapBody } from '../requests/index.js' | ||
21 | import { ObjectStorageCommand, PeerTubeServer } from '../server/index.js' | ||
22 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
23 | import { sendRTMPStream, testFfmpegStreamError } from './live.js' | ||
24 | |||
25 | export class LiveCommand extends AbstractCommand { | ||
26 | |||
27 | get (options: OverrideCommandOptions & { | ||
28 | videoId: number | string | ||
29 | }) { | ||
30 | const path = '/api/v1/videos/live' | ||
31 | |||
32 | return this.getRequestBody<LiveVideo>({ | ||
33 | ...options, | ||
34 | |||
35 | path: path + '/' + options.videoId, | ||
36 | implicitToken: true, | ||
37 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | // --------------------------------------------------------------------------- | ||
42 | |||
43 | listSessions (options: OverrideCommandOptions & { | ||
44 | videoId: number | string | ||
45 | }) { | ||
46 | const path = `/api/v1/videos/live/${options.videoId}/sessions` | ||
47 | |||
48 | return this.getRequestBody<ResultList<LiveVideoSession>>({ | ||
49 | ...options, | ||
50 | |||
51 | path, | ||
52 | implicitToken: true, | ||
53 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
54 | }) | ||
55 | } | ||
56 | |||
57 | async findLatestSession (options: OverrideCommandOptions & { | ||
58 | videoId: number | string | ||
59 | }) { | ||
60 | const { data: sessions } = await this.listSessions(options) | ||
61 | |||
62 | return sessions[sessions.length - 1] | ||
63 | } | ||
64 | |||
65 | getReplaySession (options: OverrideCommandOptions & { | ||
66 | videoId: number | string | ||
67 | }) { | ||
68 | const path = `/api/v1/videos/${options.videoId}/live-session` | ||
69 | |||
70 | return this.getRequestBody<LiveVideoSession>({ | ||
71 | ...options, | ||
72 | |||
73 | path, | ||
74 | implicitToken: true, | ||
75 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
76 | }) | ||
77 | } | ||
78 | |||
79 | // --------------------------------------------------------------------------- | ||
80 | |||
81 | update (options: OverrideCommandOptions & { | ||
82 | videoId: number | string | ||
83 | fields: LiveVideoUpdate | ||
84 | }) { | ||
85 | const { videoId, fields } = options | ||
86 | const path = '/api/v1/videos/live' | ||
87 | |||
88 | return this.putBodyRequest({ | ||
89 | ...options, | ||
90 | |||
91 | path: path + '/' + videoId, | ||
92 | fields, | ||
93 | implicitToken: true, | ||
94 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
95 | }) | ||
96 | } | ||
97 | |||
98 | async create (options: OverrideCommandOptions & { | ||
99 | fields: LiveVideoCreate | ||
100 | }) { | ||
101 | const { fields } = options | ||
102 | const path = '/api/v1/videos/live' | ||
103 | |||
104 | const attaches: any = {} | ||
105 | if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile | ||
106 | if (fields.previewfile) attaches.previewfile = fields.previewfile | ||
107 | |||
108 | const body = await unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({ | ||
109 | ...options, | ||
110 | |||
111 | path, | ||
112 | attaches, | ||
113 | fields: omit(fields, [ 'thumbnailfile', 'previewfile' ]), | ||
114 | implicitToken: true, | ||
115 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
116 | })) | ||
117 | |||
118 | return body.video | ||
119 | } | ||
120 | |||
121 | async quickCreate (options: OverrideCommandOptions & { | ||
122 | saveReplay: boolean | ||
123 | permanentLive: boolean | ||
124 | privacy?: VideoPrivacyType | ||
125 | videoPasswords?: string[] | ||
126 | }) { | ||
127 | const { saveReplay, permanentLive, privacy = VideoPrivacy.PUBLIC, videoPasswords } = options | ||
128 | |||
129 | const replaySettings = privacy === VideoPrivacy.PASSWORD_PROTECTED | ||
130 | ? { privacy: VideoPrivacy.PRIVATE } | ||
131 | : { privacy } | ||
132 | |||
133 | const { uuid } = await this.create({ | ||
134 | ...options, | ||
135 | |||
136 | fields: { | ||
137 | name: 'live', | ||
138 | permanentLive, | ||
139 | saveReplay, | ||
140 | replaySettings, | ||
141 | channelId: this.server.store.channel.id, | ||
142 | privacy, | ||
143 | videoPasswords | ||
144 | } | ||
145 | }) | ||
146 | |||
147 | const video = await this.server.videos.getWithToken({ id: uuid }) | ||
148 | const live = await this.get({ videoId: uuid }) | ||
149 | |||
150 | return { video, live } | ||
151 | } | ||
152 | |||
153 | // --------------------------------------------------------------------------- | ||
154 | |||
155 | async sendRTMPStreamInVideo (options: OverrideCommandOptions & { | ||
156 | videoId: number | string | ||
157 | fixtureName?: string | ||
158 | copyCodecs?: boolean | ||
159 | }) { | ||
160 | const { videoId, fixtureName, copyCodecs } = options | ||
161 | const videoLive = await this.get({ videoId }) | ||
162 | |||
163 | return sendRTMPStream({ rtmpBaseUrl: videoLive.rtmpUrl, streamKey: videoLive.streamKey, fixtureName, copyCodecs }) | ||
164 | } | ||
165 | |||
166 | async runAndTestStreamError (options: OverrideCommandOptions & { | ||
167 | videoId: number | string | ||
168 | shouldHaveError: boolean | ||
169 | }) { | ||
170 | const command = await this.sendRTMPStreamInVideo(options) | ||
171 | |||
172 | return testFfmpegStreamError(command, options.shouldHaveError) | ||
173 | } | ||
174 | |||
175 | // --------------------------------------------------------------------------- | ||
176 | |||
177 | waitUntilPublished (options: OverrideCommandOptions & { | ||
178 | videoId: number | string | ||
179 | }) { | ||
180 | const { videoId } = options | ||
181 | return this.waitUntilState({ videoId, state: VideoState.PUBLISHED }) | ||
182 | } | ||
183 | |||
184 | waitUntilWaiting (options: OverrideCommandOptions & { | ||
185 | videoId: number | string | ||
186 | }) { | ||
187 | const { videoId } = options | ||
188 | return this.waitUntilState({ videoId, state: VideoState.WAITING_FOR_LIVE }) | ||
189 | } | ||
190 | |||
191 | waitUntilEnded (options: OverrideCommandOptions & { | ||
192 | videoId: number | string | ||
193 | }) { | ||
194 | const { videoId } = options | ||
195 | return this.waitUntilState({ videoId, state: VideoState.LIVE_ENDED }) | ||
196 | } | ||
197 | |||
198 | async waitUntilSegmentGeneration (options: OverrideCommandOptions & { | ||
199 | server: PeerTubeServer | ||
200 | videoUUID: string | ||
201 | playlistNumber: number | ||
202 | segment: number | ||
203 | objectStorage?: ObjectStorageCommand | ||
204 | objectStorageBaseUrl?: string | ||
205 | }) { | ||
206 | const { | ||
207 | server, | ||
208 | objectStorage, | ||
209 | playlistNumber, | ||
210 | segment, | ||
211 | videoUUID, | ||
212 | objectStorageBaseUrl | ||
213 | } = options | ||
214 | |||
215 | const segmentName = `${playlistNumber}-00000${segment}.ts` | ||
216 | const baseUrl = objectStorage | ||
217 | ? join(objectStorageBaseUrl || objectStorage.getMockPlaylistBaseUrl(), 'hls') | ||
218 | : server.url + '/static/streaming-playlists/hls' | ||
219 | |||
220 | let error = true | ||
221 | |||
222 | while (error) { | ||
223 | try { | ||
224 | // Check fragment exists | ||
225 | await this.getRawRequest({ | ||
226 | ...options, | ||
227 | |||
228 | url: `${baseUrl}/${videoUUID}/${segmentName}`, | ||
229 | implicitToken: false, | ||
230 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
231 | }) | ||
232 | |||
233 | const video = await server.videos.get({ id: videoUUID }) | ||
234 | const hlsPlaylist = video.streamingPlaylists[0] | ||
235 | |||
236 | // Check SHA generation | ||
237 | const shaBody = await server.streamingPlaylists.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url, withRetry: !!objectStorage }) | ||
238 | if (!shaBody[segmentName]) { | ||
239 | throw new Error('Segment SHA does not exist') | ||
240 | } | ||
241 | |||
242 | // Check fragment is in m3u8 playlist | ||
243 | const subPlaylist = await server.streamingPlaylists.get({ url: `${baseUrl}/${video.uuid}/${playlistNumber}.m3u8` }) | ||
244 | if (!subPlaylist.includes(segmentName)) throw new Error('Fragment does not exist in playlist') | ||
245 | |||
246 | error = false | ||
247 | } catch { | ||
248 | error = true | ||
249 | await wait(100) | ||
250 | } | ||
251 | } | ||
252 | } | ||
253 | |||
254 | async waitUntilReplacedByReplay (options: OverrideCommandOptions & { | ||
255 | videoId: number | string | ||
256 | }) { | ||
257 | let video: VideoDetails | ||
258 | |||
259 | do { | ||
260 | video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId }) | ||
261 | |||
262 | await wait(500) | ||
263 | } while (video.isLive === true || video.state.id !== VideoState.PUBLISHED) | ||
264 | } | ||
265 | |||
266 | // --------------------------------------------------------------------------- | ||
267 | |||
268 | getSegmentFile (options: OverrideCommandOptions & { | ||
269 | videoUUID: string | ||
270 | playlistNumber: number | ||
271 | segment: number | ||
272 | objectStorage?: ObjectStorageCommand | ||
273 | }) { | ||
274 | const { playlistNumber, segment, videoUUID, objectStorage } = options | ||
275 | |||
276 | const segmentName = `${playlistNumber}-00000${segment}.ts` | ||
277 | const baseUrl = objectStorage | ||
278 | ? objectStorage.getMockPlaylistBaseUrl() | ||
279 | : `${this.server.url}/static/streaming-playlists/hls` | ||
280 | |||
281 | const url = `${baseUrl}/${videoUUID}/${segmentName}` | ||
282 | |||
283 | return this.getRawRequest({ | ||
284 | ...options, | ||
285 | |||
286 | url, | ||
287 | implicitToken: false, | ||
288 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
289 | }) | ||
290 | } | ||
291 | |||
292 | getPlaylistFile (options: OverrideCommandOptions & { | ||
293 | videoUUID: string | ||
294 | playlistName: string | ||
295 | objectStorage?: ObjectStorageCommand | ||
296 | }) { | ||
297 | const { playlistName, videoUUID, objectStorage } = options | ||
298 | |||
299 | const baseUrl = objectStorage | ||
300 | ? objectStorage.getMockPlaylistBaseUrl() | ||
301 | : `${this.server.url}/static/streaming-playlists/hls` | ||
302 | |||
303 | const url = `${baseUrl}/${videoUUID}/${playlistName}` | ||
304 | |||
305 | return this.getRawRequest({ | ||
306 | ...options, | ||
307 | |||
308 | url, | ||
309 | implicitToken: false, | ||
310 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
311 | }) | ||
312 | } | ||
313 | |||
314 | // --------------------------------------------------------------------------- | ||
315 | |||
316 | async countPlaylists (options: OverrideCommandOptions & { | ||
317 | videoUUID: string | ||
318 | }) { | ||
319 | const basePath = this.server.servers.buildDirectory('streaming-playlists') | ||
320 | const hlsPath = join(basePath, 'hls', options.videoUUID) | ||
321 | |||
322 | const files = await readdir(hlsPath) | ||
323 | |||
324 | return files.filter(f => f.endsWith('.m3u8')).length | ||
325 | } | ||
326 | |||
327 | private async waitUntilState (options: OverrideCommandOptions & { | ||
328 | videoId: number | string | ||
329 | state: VideoStateType | ||
330 | }) { | ||
331 | let video: VideoDetails | ||
332 | |||
333 | do { | ||
334 | video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId }) | ||
335 | |||
336 | await wait(500) | ||
337 | } while (video.state.id !== options.state) | ||
338 | } | ||
339 | } | ||
diff --git a/packages/server-commands/src/videos/live.ts b/packages/server-commands/src/videos/live.ts new file mode 100644 index 000000000..05bfa1113 --- /dev/null +++ b/packages/server-commands/src/videos/live.ts | |||
@@ -0,0 +1,129 @@ | |||
1 | import { wait } from '@peertube/peertube-core-utils' | ||
2 | import { VideoDetails, VideoInclude, VideoPrivacy } from '@peertube/peertube-models' | ||
3 | import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils' | ||
4 | import ffmpeg, { FfmpegCommand } from 'fluent-ffmpeg' | ||
5 | import truncate from 'lodash-es/truncate.js' | ||
6 | import { PeerTubeServer } from '../server/server.js' | ||
7 | |||
8 | function sendRTMPStream (options: { | ||
9 | rtmpBaseUrl: string | ||
10 | streamKey: string | ||
11 | fixtureName?: string // default video_short.mp4 | ||
12 | copyCodecs?: boolean // default false | ||
13 | }) { | ||
14 | const { rtmpBaseUrl, streamKey, fixtureName = 'video_short.mp4', copyCodecs = false } = options | ||
15 | |||
16 | const fixture = buildAbsoluteFixturePath(fixtureName) | ||
17 | |||
18 | const command = ffmpeg(fixture) | ||
19 | command.inputOption('-stream_loop -1') | ||
20 | command.inputOption('-re') | ||
21 | |||
22 | if (copyCodecs) { | ||
23 | command.outputOption('-c copy') | ||
24 | } else { | ||
25 | command.outputOption('-c:v libx264') | ||
26 | command.outputOption('-g 120') | ||
27 | command.outputOption('-x264-params "no-scenecut=1"') | ||
28 | command.outputOption('-r 60') | ||
29 | } | ||
30 | |||
31 | command.outputOption('-f flv') | ||
32 | |||
33 | const rtmpUrl = rtmpBaseUrl + '/' + streamKey | ||
34 | command.output(rtmpUrl) | ||
35 | |||
36 | command.on('error', err => { | ||
37 | if (err?.message?.includes('Exiting normally')) return | ||
38 | |||
39 | if (process.env.DEBUG) console.error(err) | ||
40 | }) | ||
41 | |||
42 | if (process.env.DEBUG) { | ||
43 | command.on('stderr', data => console.log(data)) | ||
44 | command.on('stdout', data => console.log(data)) | ||
45 | } | ||
46 | |||
47 | command.run() | ||
48 | |||
49 | return command | ||
50 | } | ||
51 | |||
52 | function waitFfmpegUntilError (command: FfmpegCommand, successAfterMS = 10000) { | ||
53 | return new Promise<void>((res, rej) => { | ||
54 | command.on('error', err => { | ||
55 | return rej(err) | ||
56 | }) | ||
57 | |||
58 | setTimeout(() => { | ||
59 | res() | ||
60 | }, successAfterMS) | ||
61 | }) | ||
62 | } | ||
63 | |||
64 | async function testFfmpegStreamError (command: FfmpegCommand, shouldHaveError: boolean) { | ||
65 | let error: Error | ||
66 | |||
67 | try { | ||
68 | await waitFfmpegUntilError(command, 45000) | ||
69 | } catch (err) { | ||
70 | error = err | ||
71 | } | ||
72 | |||
73 | await stopFfmpeg(command) | ||
74 | |||
75 | if (shouldHaveError && !error) throw new Error('Ffmpeg did not have an error') | ||
76 | if (!shouldHaveError && error) throw error | ||
77 | } | ||
78 | |||
79 | async function stopFfmpeg (command: FfmpegCommand) { | ||
80 | command.kill('SIGINT') | ||
81 | |||
82 | await wait(500) | ||
83 | } | ||
84 | |||
85 | async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], videoId: string) { | ||
86 | for (const server of servers) { | ||
87 | await server.live.waitUntilPublished({ videoId }) | ||
88 | } | ||
89 | } | ||
90 | |||
91 | async function waitUntilLiveWaitingOnAllServers (servers: PeerTubeServer[], videoId: string) { | ||
92 | for (const server of servers) { | ||
93 | await server.live.waitUntilWaiting({ videoId }) | ||
94 | } | ||
95 | } | ||
96 | |||
97 | async function waitUntilLiveReplacedByReplayOnAllServers (servers: PeerTubeServer[], videoId: string) { | ||
98 | for (const server of servers) { | ||
99 | await server.live.waitUntilReplacedByReplay({ videoId }) | ||
100 | } | ||
101 | } | ||
102 | |||
103 | async function findExternalSavedVideo (server: PeerTubeServer, liveDetails: VideoDetails) { | ||
104 | const include = VideoInclude.BLACKLISTED | ||
105 | const privacyOneOf = [ VideoPrivacy.INTERNAL, VideoPrivacy.PRIVATE, VideoPrivacy.PUBLIC, VideoPrivacy.UNLISTED ] | ||
106 | |||
107 | const { data } = await server.videos.list({ token: server.accessToken, sort: '-publishedAt', include, privacyOneOf }) | ||
108 | |||
109 | const videoNameSuffix = ` - ${new Date(liveDetails.publishedAt).toLocaleString()}` | ||
110 | const truncatedVideoName = truncate(liveDetails.name, { | ||
111 | length: 120 - videoNameSuffix.length | ||
112 | }) | ||
113 | const toFind = truncatedVideoName + videoNameSuffix | ||
114 | |||
115 | return data.find(v => v.name === toFind) | ||
116 | } | ||
117 | |||
118 | export { | ||
119 | sendRTMPStream, | ||
120 | waitFfmpegUntilError, | ||
121 | testFfmpegStreamError, | ||
122 | stopFfmpeg, | ||
123 | |||
124 | waitUntilLivePublishedOnAllServers, | ||
125 | waitUntilLiveReplacedByReplayOnAllServers, | ||
126 | waitUntilLiveWaitingOnAllServers, | ||
127 | |||
128 | findExternalSavedVideo | ||
129 | } | ||
diff --git a/packages/server-commands/src/videos/playlists-command.ts b/packages/server-commands/src/videos/playlists-command.ts new file mode 100644 index 000000000..2e483f318 --- /dev/null +++ b/packages/server-commands/src/videos/playlists-command.ts | |||
@@ -0,0 +1,281 @@ | |||
1 | import { omit, pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | BooleanBothQuery, | ||
4 | HttpStatusCode, | ||
5 | ResultList, | ||
6 | VideoExistInPlaylist, | ||
7 | VideoPlaylist, | ||
8 | VideoPlaylistCreate, | ||
9 | VideoPlaylistCreateResult, | ||
10 | VideoPlaylistElement, | ||
11 | VideoPlaylistElementCreate, | ||
12 | VideoPlaylistElementCreateResult, | ||
13 | VideoPlaylistElementUpdate, | ||
14 | VideoPlaylistReorder, | ||
15 | VideoPlaylistType_Type, | ||
16 | VideoPlaylistUpdate | ||
17 | } from '@peertube/peertube-models' | ||
18 | import { unwrapBody } from '../requests/index.js' | ||
19 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
20 | |||
21 | export class PlaylistsCommand extends AbstractCommand { | ||
22 | |||
23 | list (options: OverrideCommandOptions & { | ||
24 | start?: number | ||
25 | count?: number | ||
26 | sort?: string | ||
27 | playlistType?: VideoPlaylistType_Type | ||
28 | }) { | ||
29 | const path = '/api/v1/video-playlists' | ||
30 | const query = pick(options, [ 'start', 'count', 'sort', 'playlistType' ]) | ||
31 | |||
32 | return this.getRequestBody<ResultList<VideoPlaylist>>({ | ||
33 | ...options, | ||
34 | |||
35 | path, | ||
36 | query, | ||
37 | implicitToken: false, | ||
38 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
39 | }) | ||
40 | } | ||
41 | |||
42 | listByChannel (options: OverrideCommandOptions & { | ||
43 | handle: string | ||
44 | start?: number | ||
45 | count?: number | ||
46 | sort?: string | ||
47 | playlistType?: VideoPlaylistType_Type | ||
48 | }) { | ||
49 | const path = '/api/v1/video-channels/' + options.handle + '/video-playlists' | ||
50 | const query = pick(options, [ 'start', 'count', 'sort', 'playlistType' ]) | ||
51 | |||
52 | return this.getRequestBody<ResultList<VideoPlaylist>>({ | ||
53 | ...options, | ||
54 | |||
55 | path, | ||
56 | query, | ||
57 | implicitToken: false, | ||
58 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
59 | }) | ||
60 | } | ||
61 | |||
62 | listByAccount (options: OverrideCommandOptions & { | ||
63 | handle: string | ||
64 | start?: number | ||
65 | count?: number | ||
66 | sort?: string | ||
67 | search?: string | ||
68 | playlistType?: VideoPlaylistType_Type | ||
69 | }) { | ||
70 | const path = '/api/v1/accounts/' + options.handle + '/video-playlists' | ||
71 | const query = pick(options, [ 'start', 'count', 'sort', 'search', 'playlistType' ]) | ||
72 | |||
73 | return this.getRequestBody<ResultList<VideoPlaylist>>({ | ||
74 | ...options, | ||
75 | |||
76 | path, | ||
77 | query, | ||
78 | implicitToken: false, | ||
79 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
80 | }) | ||
81 | } | ||
82 | |||
83 | get (options: OverrideCommandOptions & { | ||
84 | playlistId: number | string | ||
85 | }) { | ||
86 | const { playlistId } = options | ||
87 | const path = '/api/v1/video-playlists/' + playlistId | ||
88 | |||
89 | return this.getRequestBody<VideoPlaylist>({ | ||
90 | ...options, | ||
91 | |||
92 | path, | ||
93 | implicitToken: false, | ||
94 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
95 | }) | ||
96 | } | ||
97 | |||
98 | listVideos (options: OverrideCommandOptions & { | ||
99 | playlistId: number | string | ||
100 | start?: number | ||
101 | count?: number | ||
102 | query?: { nsfw?: BooleanBothQuery } | ||
103 | }) { | ||
104 | const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' | ||
105 | const query = options.query ?? {} | ||
106 | |||
107 | return this.getRequestBody<ResultList<VideoPlaylistElement>>({ | ||
108 | ...options, | ||
109 | |||
110 | path, | ||
111 | query: { | ||
112 | ...query, | ||
113 | start: options.start, | ||
114 | count: options.count | ||
115 | }, | ||
116 | implicitToken: true, | ||
117 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
118 | }) | ||
119 | } | ||
120 | |||
121 | delete (options: OverrideCommandOptions & { | ||
122 | playlistId: number | string | ||
123 | }) { | ||
124 | const path = '/api/v1/video-playlists/' + options.playlistId | ||
125 | |||
126 | return this.deleteRequest({ | ||
127 | ...options, | ||
128 | |||
129 | path, | ||
130 | implicitToken: true, | ||
131 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
132 | }) | ||
133 | } | ||
134 | |||
135 | async create (options: OverrideCommandOptions & { | ||
136 | attributes: VideoPlaylistCreate | ||
137 | }) { | ||
138 | const path = '/api/v1/video-playlists' | ||
139 | |||
140 | const fields = omit(options.attributes, [ 'thumbnailfile' ]) | ||
141 | |||
142 | const attaches = options.attributes.thumbnailfile | ||
143 | ? { thumbnailfile: options.attributes.thumbnailfile } | ||
144 | : {} | ||
145 | |||
146 | const body = await unwrapBody<{ videoPlaylist: VideoPlaylistCreateResult }>(this.postUploadRequest({ | ||
147 | ...options, | ||
148 | |||
149 | path, | ||
150 | fields, | ||
151 | attaches, | ||
152 | implicitToken: true, | ||
153 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
154 | })) | ||
155 | |||
156 | return body.videoPlaylist | ||
157 | } | ||
158 | |||
159 | update (options: OverrideCommandOptions & { | ||
160 | attributes: VideoPlaylistUpdate | ||
161 | playlistId: number | string | ||
162 | }) { | ||
163 | const path = '/api/v1/video-playlists/' + options.playlistId | ||
164 | |||
165 | const fields = omit(options.attributes, [ 'thumbnailfile' ]) | ||
166 | |||
167 | const attaches = options.attributes.thumbnailfile | ||
168 | ? { thumbnailfile: options.attributes.thumbnailfile } | ||
169 | : {} | ||
170 | |||
171 | return this.putUploadRequest({ | ||
172 | ...options, | ||
173 | |||
174 | path, | ||
175 | fields, | ||
176 | attaches, | ||
177 | implicitToken: true, | ||
178 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
179 | }) | ||
180 | } | ||
181 | |||
182 | async addElement (options: OverrideCommandOptions & { | ||
183 | playlistId: number | string | ||
184 | attributes: VideoPlaylistElementCreate | { videoId: string } | ||
185 | }) { | ||
186 | const attributes = { | ||
187 | ...options.attributes, | ||
188 | |||
189 | videoId: await this.server.videos.getId({ ...options, uuid: options.attributes.videoId }) | ||
190 | } | ||
191 | |||
192 | const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' | ||
193 | |||
194 | const body = await unwrapBody<{ videoPlaylistElement: VideoPlaylistElementCreateResult }>(this.postBodyRequest({ | ||
195 | ...options, | ||
196 | |||
197 | path, | ||
198 | fields: attributes, | ||
199 | implicitToken: true, | ||
200 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
201 | })) | ||
202 | |||
203 | return body.videoPlaylistElement | ||
204 | } | ||
205 | |||
206 | updateElement (options: OverrideCommandOptions & { | ||
207 | playlistId: number | string | ||
208 | elementId: number | string | ||
209 | attributes: VideoPlaylistElementUpdate | ||
210 | }) { | ||
211 | const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId | ||
212 | |||
213 | return this.putBodyRequest({ | ||
214 | ...options, | ||
215 | |||
216 | path, | ||
217 | fields: options.attributes, | ||
218 | implicitToken: true, | ||
219 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
220 | }) | ||
221 | } | ||
222 | |||
223 | removeElement (options: OverrideCommandOptions & { | ||
224 | playlistId: number | string | ||
225 | elementId: number | ||
226 | }) { | ||
227 | const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId | ||
228 | |||
229 | return this.deleteRequest({ | ||
230 | ...options, | ||
231 | |||
232 | path, | ||
233 | implicitToken: true, | ||
234 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
235 | }) | ||
236 | } | ||
237 | |||
238 | reorderElements (options: OverrideCommandOptions & { | ||
239 | playlistId: number | string | ||
240 | attributes: VideoPlaylistReorder | ||
241 | }) { | ||
242 | const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/reorder' | ||
243 | |||
244 | return this.postBodyRequest({ | ||
245 | ...options, | ||
246 | |||
247 | path, | ||
248 | fields: options.attributes, | ||
249 | implicitToken: true, | ||
250 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
251 | }) | ||
252 | } | ||
253 | |||
254 | getPrivacies (options: OverrideCommandOptions = {}) { | ||
255 | const path = '/api/v1/video-playlists/privacies' | ||
256 | |||
257 | return this.getRequestBody<{ [ id: number ]: string }>({ | ||
258 | ...options, | ||
259 | |||
260 | path, | ||
261 | implicitToken: false, | ||
262 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
263 | }) | ||
264 | } | ||
265 | |||
266 | videosExist (options: OverrideCommandOptions & { | ||
267 | videoIds: number[] | ||
268 | }) { | ||
269 | const { videoIds } = options | ||
270 | const path = '/api/v1/users/me/video-playlists/videos-exist' | ||
271 | |||
272 | return this.getRequestBody<VideoExistInPlaylist>({ | ||
273 | ...options, | ||
274 | |||
275 | path, | ||
276 | query: { videoIds }, | ||
277 | implicitToken: true, | ||
278 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
279 | }) | ||
280 | } | ||
281 | } | ||
diff --git a/packages/server-commands/src/videos/services-command.ts b/packages/server-commands/src/videos/services-command.ts new file mode 100644 index 000000000..ade10cd3a --- /dev/null +++ b/packages/server-commands/src/videos/services-command.ts | |||
@@ -0,0 +1,29 @@ | |||
1 | import { HttpStatusCode } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class ServicesCommand extends AbstractCommand { | ||
5 | |||
6 | getOEmbed (options: OverrideCommandOptions & { | ||
7 | oembedUrl: string | ||
8 | format?: string | ||
9 | maxHeight?: number | ||
10 | maxWidth?: number | ||
11 | }) { | ||
12 | const path = '/services/oembed' | ||
13 | const query = { | ||
14 | url: options.oembedUrl, | ||
15 | format: options.format, | ||
16 | maxheight: options.maxHeight, | ||
17 | maxwidth: options.maxWidth | ||
18 | } | ||
19 | |||
20 | return this.getRequest({ | ||
21 | ...options, | ||
22 | |||
23 | path, | ||
24 | query, | ||
25 | implicitToken: false, | ||
26 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
27 | }) | ||
28 | } | ||
29 | } | ||
diff --git a/packages/server-commands/src/videos/storyboard-command.ts b/packages/server-commands/src/videos/storyboard-command.ts new file mode 100644 index 000000000..a692ad612 --- /dev/null +++ b/packages/server-commands/src/videos/storyboard-command.ts | |||
@@ -0,0 +1,19 @@ | |||
1 | import { HttpStatusCode, Storyboard } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class StoryboardCommand extends AbstractCommand { | ||
5 | |||
6 | list (options: OverrideCommandOptions & { | ||
7 | id: number | string | ||
8 | }) { | ||
9 | const path = '/api/v1/videos/' + options.id + '/storyboards' | ||
10 | |||
11 | return this.getRequestBody<{ storyboards: Storyboard[] }>({ | ||
12 | ...options, | ||
13 | |||
14 | path, | ||
15 | implicitToken: true, | ||
16 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
17 | }) | ||
18 | } | ||
19 | } | ||
diff --git a/packages/server-commands/src/videos/streaming-playlists-command.ts b/packages/server-commands/src/videos/streaming-playlists-command.ts new file mode 100644 index 000000000..2406dd023 --- /dev/null +++ b/packages/server-commands/src/videos/streaming-playlists-command.ts | |||
@@ -0,0 +1,119 @@ | |||
1 | import { wait } from '@peertube/peertube-core-utils' | ||
2 | import { HttpStatusCode } from '@peertube/peertube-models' | ||
3 | import { unwrapBody, unwrapBodyOrDecodeToJSON, unwrapTextOrDecode } from '../requests/index.js' | ||
4 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
5 | |||
6 | export class StreamingPlaylistsCommand extends AbstractCommand { | ||
7 | |||
8 | async get (options: OverrideCommandOptions & { | ||
9 | url: string | ||
10 | |||
11 | videoFileToken?: string | ||
12 | reinjectVideoFileToken?: boolean | ||
13 | |||
14 | withRetry?: boolean // default false | ||
15 | currentRetry?: number | ||
16 | }): Promise<string> { | ||
17 | const { videoFileToken, reinjectVideoFileToken, expectedStatus, withRetry = false, currentRetry = 1 } = options | ||
18 | |||
19 | try { | ||
20 | const result = await unwrapTextOrDecode(this.getRawRequest({ | ||
21 | ...options, | ||
22 | |||
23 | url: options.url, | ||
24 | query: { | ||
25 | videoFileToken, | ||
26 | reinjectVideoFileToken | ||
27 | }, | ||
28 | implicitToken: false, | ||
29 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
30 | })) | ||
31 | |||
32 | // master.m3u8 could be empty | ||
33 | if (!result && (!expectedStatus || expectedStatus === HttpStatusCode.OK_200)) { | ||
34 | throw new Error('Empty result') | ||
35 | } | ||
36 | |||
37 | return result | ||
38 | } catch (err) { | ||
39 | if (!withRetry || currentRetry > 10) throw err | ||
40 | |||
41 | await wait(250) | ||
42 | |||
43 | return this.get({ | ||
44 | ...options, | ||
45 | |||
46 | withRetry, | ||
47 | currentRetry: currentRetry + 1 | ||
48 | }) | ||
49 | } | ||
50 | } | ||
51 | |||
52 | async getFragmentedSegment (options: OverrideCommandOptions & { | ||
53 | url: string | ||
54 | range?: string | ||
55 | |||
56 | withRetry?: boolean // default false | ||
57 | currentRetry?: number | ||
58 | }) { | ||
59 | const { withRetry = false, currentRetry = 1 } = options | ||
60 | |||
61 | try { | ||
62 | const result = await unwrapBody<Buffer>(this.getRawRequest({ | ||
63 | ...options, | ||
64 | |||
65 | url: options.url, | ||
66 | range: options.range, | ||
67 | implicitToken: false, | ||
68 | responseType: 'application/octet-stream', | ||
69 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
70 | })) | ||
71 | |||
72 | return result | ||
73 | } catch (err) { | ||
74 | if (!withRetry || currentRetry > 10) throw err | ||
75 | |||
76 | await wait(250) | ||
77 | |||
78 | return this.getFragmentedSegment({ | ||
79 | ...options, | ||
80 | |||
81 | withRetry, | ||
82 | currentRetry: currentRetry + 1 | ||
83 | }) | ||
84 | } | ||
85 | } | ||
86 | |||
87 | async getSegmentSha256 (options: OverrideCommandOptions & { | ||
88 | url: string | ||
89 | |||
90 | withRetry?: boolean // default false | ||
91 | currentRetry?: number | ||
92 | }) { | ||
93 | const { withRetry = false, currentRetry = 1 } = options | ||
94 | |||
95 | try { | ||
96 | const result = await unwrapBodyOrDecodeToJSON<{ [ id: string ]: string }>(this.getRawRequest({ | ||
97 | ...options, | ||
98 | |||
99 | url: options.url, | ||
100 | contentType: 'application/json', | ||
101 | implicitToken: false, | ||
102 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
103 | })) | ||
104 | |||
105 | return result | ||
106 | } catch (err) { | ||
107 | if (!withRetry || currentRetry > 10) throw err | ||
108 | |||
109 | await wait(250) | ||
110 | |||
111 | return this.getSegmentSha256({ | ||
112 | ...options, | ||
113 | |||
114 | withRetry, | ||
115 | currentRetry: currentRetry + 1 | ||
116 | }) | ||
117 | } | ||
118 | } | ||
119 | } | ||
diff --git a/packages/server-commands/src/videos/video-passwords-command.ts b/packages/server-commands/src/videos/video-passwords-command.ts new file mode 100644 index 000000000..7a56311ca --- /dev/null +++ b/packages/server-commands/src/videos/video-passwords-command.ts | |||
@@ -0,0 +1,56 @@ | |||
1 | import { HttpStatusCode, ResultList, VideoPassword } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class VideoPasswordsCommand extends AbstractCommand { | ||
5 | |||
6 | list (options: OverrideCommandOptions & { | ||
7 | videoId: number | string | ||
8 | start?: number | ||
9 | count?: number | ||
10 | sort?: string | ||
11 | }) { | ||
12 | const { start, count, sort, videoId } = options | ||
13 | const path = '/api/v1/videos/' + videoId + '/passwords' | ||
14 | |||
15 | return this.getRequestBody<ResultList<VideoPassword>>({ | ||
16 | ...options, | ||
17 | |||
18 | path, | ||
19 | query: { start, count, sort }, | ||
20 | implicitToken: true, | ||
21 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
22 | }) | ||
23 | } | ||
24 | |||
25 | updateAll (options: OverrideCommandOptions & { | ||
26 | videoId: number | string | ||
27 | passwords: string[] | ||
28 | }) { | ||
29 | const { videoId, passwords } = options | ||
30 | const path = `/api/v1/videos/${videoId}/passwords` | ||
31 | |||
32 | return this.putBodyRequest({ | ||
33 | ...options, | ||
34 | path, | ||
35 | fields: { passwords }, | ||
36 | implicitToken: true, | ||
37 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
38 | }) | ||
39 | } | ||
40 | |||
41 | remove (options: OverrideCommandOptions & { | ||
42 | id: number | ||
43 | videoId: number | string | ||
44 | }) { | ||
45 | const { id, videoId } = options | ||
46 | const path = `/api/v1/videos/${videoId}/passwords/${id}` | ||
47 | |||
48 | return this.deleteRequest({ | ||
49 | ...options, | ||
50 | |||
51 | path, | ||
52 | implicitToken: true, | ||
53 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
54 | }) | ||
55 | } | ||
56 | } | ||
diff --git a/packages/server-commands/src/videos/video-stats-command.ts b/packages/server-commands/src/videos/video-stats-command.ts new file mode 100644 index 000000000..1b7a9b592 --- /dev/null +++ b/packages/server-commands/src/videos/video-stats-command.ts | |||
@@ -0,0 +1,62 @@ | |||
1 | import { pick } from '@peertube/peertube-core-utils' | ||
2 | import { | ||
3 | HttpStatusCode, | ||
4 | VideoStatsOverall, | ||
5 | VideoStatsRetention, | ||
6 | VideoStatsTimeserie, | ||
7 | VideoStatsTimeserieMetric | ||
8 | } from '@peertube/peertube-models' | ||
9 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
10 | |||
11 | export class VideoStatsCommand extends AbstractCommand { | ||
12 | |||
13 | getOverallStats (options: OverrideCommandOptions & { | ||
14 | videoId: number | string | ||
15 | startDate?: string | ||
16 | endDate?: string | ||
17 | }) { | ||
18 | const path = '/api/v1/videos/' + options.videoId + '/stats/overall' | ||
19 | |||
20 | return this.getRequestBody<VideoStatsOverall>({ | ||
21 | ...options, | ||
22 | path, | ||
23 | |||
24 | query: pick(options, [ 'startDate', 'endDate' ]), | ||
25 | |||
26 | implicitToken: true, | ||
27 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
28 | }) | ||
29 | } | ||
30 | |||
31 | getTimeserieStats (options: OverrideCommandOptions & { | ||
32 | videoId: number | string | ||
33 | metric: VideoStatsTimeserieMetric | ||
34 | startDate?: Date | ||
35 | endDate?: Date | ||
36 | }) { | ||
37 | const path = '/api/v1/videos/' + options.videoId + '/stats/timeseries/' + options.metric | ||
38 | |||
39 | return this.getRequestBody<VideoStatsTimeserie>({ | ||
40 | ...options, | ||
41 | path, | ||
42 | |||
43 | query: pick(options, [ 'startDate', 'endDate' ]), | ||
44 | implicitToken: true, | ||
45 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
46 | }) | ||
47 | } | ||
48 | |||
49 | getRetentionStats (options: OverrideCommandOptions & { | ||
50 | videoId: number | string | ||
51 | }) { | ||
52 | const path = '/api/v1/videos/' + options.videoId + '/stats/retention' | ||
53 | |||
54 | return this.getRequestBody<VideoStatsRetention>({ | ||
55 | ...options, | ||
56 | path, | ||
57 | |||
58 | implicitToken: true, | ||
59 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
60 | }) | ||
61 | } | ||
62 | } | ||
diff --git a/packages/server-commands/src/videos/video-studio-command.ts b/packages/server-commands/src/videos/video-studio-command.ts new file mode 100644 index 000000000..8c5ff169a --- /dev/null +++ b/packages/server-commands/src/videos/video-studio-command.ts | |||
@@ -0,0 +1,67 @@ | |||
1 | import { HttpStatusCode, VideoStudioTask } from '@peertube/peertube-models' | ||
2 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
3 | |||
4 | export class VideoStudioCommand extends AbstractCommand { | ||
5 | |||
6 | static getComplexTask (): VideoStudioTask[] { | ||
7 | return [ | ||
8 | // Total duration: 2 | ||
9 | { | ||
10 | name: 'cut', | ||
11 | options: { | ||
12 | start: 1, | ||
13 | end: 3 | ||
14 | } | ||
15 | }, | ||
16 | |||
17 | // Total duration: 7 | ||
18 | { | ||
19 | name: 'add-outro', | ||
20 | options: { | ||
21 | file: 'video_short.webm' | ||
22 | } | ||
23 | }, | ||
24 | |||
25 | { | ||
26 | name: 'add-watermark', | ||
27 | options: { | ||
28 | file: 'custom-thumbnail.png' | ||
29 | } | ||
30 | }, | ||
31 | |||
32 | // Total duration: 9 | ||
33 | { | ||
34 | name: 'add-intro', | ||
35 | options: { | ||
36 | file: 'video_very_short_240p.mp4' | ||
37 | } | ||
38 | } | ||
39 | ] | ||
40 | } | ||
41 | |||
42 | createEditionTasks (options: OverrideCommandOptions & { | ||
43 | videoId: number | string | ||
44 | tasks: VideoStudioTask[] | ||
45 | }) { | ||
46 | const path = '/api/v1/videos/' + options.videoId + '/studio/edit' | ||
47 | const attaches: { [id: string]: any } = {} | ||
48 | |||
49 | for (let i = 0; i < options.tasks.length; i++) { | ||
50 | const task = options.tasks[i] | ||
51 | |||
52 | if (task.name === 'add-intro' || task.name === 'add-outro' || task.name === 'add-watermark') { | ||
53 | attaches[`tasks[${i}][options][file]`] = task.options.file | ||
54 | } | ||
55 | } | ||
56 | |||
57 | return this.postUploadRequest({ | ||
58 | ...options, | ||
59 | |||
60 | path, | ||
61 | attaches, | ||
62 | fields: { tasks: options.tasks }, | ||
63 | implicitToken: true, | ||
64 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
65 | }) | ||
66 | } | ||
67 | } | ||
diff --git a/packages/server-commands/src/videos/video-token-command.ts b/packages/server-commands/src/videos/video-token-command.ts new file mode 100644 index 000000000..5812e484a --- /dev/null +++ b/packages/server-commands/src/videos/video-token-command.ts | |||
@@ -0,0 +1,34 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ | ||
2 | |||
3 | import { HttpStatusCode, VideoToken } from '@peertube/peertube-models' | ||
4 | import { unwrapBody } from '../requests/index.js' | ||
5 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
6 | |||
7 | export class VideoTokenCommand extends AbstractCommand { | ||
8 | |||
9 | create (options: OverrideCommandOptions & { | ||
10 | videoId: number | string | ||
11 | videoPassword?: string | ||
12 | }) { | ||
13 | const { videoId, videoPassword } = options | ||
14 | const path = '/api/v1/videos/' + videoId + '/token' | ||
15 | |||
16 | return unwrapBody<VideoToken>(this.postBodyRequest({ | ||
17 | ...options, | ||
18 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
19 | |||
20 | path, | ||
21 | implicitToken: true, | ||
22 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
23 | })) | ||
24 | } | ||
25 | |||
26 | async getVideoFileToken (options: OverrideCommandOptions & { | ||
27 | videoId: number | string | ||
28 | videoPassword?: string | ||
29 | }) { | ||
30 | const { files } = await this.create(options) | ||
31 | |||
32 | return files.token | ||
33 | } | ||
34 | } | ||
diff --git a/packages/server-commands/src/videos/videos-command.ts b/packages/server-commands/src/videos/videos-command.ts new file mode 100644 index 000000000..72dc58a4b --- /dev/null +++ b/packages/server-commands/src/videos/videos-command.ts | |||
@@ -0,0 +1,831 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ | ||
2 | |||
3 | import { expect } from 'chai' | ||
4 | import { createReadStream } from 'fs' | ||
5 | import { stat } from 'fs/promises' | ||
6 | import got, { Response as GotResponse } from 'got' | ||
7 | import validator from 'validator' | ||
8 | import { getAllPrivacies, omit, pick, wait } from '@peertube/peertube-core-utils' | ||
9 | import { | ||
10 | HttpStatusCode, | ||
11 | HttpStatusCodeType, | ||
12 | ResultList, | ||
13 | UserVideoRateType, | ||
14 | Video, | ||
15 | VideoCreate, | ||
16 | VideoCreateResult, | ||
17 | VideoDetails, | ||
18 | VideoFileMetadata, | ||
19 | VideoInclude, | ||
20 | VideoPrivacy, | ||
21 | VideoPrivacyType, | ||
22 | VideosCommonQuery, | ||
23 | VideoSource, | ||
24 | VideoTranscodingCreate | ||
25 | } from '@peertube/peertube-models' | ||
26 | import { buildAbsoluteFixturePath, buildUUID } from '@peertube/peertube-node-utils' | ||
27 | import { unwrapBody } from '../requests/index.js' | ||
28 | import { waitJobs } from '../server/jobs.js' | ||
29 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
30 | |||
31 | export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & { | ||
32 | fixture?: string | ||
33 | thumbnailfile?: string | ||
34 | previewfile?: string | ||
35 | } | ||
36 | |||
37 | export class VideosCommand extends AbstractCommand { | ||
38 | |||
39 | getCategories (options: OverrideCommandOptions = {}) { | ||
40 | const path = '/api/v1/videos/categories' | ||
41 | |||
42 | return this.getRequestBody<{ [id: number]: string }>({ | ||
43 | ...options, | ||
44 | path, | ||
45 | |||
46 | implicitToken: false, | ||
47 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
48 | }) | ||
49 | } | ||
50 | |||
51 | getLicences (options: OverrideCommandOptions = {}) { | ||
52 | const path = '/api/v1/videos/licences' | ||
53 | |||
54 | return this.getRequestBody<{ [id: number]: string }>({ | ||
55 | ...options, | ||
56 | path, | ||
57 | |||
58 | implicitToken: false, | ||
59 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
60 | }) | ||
61 | } | ||
62 | |||
63 | getLanguages (options: OverrideCommandOptions = {}) { | ||
64 | const path = '/api/v1/videos/languages' | ||
65 | |||
66 | return this.getRequestBody<{ [id: string]: string }>({ | ||
67 | ...options, | ||
68 | path, | ||
69 | |||
70 | implicitToken: false, | ||
71 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
72 | }) | ||
73 | } | ||
74 | |||
75 | getPrivacies (options: OverrideCommandOptions = {}) { | ||
76 | const path = '/api/v1/videos/privacies' | ||
77 | |||
78 | return this.getRequestBody<{ [id in VideoPrivacyType]: string }>({ | ||
79 | ...options, | ||
80 | path, | ||
81 | |||
82 | implicitToken: false, | ||
83 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
84 | }) | ||
85 | } | ||
86 | |||
87 | // --------------------------------------------------------------------------- | ||
88 | |||
89 | getDescription (options: OverrideCommandOptions & { | ||
90 | descriptionPath: string | ||
91 | }) { | ||
92 | return this.getRequestBody<{ description: string }>({ | ||
93 | ...options, | ||
94 | path: options.descriptionPath, | ||
95 | |||
96 | implicitToken: false, | ||
97 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
98 | }) | ||
99 | } | ||
100 | |||
101 | getFileMetadata (options: OverrideCommandOptions & { | ||
102 | url: string | ||
103 | }) { | ||
104 | return unwrapBody<VideoFileMetadata>(this.getRawRequest({ | ||
105 | ...options, | ||
106 | |||
107 | url: options.url, | ||
108 | implicitToken: false, | ||
109 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
110 | })) | ||
111 | } | ||
112 | |||
113 | // --------------------------------------------------------------------------- | ||
114 | |||
115 | rate (options: OverrideCommandOptions & { | ||
116 | id: number | string | ||
117 | rating: UserVideoRateType | ||
118 | videoPassword?: string | ||
119 | }) { | ||
120 | const { id, rating, videoPassword } = options | ||
121 | const path = '/api/v1/videos/' + id + '/rate' | ||
122 | |||
123 | return this.putBodyRequest({ | ||
124 | ...options, | ||
125 | |||
126 | path, | ||
127 | fields: { rating }, | ||
128 | headers: this.buildVideoPasswordHeader(videoPassword), | ||
129 | implicitToken: true, | ||
130 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
131 | }) | ||
132 | } | ||
133 | |||
134 | // --------------------------------------------------------------------------- | ||
135 | |||
136 | get (options: OverrideCommandOptions & { | ||
137 | id: number | string | ||
138 | }) { | ||
139 | const path = '/api/v1/videos/' + options.id | ||
140 | |||
141 | return this.getRequestBody<VideoDetails>({ | ||
142 | ...options, | ||
143 | |||
144 | path, | ||
145 | implicitToken: false, | ||
146 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
147 | }) | ||
148 | } | ||
149 | |||
150 | getWithToken (options: OverrideCommandOptions & { | ||
151 | id: number | string | ||
152 | }) { | ||
153 | return this.get({ | ||
154 | ...options, | ||
155 | |||
156 | token: this.buildCommonRequestToken({ ...options, implicitToken: true }) | ||
157 | }) | ||
158 | } | ||
159 | |||
160 | getWithPassword (options: OverrideCommandOptions & { | ||
161 | id: number | string | ||
162 | password?: string | ||
163 | }) { | ||
164 | const path = '/api/v1/videos/' + options.id | ||
165 | |||
166 | return this.getRequestBody<VideoDetails>({ | ||
167 | ...options, | ||
168 | headers:{ | ||
169 | 'x-peertube-video-password': options.password | ||
170 | }, | ||
171 | path, | ||
172 | implicitToken: false, | ||
173 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
174 | }) | ||
175 | } | ||
176 | |||
177 | getSource (options: OverrideCommandOptions & { | ||
178 | id: number | string | ||
179 | }) { | ||
180 | const path = '/api/v1/videos/' + options.id + '/source' | ||
181 | |||
182 | return this.getRequestBody<VideoSource>({ | ||
183 | ...options, | ||
184 | |||
185 | path, | ||
186 | implicitToken: true, | ||
187 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
188 | }) | ||
189 | } | ||
190 | |||
191 | async getId (options: OverrideCommandOptions & { | ||
192 | uuid: number | string | ||
193 | }) { | ||
194 | const { uuid } = options | ||
195 | |||
196 | if (validator.default.isUUID('' + uuid) === false) return uuid as number | ||
197 | |||
198 | const { id } = await this.get({ ...options, id: uuid }) | ||
199 | |||
200 | return id | ||
201 | } | ||
202 | |||
203 | async listFiles (options: OverrideCommandOptions & { | ||
204 | id: number | string | ||
205 | }) { | ||
206 | const video = await this.get(options) | ||
207 | |||
208 | const files = video.files || [] | ||
209 | const hlsFiles = video.streamingPlaylists[0]?.files || [] | ||
210 | |||
211 | return files.concat(hlsFiles) | ||
212 | } | ||
213 | |||
214 | // --------------------------------------------------------------------------- | ||
215 | |||
216 | listMyVideos (options: OverrideCommandOptions & { | ||
217 | start?: number | ||
218 | count?: number | ||
219 | sort?: string | ||
220 | search?: string | ||
221 | isLive?: boolean | ||
222 | channelId?: number | ||
223 | } = {}) { | ||
224 | const path = '/api/v1/users/me/videos' | ||
225 | |||
226 | return this.getRequestBody<ResultList<Video>>({ | ||
227 | ...options, | ||
228 | |||
229 | path, | ||
230 | query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]), | ||
231 | implicitToken: true, | ||
232 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
233 | }) | ||
234 | } | ||
235 | |||
236 | listMySubscriptionVideos (options: OverrideCommandOptions & VideosCommonQuery = {}) { | ||
237 | const { sort = '-createdAt' } = options | ||
238 | const path = '/api/v1/users/me/subscriptions/videos' | ||
239 | |||
240 | return this.getRequestBody<ResultList<Video>>({ | ||
241 | ...options, | ||
242 | |||
243 | path, | ||
244 | query: { sort, ...this.buildListQuery(options) }, | ||
245 | implicitToken: true, | ||
246 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
247 | }) | ||
248 | } | ||
249 | |||
250 | // --------------------------------------------------------------------------- | ||
251 | |||
252 | list (options: OverrideCommandOptions & VideosCommonQuery = {}) { | ||
253 | const path = '/api/v1/videos' | ||
254 | |||
255 | const query = this.buildListQuery(options) | ||
256 | |||
257 | return this.getRequestBody<ResultList<Video>>({ | ||
258 | ...options, | ||
259 | |||
260 | path, | ||
261 | query: { sort: 'name', ...query }, | ||
262 | implicitToken: false, | ||
263 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
264 | }) | ||
265 | } | ||
266 | |||
267 | listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) { | ||
268 | return this.list({ | ||
269 | ...options, | ||
270 | |||
271 | token: this.buildCommonRequestToken({ ...options, implicitToken: true }) | ||
272 | }) | ||
273 | } | ||
274 | |||
275 | listAllForAdmin (options: OverrideCommandOptions & VideosCommonQuery = {}) { | ||
276 | const include = VideoInclude.NOT_PUBLISHED_STATE | VideoInclude.BLACKLISTED | VideoInclude.BLOCKED_OWNER | ||
277 | const nsfw = 'both' | ||
278 | const privacyOneOf = getAllPrivacies() | ||
279 | |||
280 | return this.list({ | ||
281 | ...options, | ||
282 | |||
283 | include, | ||
284 | nsfw, | ||
285 | privacyOneOf, | ||
286 | |||
287 | token: this.buildCommonRequestToken({ ...options, implicitToken: true }) | ||
288 | }) | ||
289 | } | ||
290 | |||
291 | listByAccount (options: OverrideCommandOptions & VideosCommonQuery & { | ||
292 | handle: string | ||
293 | }) { | ||
294 | const { handle, search } = options | ||
295 | const path = '/api/v1/accounts/' + handle + '/videos' | ||
296 | |||
297 | return this.getRequestBody<ResultList<Video>>({ | ||
298 | ...options, | ||
299 | |||
300 | path, | ||
301 | query: { search, ...this.buildListQuery(options) }, | ||
302 | implicitToken: true, | ||
303 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
304 | }) | ||
305 | } | ||
306 | |||
307 | listByChannel (options: OverrideCommandOptions & VideosCommonQuery & { | ||
308 | handle: string | ||
309 | }) { | ||
310 | const { handle } = options | ||
311 | const path = '/api/v1/video-channels/' + handle + '/videos' | ||
312 | |||
313 | return this.getRequestBody<ResultList<Video>>({ | ||
314 | ...options, | ||
315 | |||
316 | path, | ||
317 | query: this.buildListQuery(options), | ||
318 | implicitToken: true, | ||
319 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
320 | }) | ||
321 | } | ||
322 | |||
323 | // --------------------------------------------------------------------------- | ||
324 | |||
325 | async find (options: OverrideCommandOptions & { | ||
326 | name: string | ||
327 | }) { | ||
328 | const { data } = await this.list(options) | ||
329 | |||
330 | return data.find(v => v.name === options.name) | ||
331 | } | ||
332 | |||
333 | // --------------------------------------------------------------------------- | ||
334 | |||
335 | update (options: OverrideCommandOptions & { | ||
336 | id: number | string | ||
337 | attributes?: VideoEdit | ||
338 | }) { | ||
339 | const { id, attributes = {} } = options | ||
340 | const path = '/api/v1/videos/' + id | ||
341 | |||
342 | // Upload request | ||
343 | if (attributes.thumbnailfile || attributes.previewfile) { | ||
344 | const attaches: any = {} | ||
345 | if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile | ||
346 | if (attributes.previewfile) attaches.previewfile = attributes.previewfile | ||
347 | |||
348 | return this.putUploadRequest({ | ||
349 | ...options, | ||
350 | |||
351 | path, | ||
352 | fields: options.attributes, | ||
353 | attaches: { | ||
354 | thumbnailfile: attributes.thumbnailfile, | ||
355 | previewfile: attributes.previewfile | ||
356 | }, | ||
357 | implicitToken: true, | ||
358 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
359 | }) | ||
360 | } | ||
361 | |||
362 | return this.putBodyRequest({ | ||
363 | ...options, | ||
364 | |||
365 | path, | ||
366 | fields: options.attributes, | ||
367 | implicitToken: true, | ||
368 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
369 | }) | ||
370 | } | ||
371 | |||
372 | remove (options: OverrideCommandOptions & { | ||
373 | id: number | string | ||
374 | }) { | ||
375 | const path = '/api/v1/videos/' + options.id | ||
376 | |||
377 | return unwrapBody(this.deleteRequest({ | ||
378 | ...options, | ||
379 | |||
380 | path, | ||
381 | implicitToken: true, | ||
382 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
383 | })) | ||
384 | } | ||
385 | |||
386 | async removeAll () { | ||
387 | const { data } = await this.list() | ||
388 | |||
389 | for (const v of data) { | ||
390 | await this.remove({ id: v.id }) | ||
391 | } | ||
392 | } | ||
393 | |||
394 | // --------------------------------------------------------------------------- | ||
395 | |||
396 | async upload (options: OverrideCommandOptions & { | ||
397 | attributes?: VideoEdit | ||
398 | mode?: 'legacy' | 'resumable' // default legacy | ||
399 | waitTorrentGeneration?: boolean // default true | ||
400 | completedExpectedStatus?: HttpStatusCodeType | ||
401 | } = {}) { | ||
402 | const { mode = 'legacy', waitTorrentGeneration = true } = options | ||
403 | let defaultChannelId = 1 | ||
404 | |||
405 | try { | ||
406 | const { videoChannels } = await this.server.users.getMyInfo({ token: options.token }) | ||
407 | defaultChannelId = videoChannels[0].id | ||
408 | } catch (e) { /* empty */ } | ||
409 | |||
410 | // Override default attributes | ||
411 | const attributes = { | ||
412 | name: 'my super video', | ||
413 | category: 5, | ||
414 | licence: 4, | ||
415 | language: 'zh', | ||
416 | channelId: defaultChannelId, | ||
417 | nsfw: true, | ||
418 | waitTranscoding: false, | ||
419 | description: 'my super description', | ||
420 | support: 'my super support text', | ||
421 | tags: [ 'tag' ], | ||
422 | privacy: VideoPrivacy.PUBLIC, | ||
423 | commentsEnabled: true, | ||
424 | downloadEnabled: true, | ||
425 | fixture: 'video_short.webm', | ||
426 | |||
427 | ...options.attributes | ||
428 | } | ||
429 | |||
430 | const created = mode === 'legacy' | ||
431 | ? await this.buildLegacyUpload({ ...options, attributes }) | ||
432 | : await this.buildResumeUpload({ ...options, path: '/api/v1/videos/upload-resumable', attributes }) | ||
433 | |||
434 | // Wait torrent generation | ||
435 | const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 }) | ||
436 | if (expectedStatus === HttpStatusCode.OK_200 && waitTorrentGeneration) { | ||
437 | let video: VideoDetails | ||
438 | |||
439 | do { | ||
440 | video = await this.getWithToken({ ...options, id: created.uuid }) | ||
441 | |||
442 | await wait(50) | ||
443 | } while (!video.files[0].torrentUrl) | ||
444 | } | ||
445 | |||
446 | return created | ||
447 | } | ||
448 | |||
449 | async buildLegacyUpload (options: OverrideCommandOptions & { | ||
450 | attributes: VideoEdit | ||
451 | }): Promise<VideoCreateResult> { | ||
452 | const path = '/api/v1/videos/upload' | ||
453 | |||
454 | return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({ | ||
455 | ...options, | ||
456 | |||
457 | path, | ||
458 | fields: this.buildUploadFields(options.attributes), | ||
459 | attaches: this.buildUploadAttaches(options.attributes), | ||
460 | implicitToken: true, | ||
461 | defaultExpectedStatus: HttpStatusCode.OK_200 | ||
462 | })).then(body => body.video || body as any) | ||
463 | } | ||
464 | |||
465 | async buildResumeUpload (options: OverrideCommandOptions & { | ||
466 | path: string | ||
467 | attributes: { fixture?: string } & { [id: string]: any } | ||
468 | completedExpectedStatus?: HttpStatusCodeType // When the upload is finished | ||
469 | }): Promise<VideoCreateResult> { | ||
470 | const { path, attributes, expectedStatus = HttpStatusCode.OK_200, completedExpectedStatus } = options | ||
471 | |||
472 | let size = 0 | ||
473 | let videoFilePath: string | ||
474 | let mimetype = 'video/mp4' | ||
475 | |||
476 | if (attributes.fixture) { | ||
477 | videoFilePath = buildAbsoluteFixturePath(attributes.fixture) | ||
478 | size = (await stat(videoFilePath)).size | ||
479 | |||
480 | if (videoFilePath.endsWith('.mkv')) { | ||
481 | mimetype = 'video/x-matroska' | ||
482 | } else if (videoFilePath.endsWith('.webm')) { | ||
483 | mimetype = 'video/webm' | ||
484 | } | ||
485 | } | ||
486 | |||
487 | // Do not check status automatically, we'll check it manually | ||
488 | const initializeSessionRes = await this.prepareResumableUpload({ | ||
489 | ...options, | ||
490 | |||
491 | path, | ||
492 | expectedStatus: null, | ||
493 | attributes, | ||
494 | size, | ||
495 | mimetype | ||
496 | }) | ||
497 | const initStatus = initializeSessionRes.status | ||
498 | |||
499 | if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) { | ||
500 | const locationHeader = initializeSessionRes.header['location'] | ||
501 | expect(locationHeader).to.not.be.undefined | ||
502 | |||
503 | const pathUploadId = locationHeader.split('?')[1] | ||
504 | |||
505 | const result = await this.sendResumableChunks({ | ||
506 | ...options, | ||
507 | |||
508 | path, | ||
509 | pathUploadId, | ||
510 | videoFilePath, | ||
511 | size, | ||
512 | expectedStatus: completedExpectedStatus | ||
513 | }) | ||
514 | |||
515 | if (result.statusCode === HttpStatusCode.OK_200) { | ||
516 | await this.endResumableUpload({ | ||
517 | ...options, | ||
518 | |||
519 | expectedStatus: HttpStatusCode.NO_CONTENT_204, | ||
520 | path, | ||
521 | pathUploadId | ||
522 | }) | ||
523 | } | ||
524 | |||
525 | return result.body?.video || result.body as any | ||
526 | } | ||
527 | |||
528 | const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200 | ||
529 | ? HttpStatusCode.CREATED_201 | ||
530 | : expectedStatus | ||
531 | |||
532 | expect(initStatus).to.equal(expectedInitStatus) | ||
533 | |||
534 | return initializeSessionRes.body.video || initializeSessionRes.body | ||
535 | } | ||
536 | |||
537 | async prepareResumableUpload (options: OverrideCommandOptions & { | ||
538 | path: string | ||
539 | attributes: { fixture?: string } & { [id: string]: any } | ||
540 | size: number | ||
541 | mimetype: string | ||
542 | |||
543 | originalName?: string | ||
544 | lastModified?: number | ||
545 | }) { | ||
546 | const { path, attributes, originalName, lastModified, size, mimetype } = options | ||
547 | |||
548 | const attaches = this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ])) | ||
549 | |||
550 | const uploadOptions = { | ||
551 | ...options, | ||
552 | |||
553 | path, | ||
554 | headers: { | ||
555 | 'X-Upload-Content-Type': mimetype, | ||
556 | 'X-Upload-Content-Length': size.toString() | ||
557 | }, | ||
558 | fields: { | ||
559 | filename: attributes.fixture, | ||
560 | originalName, | ||
561 | lastModified, | ||
562 | |||
563 | ...this.buildUploadFields(options.attributes) | ||
564 | }, | ||
565 | |||
566 | // Fixture will be sent later | ||
567 | attaches: this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ])), | ||
568 | implicitToken: true, | ||
569 | |||
570 | defaultExpectedStatus: null | ||
571 | } | ||
572 | |||
573 | if (Object.keys(attaches).length === 0) return this.postBodyRequest(uploadOptions) | ||
574 | |||
575 | return this.postUploadRequest(uploadOptions) | ||
576 | } | ||
577 | |||
578 | sendResumableChunks (options: OverrideCommandOptions & { | ||
579 | pathUploadId: string | ||
580 | path: string | ||
581 | videoFilePath: string | ||
582 | size: number | ||
583 | contentLength?: number | ||
584 | contentRangeBuilder?: (start: number, chunk: any) => string | ||
585 | digestBuilder?: (chunk: any) => string | ||
586 | }) { | ||
587 | const { | ||
588 | path, | ||
589 | pathUploadId, | ||
590 | videoFilePath, | ||
591 | size, | ||
592 | contentLength, | ||
593 | contentRangeBuilder, | ||
594 | digestBuilder, | ||
595 | expectedStatus = HttpStatusCode.OK_200 | ||
596 | } = options | ||
597 | |||
598 | let start = 0 | ||
599 | |||
600 | const token = this.buildCommonRequestToken({ ...options, implicitToken: true }) | ||
601 | |||
602 | const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 }) | ||
603 | const server = this.server | ||
604 | return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => { | ||
605 | readable.on('data', async function onData (chunk) { | ||
606 | try { | ||
607 | readable.pause() | ||
608 | |||
609 | const byterangeStart = start + chunk.length - 1 | ||
610 | |||
611 | const headers = { | ||
612 | 'Authorization': 'Bearer ' + token, | ||
613 | 'Content-Type': 'application/octet-stream', | ||
614 | 'Content-Range': contentRangeBuilder | ||
615 | ? contentRangeBuilder(start, chunk) | ||
616 | : `bytes ${start}-${byterangeStart}/${size}`, | ||
617 | 'Content-Length': contentLength ? contentLength + '' : chunk.length + '' | ||
618 | } | ||
619 | |||
620 | if (digestBuilder) { | ||
621 | Object.assign(headers, { digest: digestBuilder(chunk) }) | ||
622 | } | ||
623 | |||
624 | const res = await got<{ video: VideoCreateResult }>({ | ||
625 | url: new URL(path + '?' + pathUploadId, server.url).toString(), | ||
626 | method: 'put', | ||
627 | headers, | ||
628 | body: chunk, | ||
629 | responseType: 'json', | ||
630 | throwHttpErrors: false | ||
631 | }) | ||
632 | |||
633 | start += chunk.length | ||
634 | |||
635 | // Last request, check final status | ||
636 | if (byterangeStart + 1 === size) { | ||
637 | if (res.statusCode === expectedStatus) { | ||
638 | return resolve(res) | ||
639 | } | ||
640 | |||
641 | if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) { | ||
642 | readable.off('data', onData) | ||
643 | |||
644 | // eslint-disable-next-line max-len | ||
645 | const message = `Incorrect transient behaviour sending intermediary chunks. Status code is ${res.statusCode} instead of ${expectedStatus}` | ||
646 | return reject(new Error(message)) | ||
647 | } | ||
648 | } | ||
649 | |||
650 | readable.resume() | ||
651 | } catch (err) { | ||
652 | reject(err) | ||
653 | } | ||
654 | }) | ||
655 | }) | ||
656 | } | ||
657 | |||
658 | endResumableUpload (options: OverrideCommandOptions & { | ||
659 | path: string | ||
660 | pathUploadId: string | ||
661 | }) { | ||
662 | return this.deleteRequest({ | ||
663 | ...options, | ||
664 | |||
665 | path: options.path, | ||
666 | rawQuery: options.pathUploadId, | ||
667 | implicitToken: true, | ||
668 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
669 | }) | ||
670 | } | ||
671 | |||
672 | quickUpload (options: OverrideCommandOptions & { | ||
673 | name: string | ||
674 | nsfw?: boolean | ||
675 | privacy?: VideoPrivacyType | ||
676 | fixture?: string | ||
677 | videoPasswords?: string[] | ||
678 | }) { | ||
679 | const attributes: VideoEdit = { name: options.name } | ||
680 | if (options.nsfw) attributes.nsfw = options.nsfw | ||
681 | if (options.privacy) attributes.privacy = options.privacy | ||
682 | if (options.fixture) attributes.fixture = options.fixture | ||
683 | if (options.videoPasswords) attributes.videoPasswords = options.videoPasswords | ||
684 | |||
685 | return this.upload({ ...options, attributes }) | ||
686 | } | ||
687 | |||
688 | async randomUpload (options: OverrideCommandOptions & { | ||
689 | wait?: boolean // default true | ||
690 | additionalParams?: VideoEdit & { prefixName?: string } | ||
691 | } = {}) { | ||
692 | const { wait = true, additionalParams } = options | ||
693 | const prefixName = additionalParams?.prefixName || '' | ||
694 | const name = prefixName + buildUUID() | ||
695 | |||
696 | const attributes = { name, ...additionalParams } | ||
697 | |||
698 | const result = await this.upload({ ...options, attributes }) | ||
699 | |||
700 | if (wait) await waitJobs([ this.server ]) | ||
701 | |||
702 | return { ...result, name } | ||
703 | } | ||
704 | |||
705 | // --------------------------------------------------------------------------- | ||
706 | |||
707 | replaceSourceFile (options: OverrideCommandOptions & { | ||
708 | videoId: number | string | ||
709 | fixture: string | ||
710 | completedExpectedStatus?: HttpStatusCodeType | ||
711 | }) { | ||
712 | return this.buildResumeUpload({ | ||
713 | ...options, | ||
714 | |||
715 | path: '/api/v1/videos/' + options.videoId + '/source/replace-resumable', | ||
716 | attributes: { fixture: options.fixture } | ||
717 | }) | ||
718 | } | ||
719 | |||
720 | // --------------------------------------------------------------------------- | ||
721 | |||
722 | removeHLSPlaylist (options: OverrideCommandOptions & { | ||
723 | videoId: number | string | ||
724 | }) { | ||
725 | const path = '/api/v1/videos/' + options.videoId + '/hls' | ||
726 | |||
727 | return this.deleteRequest({ | ||
728 | ...options, | ||
729 | |||
730 | path, | ||
731 | implicitToken: true, | ||
732 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
733 | }) | ||
734 | } | ||
735 | |||
736 | removeHLSFile (options: OverrideCommandOptions & { | ||
737 | videoId: number | string | ||
738 | fileId: number | ||
739 | }) { | ||
740 | const path = '/api/v1/videos/' + options.videoId + '/hls/' + options.fileId | ||
741 | |||
742 | return this.deleteRequest({ | ||
743 | ...options, | ||
744 | |||
745 | path, | ||
746 | implicitToken: true, | ||
747 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
748 | }) | ||
749 | } | ||
750 | |||
751 | removeAllWebVideoFiles (options: OverrideCommandOptions & { | ||
752 | videoId: number | string | ||
753 | }) { | ||
754 | const path = '/api/v1/videos/' + options.videoId + '/web-videos' | ||
755 | |||
756 | return this.deleteRequest({ | ||
757 | ...options, | ||
758 | |||
759 | path, | ||
760 | implicitToken: true, | ||
761 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
762 | }) | ||
763 | } | ||
764 | |||
765 | removeWebVideoFile (options: OverrideCommandOptions & { | ||
766 | videoId: number | string | ||
767 | fileId: number | ||
768 | }) { | ||
769 | const path = '/api/v1/videos/' + options.videoId + '/web-videos/' + options.fileId | ||
770 | |||
771 | return this.deleteRequest({ | ||
772 | ...options, | ||
773 | |||
774 | path, | ||
775 | implicitToken: true, | ||
776 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
777 | }) | ||
778 | } | ||
779 | |||
780 | runTranscoding (options: OverrideCommandOptions & VideoTranscodingCreate & { | ||
781 | videoId: number | string | ||
782 | }) { | ||
783 | const path = '/api/v1/videos/' + options.videoId + '/transcoding' | ||
784 | |||
785 | return this.postBodyRequest({ | ||
786 | ...options, | ||
787 | |||
788 | path, | ||
789 | fields: pick(options, [ 'transcodingType', 'forceTranscoding' ]), | ||
790 | implicitToken: true, | ||
791 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
792 | }) | ||
793 | } | ||
794 | |||
795 | // --------------------------------------------------------------------------- | ||
796 | |||
797 | private buildListQuery (options: VideosCommonQuery) { | ||
798 | return pick(options, [ | ||
799 | 'start', | ||
800 | 'count', | ||
801 | 'sort', | ||
802 | 'nsfw', | ||
803 | 'isLive', | ||
804 | 'categoryOneOf', | ||
805 | 'licenceOneOf', | ||
806 | 'languageOneOf', | ||
807 | 'privacyOneOf', | ||
808 | 'tagsOneOf', | ||
809 | 'tagsAllOf', | ||
810 | 'isLocal', | ||
811 | 'include', | ||
812 | 'skipCount' | ||
813 | ]) | ||
814 | } | ||
815 | |||
816 | private buildUploadFields (attributes: VideoEdit) { | ||
817 | return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ]) | ||
818 | } | ||
819 | |||
820 | private buildUploadAttaches (attributes: VideoEdit) { | ||
821 | const attaches: { [ name: string ]: string } = {} | ||
822 | |||
823 | for (const key of [ 'thumbnailfile', 'previewfile' ]) { | ||
824 | if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key]) | ||
825 | } | ||
826 | |||
827 | if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture) | ||
828 | |||
829 | return attaches | ||
830 | } | ||
831 | } | ||
diff --git a/packages/server-commands/src/videos/views-command.ts b/packages/server-commands/src/videos/views-command.ts new file mode 100644 index 000000000..048bd3fda --- /dev/null +++ b/packages/server-commands/src/videos/views-command.ts | |||
@@ -0,0 +1,51 @@ | |||
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ | ||
2 | import { HttpStatusCode, VideoViewEvent } from '@peertube/peertube-models' | ||
3 | import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js' | ||
4 | |||
5 | export class ViewsCommand extends AbstractCommand { | ||
6 | |||
7 | view (options: OverrideCommandOptions & { | ||
8 | id: number | string | ||
9 | currentTime: number | ||
10 | viewEvent?: VideoViewEvent | ||
11 | xForwardedFor?: string | ||
12 | }) { | ||
13 | const { id, xForwardedFor, viewEvent, currentTime } = options | ||
14 | const path = '/api/v1/videos/' + id + '/views' | ||
15 | |||
16 | return this.postBodyRequest({ | ||
17 | ...options, | ||
18 | |||
19 | path, | ||
20 | xForwardedFor, | ||
21 | fields: { | ||
22 | currentTime, | ||
23 | viewEvent | ||
24 | }, | ||
25 | implicitToken: false, | ||
26 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | ||
27 | }) | ||
28 | } | ||
29 | |||
30 | async simulateView (options: OverrideCommandOptions & { | ||
31 | id: number | string | ||
32 | xForwardedFor?: string | ||
33 | }) { | ||
34 | await this.view({ ...options, currentTime: 0 }) | ||
35 | await this.view({ ...options, currentTime: 5 }) | ||
36 | } | ||
37 | |||
38 | async simulateViewer (options: OverrideCommandOptions & { | ||
39 | id: number | string | ||
40 | currentTimes: number[] | ||
41 | xForwardedFor?: string | ||
42 | }) { | ||
43 | let viewEvent: VideoViewEvent = 'seek' | ||
44 | |||
45 | for (const currentTime of options.currentTimes) { | ||
46 | await this.view({ ...options, currentTime, viewEvent }) | ||
47 | |||
48 | viewEvent = undefined | ||
49 | } | ||
50 | } | ||
51 | } | ||
diff --git a/packages/server-commands/tsconfig.json b/packages/server-commands/tsconfig.json new file mode 100644 index 000000000..eb942f295 --- /dev/null +++ b/packages/server-commands/tsconfig.json | |||
@@ -0,0 +1,14 @@ | |||
1 | { | ||
2 | "extends": "../../tsconfig.base.json", | ||
3 | "compilerOptions": { | ||
4 | "baseUrl": "./", | ||
5 | "outDir": "./dist", | ||
6 | "rootDir": "src", | ||
7 | "tsBuildInfoFile": "./dist/.tsbuildinfo" | ||
8 | }, | ||
9 | "references": [ | ||
10 | { "path": "../models" }, | ||
11 | { "path": "../core-utils" }, | ||
12 | { "path": "../typescript-utils" } | ||
13 | ] | ||
14 | } | ||