aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/server-commands/server
diff options
context:
space:
mode:
Diffstat (limited to 'shared/server-commands/server')
-rw-r--r--shared/server-commands/server/config-command.ts576
-rw-r--r--shared/server-commands/server/contact-form-command.ts31
-rw-r--r--shared/server-commands/server/debug-command.ts33
-rw-r--r--shared/server-commands/server/follows-command.ts139
-rw-r--r--shared/server-commands/server/follows.ts20
-rw-r--r--shared/server-commands/server/index.ts15
-rw-r--r--shared/server-commands/server/jobs-command.ts84
-rw-r--r--shared/server-commands/server/jobs.ts118
-rw-r--r--shared/server-commands/server/metrics-command.ts18
-rw-r--r--shared/server-commands/server/object-storage-command.ts165
-rw-r--r--shared/server-commands/server/plugins-command.ts257
-rw-r--r--shared/server-commands/server/redundancy-command.ts80
-rw-r--r--shared/server-commands/server/server.ts450
-rw-r--r--shared/server-commands/server/servers-command.ts103
-rw-r--r--shared/server-commands/server/servers.ts68
-rw-r--r--shared/server-commands/server/stats-command.ts25
16 files changed, 0 insertions, 2182 deletions
diff --git a/shared/server-commands/server/config-command.ts b/shared/server-commands/server/config-command.ts
deleted file mode 100644
index 5ee2fe021..000000000
--- a/shared/server-commands/server/config-command.ts
+++ /dev/null
@@ -1,576 +0,0 @@
1import { merge } from 'lodash'
2import { About, CustomConfig, HttpStatusCode, ServerConfig } from '@shared/models'
3import { DeepPartial } from '@shared/typescript-utils'
4import { AbstractCommand, OverrideCommandOptions } from '../shared/abstract-command'
5
6export 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/shared/server-commands/server/contact-form-command.ts b/shared/server-commands/server/contact-form-command.ts
deleted file mode 100644
index 0e8fd6d84..000000000
--- a/shared/server-commands/server/contact-form-command.ts
+++ /dev/null
@@ -1,31 +0,0 @@
1import { HttpStatusCode } from '@shared/models'
2import { ContactForm } from '../../models/server'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export class ContactFormCommand extends AbstractCommand {
6
7 send (options: OverrideCommandOptions & {
8 fromEmail: string
9 fromName: string
10 subject: string
11 body: string
12 }) {
13 const path = '/api/v1/server/contact'
14
15 const body: ContactForm = {
16 fromEmail: options.fromEmail,
17 fromName: options.fromName,
18 subject: options.subject,
19 body: options.body
20 }
21
22 return this.postBodyRequest({
23 ...options,
24
25 path,
26 fields: body,
27 implicitToken: false,
28 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
29 })
30 }
31}
diff --git a/shared/server-commands/server/debug-command.ts b/shared/server-commands/server/debug-command.ts
deleted file mode 100644
index 3c5a785bb..000000000
--- a/shared/server-commands/server/debug-command.ts
+++ /dev/null
@@ -1,33 +0,0 @@
1import { Debug, HttpStatusCode, SendDebugCommand } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/server/follows-command.ts b/shared/server-commands/server/follows-command.ts
deleted file mode 100644
index 496e11df1..000000000
--- a/shared/server-commands/server/follows-command.ts
+++ /dev/null
@@ -1,139 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList, ServerFollowCreate } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4import { PeerTubeServer } from './server'
5
6export 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/shared/server-commands/server/follows.ts b/shared/server-commands/server/follows.ts
deleted file mode 100644
index 698238f29..000000000
--- a/shared/server-commands/server/follows.ts
+++ /dev/null
@@ -1,20 +0,0 @@
1import { waitJobs } from './jobs'
2import { PeerTubeServer } from './server'
3
4async 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
18export {
19 doubleFollow
20}
diff --git a/shared/server-commands/server/index.ts b/shared/server-commands/server/index.ts
deleted file mode 100644
index 9a2fbf8d3..000000000
--- a/shared/server-commands/server/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
1export * from './config-command'
2export * from './contact-form-command'
3export * from './debug-command'
4export * from './follows-command'
5export * from './follows'
6export * from './jobs'
7export * from './jobs-command'
8export * from './metrics-command'
9export * from './object-storage-command'
10export * from './plugins-command'
11export * from './redundancy-command'
12export * from './server'
13export * from './servers-command'
14export * from './servers'
15export * from './stats-command'
diff --git a/shared/server-commands/server/jobs-command.ts b/shared/server-commands/server/jobs-command.ts
deleted file mode 100644
index b8790ea00..000000000
--- a/shared/server-commands/server/jobs-command.ts
+++ /dev/null
@@ -1,84 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { HttpStatusCode, Job, JobState, JobType, ResultList } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export 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/shared/server-commands/server/jobs.ts b/shared/server-commands/server/jobs.ts
deleted file mode 100644
index 8f131fba4..000000000
--- a/shared/server-commands/server/jobs.ts
+++ /dev/null
@@ -1,118 +0,0 @@
1
2import { expect } from 'chai'
3import { wait } from '@shared/core-utils'
4import { JobState, JobType, RunnerJobState } from '../../models'
5import { PeerTubeServer } from './server'
6
7async function waitJobs (
8 serversArg: PeerTubeServer[] | PeerTubeServer,
9 options: {
10 skipDelayed?: boolean // default false
11 runnerJobs?: boolean // default false
12 } = {}
13) {
14 const { skipDelayed = false, runnerJobs = false } = options
15
16 const pendingJobWait = process.env.NODE_PENDING_JOB_WAIT
17 ? parseInt(process.env.NODE_PENDING_JOB_WAIT, 10)
18 : 250
19
20 let servers: PeerTubeServer[]
21
22 if (Array.isArray(serversArg) === false) servers = [ serversArg as PeerTubeServer ]
23 else servers = serversArg as PeerTubeServer[]
24
25 const states: JobState[] = [ 'waiting', 'active' ]
26 if (!skipDelayed) states.push('delayed')
27
28 const repeatableJobs: JobType[] = [ 'videos-views-stats', 'activitypub-cleaner' ]
29 let pendingRequests: boolean
30
31 function tasksBuilder () {
32 const tasks: Promise<any>[] = []
33
34 // Check if each server has pending request
35 for (const server of servers) {
36 if (process.env.DEBUG) console.log('Checking ' + server.url)
37
38 for (const state of states) {
39
40 const jobPromise = server.jobs.list({
41 state,
42 start: 0,
43 count: 10,
44 sort: '-createdAt'
45 }).then(body => body.data)
46 .then(jobs => jobs.filter(j => !repeatableJobs.includes(j.type)))
47 .then(jobs => {
48 if (jobs.length !== 0) {
49 pendingRequests = true
50
51 if (process.env.DEBUG) {
52 console.log(jobs)
53 }
54 }
55 })
56
57 tasks.push(jobPromise)
58 }
59
60 const debugPromise = server.debug.getDebug()
61 .then(obj => {
62 if (obj.activityPubMessagesWaiting !== 0) {
63 pendingRequests = true
64
65 if (process.env.DEBUG) {
66 console.log('AP messages waiting: ' + obj.activityPubMessagesWaiting)
67 }
68 }
69 })
70 tasks.push(debugPromise)
71
72 if (runnerJobs) {
73 const runnerJobsPromise = server.runnerJobs.list({ count: 100 })
74 .then(({ data }) => {
75 for (const job of data) {
76 if (job.state.id !== RunnerJobState.COMPLETED) {
77 pendingRequests = true
78
79 if (process.env.DEBUG) {
80 console.log(job)
81 }
82 }
83 }
84 })
85 tasks.push(runnerJobsPromise)
86 }
87 }
88
89 return tasks
90 }
91
92 do {
93 pendingRequests = false
94 await Promise.all(tasksBuilder())
95
96 // Retry, in case of new jobs were created
97 if (pendingRequests === false) {
98 await wait(pendingJobWait)
99 await Promise.all(tasksBuilder())
100 }
101
102 if (pendingRequests) {
103 await wait(pendingJobWait)
104 }
105 } while (pendingRequests)
106}
107
108async function expectNoFailedTranscodingJob (server: PeerTubeServer) {
109 const { data } = await server.jobs.listFailed({ jobType: 'video-transcoding' })
110 expect(data).to.have.lengthOf(0)
111}
112
113// ---------------------------------------------------------------------------
114
115export {
116 waitJobs,
117 expectNoFailedTranscodingJob
118}
diff --git a/shared/server-commands/server/metrics-command.ts b/shared/server-commands/server/metrics-command.ts
deleted file mode 100644
index d22b4833d..000000000
--- a/shared/server-commands/server/metrics-command.ts
+++ /dev/null
@@ -1,18 +0,0 @@
1import { HttpStatusCode, PlaybackMetricCreate } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/server/object-storage-command.ts b/shared/server-commands/server/object-storage-command.ts
deleted file mode 100644
index 6bb232c36..000000000
--- a/shared/server-commands/server/object-storage-command.ts
+++ /dev/null
@@ -1,165 +0,0 @@
1import { randomInt } from 'crypto'
2import { HttpStatusCode } from '@shared/models'
3import { makePostBodyRequest } from '../requests'
4
5export 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/shared/server-commands/server/plugins-command.ts b/shared/server-commands/server/plugins-command.ts
deleted file mode 100644
index bb1277a7c..000000000
--- a/shared/server-commands/server/plugins-command.ts
+++ /dev/null
@@ -1,257 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3import { readJSON, writeJSON } from 'fs-extra'
4import { join } from 'path'
5import { root } from '@shared/core-utils'
6import {
7 HttpStatusCode,
8 PeerTubePlugin,
9 PeerTubePluginIndex,
10 PeertubePluginIndexList,
11 PluginPackageJSON,
12 PluginTranslation,
13 PluginType,
14 PublicServerSetting,
15 RegisteredServerSettings,
16 ResultList
17} from '@shared/models'
18import { AbstractCommand, OverrideCommandOptions } from '../shared'
19
20export class PluginsCommand extends AbstractCommand {
21
22 static getPluginTestPath (suffix = '') {
23 return join(root(), 'server', 'tests', 'fixtures', 'peertube-plugin-test' + suffix)
24 }
25
26 list (options: OverrideCommandOptions & {
27 start?: number
28 count?: number
29 sort?: string
30 pluginType?: PluginType
31 uninstalled?: boolean
32 }) {
33 const { start, count, sort, pluginType, uninstalled } = options
34 const path = '/api/v1/plugins'
35
36 return this.getRequestBody<ResultList<PeerTubePlugin>>({
37 ...options,
38
39 path,
40 query: {
41 start,
42 count,
43 sort,
44 pluginType,
45 uninstalled
46 },
47 implicitToken: true,
48 defaultExpectedStatus: HttpStatusCode.OK_200
49 })
50 }
51
52 listAvailable (options: OverrideCommandOptions & {
53 start?: number
54 count?: number
55 sort?: string
56 pluginType?: PluginType
57 currentPeerTubeEngine?: string
58 search?: string
59 expectedStatus?: HttpStatusCode
60 }) {
61 const { start, count, sort, pluginType, search, currentPeerTubeEngine } = options
62 const path = '/api/v1/plugins/available'
63
64 const query: PeertubePluginIndexList = {
65 start,
66 count,
67 sort,
68 pluginType,
69 currentPeerTubeEngine,
70 search
71 }
72
73 return this.getRequestBody<ResultList<PeerTubePluginIndex>>({
74 ...options,
75
76 path,
77 query,
78 implicitToken: true,
79 defaultExpectedStatus: HttpStatusCode.OK_200
80 })
81 }
82
83 get (options: OverrideCommandOptions & {
84 npmName: string
85 }) {
86 const path = '/api/v1/plugins/' + options.npmName
87
88 return this.getRequestBody<PeerTubePlugin>({
89 ...options,
90
91 path,
92 implicitToken: true,
93 defaultExpectedStatus: HttpStatusCode.OK_200
94 })
95 }
96
97 updateSettings (options: OverrideCommandOptions & {
98 npmName: string
99 settings: any
100 }) {
101 const { npmName, settings } = options
102 const path = '/api/v1/plugins/' + npmName + '/settings'
103
104 return this.putBodyRequest({
105 ...options,
106
107 path,
108 fields: { settings },
109 implicitToken: true,
110 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
111 })
112 }
113
114 getRegisteredSettings (options: OverrideCommandOptions & {
115 npmName: string
116 }) {
117 const path = '/api/v1/plugins/' + options.npmName + '/registered-settings'
118
119 return this.getRequestBody<RegisteredServerSettings>({
120 ...options,
121
122 path,
123 implicitToken: true,
124 defaultExpectedStatus: HttpStatusCode.OK_200
125 })
126 }
127
128 getPublicSettings (options: OverrideCommandOptions & {
129 npmName: string
130 }) {
131 const { npmName } = options
132 const path = '/api/v1/plugins/' + npmName + '/public-settings'
133
134 return this.getRequestBody<PublicServerSetting>({
135 ...options,
136
137 path,
138 implicitToken: false,
139 defaultExpectedStatus: HttpStatusCode.OK_200
140 })
141 }
142
143 getTranslations (options: OverrideCommandOptions & {
144 locale: string
145 }) {
146 const { locale } = options
147 const path = '/plugins/translations/' + locale + '.json'
148
149 return this.getRequestBody<PluginTranslation>({
150 ...options,
151
152 path,
153 implicitToken: false,
154 defaultExpectedStatus: HttpStatusCode.OK_200
155 })
156 }
157
158 install (options: OverrideCommandOptions & {
159 path?: string
160 npmName?: string
161 pluginVersion?: string
162 }) {
163 const { npmName, path, pluginVersion } = options
164 const apiPath = '/api/v1/plugins/install'
165
166 return this.postBodyRequest({
167 ...options,
168
169 path: apiPath,
170 fields: { npmName, path, pluginVersion },
171 implicitToken: true,
172 defaultExpectedStatus: HttpStatusCode.OK_200
173 })
174 }
175
176 update (options: OverrideCommandOptions & {
177 path?: string
178 npmName?: string
179 }) {
180 const { npmName, path } = options
181 const apiPath = '/api/v1/plugins/update'
182
183 return this.postBodyRequest({
184 ...options,
185
186 path: apiPath,
187 fields: { npmName, path },
188 implicitToken: true,
189 defaultExpectedStatus: HttpStatusCode.OK_200
190 })
191 }
192
193 uninstall (options: OverrideCommandOptions & {
194 npmName: string
195 }) {
196 const { npmName } = options
197 const apiPath = '/api/v1/plugins/uninstall'
198
199 return this.postBodyRequest({
200 ...options,
201
202 path: apiPath,
203 fields: { npmName },
204 implicitToken: true,
205 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
206 })
207 }
208
209 getCSS (options: OverrideCommandOptions = {}) {
210 const path = '/plugins/global.css'
211
212 return this.getRequestText({
213 ...options,
214
215 path,
216 implicitToken: false,
217 defaultExpectedStatus: HttpStatusCode.OK_200
218 })
219 }
220
221 getExternalAuth (options: OverrideCommandOptions & {
222 npmName: string
223 npmVersion: string
224 authName: string
225 query?: any
226 }) {
227 const { npmName, npmVersion, authName, query } = options
228
229 const path = '/plugins/' + npmName + '/' + npmVersion + '/auth/' + authName
230
231 return this.getRequest({
232 ...options,
233
234 path,
235 query,
236 implicitToken: false,
237 defaultExpectedStatus: HttpStatusCode.OK_200,
238 redirects: 0
239 })
240 }
241
242 updatePackageJSON (npmName: string, json: any) {
243 const path = this.getPackageJSONPath(npmName)
244
245 return writeJSON(path, json)
246 }
247
248 getPackageJSON (npmName: string): Promise<PluginPackageJSON> {
249 const path = this.getPackageJSONPath(npmName)
250
251 return readJSON(path)
252 }
253
254 private getPackageJSONPath (npmName: string) {
255 return this.server.servers.buildDirectory(join('plugins', 'node_modules', npmName, 'package.json'))
256 }
257}
diff --git a/shared/server-commands/server/redundancy-command.ts b/shared/server-commands/server/redundancy-command.ts
deleted file mode 100644
index e7a8b3c29..000000000
--- a/shared/server-commands/server/redundancy-command.ts
+++ /dev/null
@@ -1,80 +0,0 @@
1import { HttpStatusCode, ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/server/server.ts b/shared/server-commands/server/server.ts
deleted file mode 100644
index 38568a890..000000000
--- a/shared/server-commands/server/server.ts
+++ /dev/null
@@ -1,450 +0,0 @@
1import { ChildProcess, fork } from 'child_process'
2import { copy } from 'fs-extra'
3import { join } from 'path'
4import { parallelTests, randomInt, root } from '@shared/core-utils'
5import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@shared/models'
6import { BulkCommand } from '../bulk'
7import { CLICommand } from '../cli'
8import { CustomPagesCommand } from '../custom-pages'
9import { FeedCommand } from '../feeds'
10import { LogsCommand } from '../logs'
11import { AbusesCommand } from '../moderation'
12import { OverviewsCommand } from '../overviews'
13import { RunnerJobsCommand, RunnerRegistrationTokensCommand, RunnersCommand } from '../runners'
14import { SearchCommand } from '../search'
15import { SocketIOCommand } from '../socket'
16import {
17 AccountsCommand,
18 BlocklistCommand,
19 LoginCommand,
20 NotificationsCommand,
21 RegistrationsCommand,
22 SubscriptionsCommand,
23 TwoFactorCommand,
24 UsersCommand
25} from '../users'
26import {
27 BlacklistCommand,
28 CaptionsCommand,
29 ChangeOwnershipCommand,
30 ChannelsCommand,
31 ChannelSyncsCommand,
32 HistoryCommand,
33 ImportsCommand,
34 LiveCommand,
35 VideoPasswordsCommand,
36 PlaylistsCommand,
37 ServicesCommand,
38 StoryboardCommand,
39 StreamingPlaylistsCommand,
40 VideosCommand,
41 VideoStudioCommand,
42 VideoTokenCommand,
43 ViewsCommand
44} from '../videos'
45import { CommentsCommand } from '../videos/comments-command'
46import { VideoStatsCommand } from '../videos/video-stats-command'
47import { ConfigCommand } from './config-command'
48import { ContactFormCommand } from './contact-form-command'
49import { DebugCommand } from './debug-command'
50import { FollowsCommand } from './follows-command'
51import { JobsCommand } from './jobs-command'
52import { MetricsCommand } from './metrics-command'
53import { PluginsCommand } from './plugins-command'
54import { RedundancyCommand } from './redundancy-command'
55import { ServersCommand } from './servers-command'
56import { StatsCommand } from './stats-command'
57
58export type RunServerOptions = {
59 hideLogs?: boolean
60 nodeArgs?: string[]
61 peertubeArgs?: string[]
62 env?: { [ id: string ]: string }
63}
64
65export class PeerTubeServer {
66 app?: ChildProcess
67
68 url: string
69 host?: string
70 hostname?: string
71 port?: number
72
73 rtmpPort?: number
74 rtmpsPort?: number
75
76 parallel?: boolean
77 internalServerNumber: number
78
79 serverNumber?: number
80 customConfigFile?: string
81
82 store?: {
83 client?: {
84 id?: string
85 secret?: string
86 }
87
88 user?: {
89 username: string
90 password: string
91 email?: string
92 }
93
94 channel?: VideoChannel
95 videoChannelSync?: Partial<VideoChannelSync>
96
97 video?: Video
98 videoCreated?: VideoCreateResult
99 videoDetails?: VideoDetails
100
101 videos?: { id: number, uuid: string }[]
102 }
103
104 accessToken?: string
105 refreshToken?: string
106
107 bulk?: BulkCommand
108 cli?: CLICommand
109 customPage?: CustomPagesCommand
110 feed?: FeedCommand
111 logs?: LogsCommand
112 abuses?: AbusesCommand
113 overviews?: OverviewsCommand
114 search?: SearchCommand
115 contactForm?: ContactFormCommand
116 debug?: DebugCommand
117 follows?: FollowsCommand
118 jobs?: JobsCommand
119 metrics?: MetricsCommand
120 plugins?: PluginsCommand
121 redundancy?: RedundancyCommand
122 stats?: StatsCommand
123 config?: ConfigCommand
124 socketIO?: SocketIOCommand
125 accounts?: AccountsCommand
126 blocklist?: BlocklistCommand
127 subscriptions?: SubscriptionsCommand
128 live?: LiveCommand
129 services?: ServicesCommand
130 blacklist?: BlacklistCommand
131 captions?: CaptionsCommand
132 changeOwnership?: ChangeOwnershipCommand
133 playlists?: PlaylistsCommand
134 history?: HistoryCommand
135 imports?: ImportsCommand
136 channelSyncs?: ChannelSyncsCommand
137 streamingPlaylists?: StreamingPlaylistsCommand
138 channels?: ChannelsCommand
139 comments?: CommentsCommand
140 notifications?: NotificationsCommand
141 servers?: ServersCommand
142 login?: LoginCommand
143 users?: UsersCommand
144 videoStudio?: VideoStudioCommand
145 videos?: VideosCommand
146 videoStats?: VideoStatsCommand
147 views?: ViewsCommand
148 twoFactor?: TwoFactorCommand
149 videoToken?: VideoTokenCommand
150 registrations?: RegistrationsCommand
151 videoPasswords?: VideoPasswordsCommand
152
153 storyboard?: StoryboardCommand
154
155 runners?: RunnersCommand
156 runnerRegistrationTokens?: RunnerRegistrationTokensCommand
157 runnerJobs?: RunnerJobsCommand
158
159 constructor (options: { serverNumber: number } | { url: string }) {
160 if ((options as any).url) {
161 this.setUrl((options as any).url)
162 } else {
163 this.setServerNumber((options as any).serverNumber)
164 }
165
166 this.store = {
167 client: {
168 id: null,
169 secret: null
170 },
171 user: {
172 username: null,
173 password: null
174 }
175 }
176
177 this.assignCommands()
178 }
179
180 setServerNumber (serverNumber: number) {
181 this.serverNumber = serverNumber
182
183 this.parallel = parallelTests()
184
185 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
186 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
187 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
188 this.port = 9000 + this.internalServerNumber
189
190 this.url = `http://127.0.0.1:${this.port}`
191 this.host = `127.0.0.1:${this.port}`
192 this.hostname = '127.0.0.1'
193 }
194
195 setUrl (url: string) {
196 const parsed = new URL(url)
197
198 this.url = url
199 this.host = parsed.host
200 this.hostname = parsed.hostname
201 this.port = parseInt(parsed.port)
202 }
203
204 getDirectoryPath (directoryName: string) {
205 const testDirectory = 'test' + this.internalServerNumber
206
207 return join(root(), testDirectory, directoryName)
208 }
209
210 async flushAndRun (configOverride?: object, options: RunServerOptions = {}) {
211 await ServersCommand.flushTests(this.internalServerNumber)
212
213 return this.run(configOverride, options)
214 }
215
216 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
217 // These actions are async so we need to be sure that they have both been done
218 const serverRunString = {
219 'HTTP server listening': false
220 }
221 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
222 serverRunString[key] = false
223
224 const regexps = {
225 client_id: 'Client id: (.+)',
226 client_secret: 'Client secret: (.+)',
227 user_username: 'Username: (.+)',
228 user_password: 'User password: (.+)'
229 }
230
231 await this.assignCustomConfigFile()
232
233 const configOverride = this.buildConfigOverride()
234
235 if (configOverrideArg !== undefined) {
236 Object.assign(configOverride, configOverrideArg)
237 }
238
239 // Share the environment
240 const env = { ...process.env }
241 env['NODE_ENV'] = 'test'
242 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
243 env['NODE_CONFIG'] = JSON.stringify(configOverride)
244
245 if (options.env) {
246 Object.assign(env, options.env)
247 }
248
249 const execArgv = options.nodeArgs || []
250 // FIXME: too slow :/
251 // execArgv.push('--enable-source-maps')
252
253 const forkOptions = {
254 silent: true,
255 env,
256 detached: false,
257 execArgv
258 }
259
260 const peertubeArgs = options.peertubeArgs || []
261
262 return new Promise<void>((res, rej) => {
263 const self = this
264 let aggregatedLogs = ''
265
266 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
267
268 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
269 const onParentExit = () => {
270 if (!this.app?.pid) return
271
272 try {
273 process.kill(self.app.pid)
274 } catch { /* empty */ }
275 }
276
277 this.app.on('exit', onPeerTubeExit)
278 process.on('exit', onParentExit)
279
280 this.app.stdout.on('data', function onStdout (data) {
281 let dontContinue = false
282
283 const log: string = data.toString()
284 aggregatedLogs += log
285
286 // Capture things if we want to
287 for (const key of Object.keys(regexps)) {
288 const regexp = regexps[key]
289 const matches = log.match(regexp)
290 if (matches !== null) {
291 if (key === 'client_id') self.store.client.id = matches[1]
292 else if (key === 'client_secret') self.store.client.secret = matches[1]
293 else if (key === 'user_username') self.store.user.username = matches[1]
294 else if (key === 'user_password') self.store.user.password = matches[1]
295 }
296 }
297
298 // Check if all required sentences are here
299 for (const key of Object.keys(serverRunString)) {
300 if (log.includes(key)) serverRunString[key] = true
301 if (serverRunString[key] === false) dontContinue = true
302 }
303
304 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
305 if (dontContinue === true) return
306
307 if (options.hideLogs === false) {
308 console.log(log)
309 } else {
310 process.removeListener('exit', onParentExit)
311 self.app.stdout.removeListener('data', onStdout)
312 self.app.removeListener('exit', onPeerTubeExit)
313 }
314
315 res()
316 })
317 })
318 }
319
320 kill () {
321 if (!this.app) return Promise.resolve()
322
323 process.kill(this.app.pid)
324
325 this.app = null
326
327 return Promise.resolve()
328 }
329
330 private randomServer () {
331 const low = 2500
332 const high = 10000
333
334 return randomInt(low, high)
335 }
336
337 private randomRTMP () {
338 const low = 1900
339 const high = 2100
340
341 return randomInt(low, high)
342 }
343
344 private async assignCustomConfigFile () {
345 if (this.internalServerNumber === this.serverNumber) return
346
347 const basePath = join(root(), 'config')
348
349 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
350 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
351
352 this.customConfigFile = tmpConfigFile
353 }
354
355 private buildConfigOverride () {
356 if (!this.parallel) return {}
357
358 return {
359 listen: {
360 port: this.port
361 },
362 webserver: {
363 port: this.port
364 },
365 database: {
366 suffix: '_test' + this.internalServerNumber
367 },
368 storage: {
369 tmp: this.getDirectoryPath('tmp') + '/',
370 tmp_persistent: this.getDirectoryPath('tmp-persistent') + '/',
371 bin: this.getDirectoryPath('bin') + '/',
372 avatars: this.getDirectoryPath('avatars') + '/',
373 web_videos: this.getDirectoryPath('web-videos') + '/',
374 streaming_playlists: this.getDirectoryPath('streaming-playlists') + '/',
375 redundancy: this.getDirectoryPath('redundancy') + '/',
376 logs: this.getDirectoryPath('logs') + '/',
377 previews: this.getDirectoryPath('previews') + '/',
378 thumbnails: this.getDirectoryPath('thumbnails') + '/',
379 storyboards: this.getDirectoryPath('storyboards') + '/',
380 torrents: this.getDirectoryPath('torrents') + '/',
381 captions: this.getDirectoryPath('captions') + '/',
382 cache: this.getDirectoryPath('cache') + '/',
383 plugins: this.getDirectoryPath('plugins') + '/',
384 well_known: this.getDirectoryPath('well-known') + '/'
385 },
386 admin: {
387 email: `admin${this.internalServerNumber}@example.com`
388 },
389 live: {
390 rtmp: {
391 port: this.rtmpPort
392 }
393 }
394 }
395 }
396
397 private assignCommands () {
398 this.bulk = new BulkCommand(this)
399 this.cli = new CLICommand(this)
400 this.customPage = new CustomPagesCommand(this)
401 this.feed = new FeedCommand(this)
402 this.logs = new LogsCommand(this)
403 this.abuses = new AbusesCommand(this)
404 this.overviews = new OverviewsCommand(this)
405 this.search = new SearchCommand(this)
406 this.contactForm = new ContactFormCommand(this)
407 this.debug = new DebugCommand(this)
408 this.follows = new FollowsCommand(this)
409 this.jobs = new JobsCommand(this)
410 this.metrics = new MetricsCommand(this)
411 this.plugins = new PluginsCommand(this)
412 this.redundancy = new RedundancyCommand(this)
413 this.stats = new StatsCommand(this)
414 this.config = new ConfigCommand(this)
415 this.socketIO = new SocketIOCommand(this)
416 this.accounts = new AccountsCommand(this)
417 this.blocklist = new BlocklistCommand(this)
418 this.subscriptions = new SubscriptionsCommand(this)
419 this.live = new LiveCommand(this)
420 this.services = new ServicesCommand(this)
421 this.blacklist = new BlacklistCommand(this)
422 this.captions = new CaptionsCommand(this)
423 this.changeOwnership = new ChangeOwnershipCommand(this)
424 this.playlists = new PlaylistsCommand(this)
425 this.history = new HistoryCommand(this)
426 this.imports = new ImportsCommand(this)
427 this.channelSyncs = new ChannelSyncsCommand(this)
428 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
429 this.channels = new ChannelsCommand(this)
430 this.comments = new CommentsCommand(this)
431 this.notifications = new NotificationsCommand(this)
432 this.servers = new ServersCommand(this)
433 this.login = new LoginCommand(this)
434 this.users = new UsersCommand(this)
435 this.videos = new VideosCommand(this)
436 this.videoStudio = new VideoStudioCommand(this)
437 this.videoStats = new VideoStatsCommand(this)
438 this.views = new ViewsCommand(this)
439 this.twoFactor = new TwoFactorCommand(this)
440 this.videoToken = new VideoTokenCommand(this)
441 this.registrations = new RegistrationsCommand(this)
442
443 this.storyboard = new StoryboardCommand(this)
444
445 this.runners = new RunnersCommand(this)
446 this.runnerRegistrationTokens = new RunnerRegistrationTokensCommand(this)
447 this.runnerJobs = new RunnerJobsCommand(this)
448 this.videoPasswords = new VideoPasswordsCommand(this)
449 }
450}
diff --git a/shared/server-commands/server/servers-command.ts b/shared/server-commands/server/servers-command.ts
deleted file mode 100644
index 54e586a18..000000000
--- a/shared/server-commands/server/servers-command.ts
+++ /dev/null
@@ -1,103 +0,0 @@
1import { exec } from 'child_process'
2import { copy, ensureDir, readFile, readdir, remove } from 'fs-extra'
3import { basename, join } from 'path'
4import { isGithubCI, root, wait } from '@shared/core-utils'
5import { getFileSize } from '@shared/extra-utils'
6import { HttpStatusCode } from '@shared/models'
7import { AbstractCommand, OverrideCommandOptions } from '../shared'
8
9export class ServersCommand extends AbstractCommand {
10
11 static flushTests (internalServerNumber: number) {
12 return new Promise<void>((res, rej) => {
13 const suffix = ` -- ${internalServerNumber}`
14
15 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
16 if (err || stderr) return rej(err || new Error(stderr))
17
18 return res()
19 })
20 })
21 }
22
23 ping (options: OverrideCommandOptions = {}) {
24 return this.getRequestBody({
25 ...options,
26
27 path: '/api/v1/ping',
28 implicitToken: false,
29 defaultExpectedStatus: HttpStatusCode.OK_200
30 })
31 }
32
33 cleanupTests () {
34 const promises: Promise<any>[] = []
35
36 const saveGithubLogsIfNeeded = async () => {
37 if (!isGithubCI()) return
38
39 await ensureDir('artifacts')
40
41 const origin = this.buildDirectory('logs/peertube.log')
42 const destname = `peertube-${this.server.internalServerNumber}.log`
43 console.log('Saving logs %s.', destname)
44
45 await copy(origin, join('artifacts', destname))
46 }
47
48 if (this.server.parallel) {
49 const promise = saveGithubLogsIfNeeded()
50 .then(() => ServersCommand.flushTests(this.server.internalServerNumber))
51
52 promises.push(promise)
53 }
54
55 if (this.server.customConfigFile) {
56 promises.push(remove(this.server.customConfigFile))
57 }
58
59 return promises
60 }
61
62 async waitUntilLog (str: string, count = 1, strictCount = true) {
63 const logfile = this.buildDirectory('logs/peertube.log')
64
65 while (true) {
66 const buf = await readFile(logfile)
67
68 const matches = buf.toString().match(new RegExp(str, 'g'))
69 if (matches && matches.length === count) return
70 if (matches && strictCount === false && matches.length >= count) return
71
72 await wait(1000)
73 }
74 }
75
76 buildDirectory (directory: string) {
77 return join(root(), 'test' + this.server.internalServerNumber, directory)
78 }
79
80 async countFiles (directory: string) {
81 const files = await readdir(this.buildDirectory(directory))
82
83 return files.length
84 }
85
86 buildWebVideoFilePath (fileUrl: string) {
87 return this.buildDirectory(join('web-videos', basename(fileUrl)))
88 }
89
90 buildFragmentedFilePath (videoUUID: string, fileUrl: string) {
91 return this.buildDirectory(join('streaming-playlists', 'hls', videoUUID, basename(fileUrl)))
92 }
93
94 getLogContent () {
95 return readFile(this.buildDirectory('logs/peertube.log'))
96 }
97
98 async getServerFileSize (subPath: string) {
99 const path = this.server.servers.buildDirectory(subPath)
100
101 return getFileSize(path)
102 }
103}
diff --git a/shared/server-commands/server/servers.ts b/shared/server-commands/server/servers.ts
deleted file mode 100644
index fe9da9e63..000000000
--- a/shared/server-commands/server/servers.ts
+++ /dev/null
@@ -1,68 +0,0 @@
1import { ensureDir } from 'fs-extra'
2import { isGithubCI } from '@shared/core-utils'
3import { PeerTubeServer, RunServerOptions } from './server'
4
5async 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
13function 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
23function killallServers (servers: PeerTubeServer[]) {
24 return Promise.all(servers.map(s => s.kill()))
25}
26
27async 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
42function 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://yt-dl.org/downloads/latest/youtube-dl'
50 : 'https://api.github.com/repos/yt-dlp/yt-dlp/releases',
51
52 name: mode
53 }
54 }
55 }
56 }
57 }
58}
59
60// ---------------------------------------------------------------------------
61
62export {
63 createSingleServer,
64 createMultipleServers,
65 cleanupTests,
66 killallServers,
67 getServerImportConfig
68}
diff --git a/shared/server-commands/server/stats-command.ts b/shared/server-commands/server/stats-command.ts
deleted file mode 100644
index 64a452306..000000000
--- a/shared/server-commands/server/stats-command.ts
+++ /dev/null
@@ -1,25 +0,0 @@
1import { HttpStatusCode, ServerStats } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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}