aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/server-commands
diff options
context:
space:
mode:
Diffstat (limited to 'shared/server-commands')
-rw-r--r--shared/server-commands/bulk/bulk-command.ts20
-rw-r--r--shared/server-commands/bulk/index.ts1
-rw-r--r--shared/server-commands/cli/cli-command.ts27
-rw-r--r--shared/server-commands/cli/index.ts1
-rw-r--r--shared/server-commands/custom-pages/custom-pages-command.ts33
-rw-r--r--shared/server-commands/custom-pages/index.ts1
-rw-r--r--shared/server-commands/feeds/feeds-command.ts78
-rw-r--r--shared/server-commands/feeds/index.ts1
-rw-r--r--shared/server-commands/index.ts14
-rw-r--r--shared/server-commands/logs/index.ts1
-rw-r--r--shared/server-commands/logs/logs-command.ts56
-rw-r--r--shared/server-commands/moderation/abuses-command.ts228
-rw-r--r--shared/server-commands/moderation/index.ts1
-rw-r--r--shared/server-commands/overviews/index.ts1
-rw-r--r--shared/server-commands/overviews/overviews-command.ts23
-rw-r--r--shared/server-commands/requests/index.ts1
-rw-r--r--shared/server-commands/requests/requests.ts259
-rw-r--r--shared/server-commands/runners/index.ts3
-rw-r--r--shared/server-commands/runners/runner-jobs-command.ts294
-rw-r--r--shared/server-commands/runners/runner-registration-tokens-command.ts55
-rw-r--r--shared/server-commands/runners/runners-command.ts78
-rw-r--r--shared/server-commands/search/index.ts1
-rw-r--r--shared/server-commands/search/search-command.ts98
-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
-rw-r--r--shared/server-commands/shared/abstract-command.ts223
-rw-r--r--shared/server-commands/shared/index.ts1
-rw-r--r--shared/server-commands/socket/index.ts1
-rw-r--r--shared/server-commands/socket/socket-io-command.ts24
-rw-r--r--shared/server-commands/users/accounts-command.ts76
-rw-r--r--shared/server-commands/users/accounts.ts15
-rw-r--r--shared/server-commands/users/blocklist-command.ts165
-rw-r--r--shared/server-commands/users/index.ts10
-rw-r--r--shared/server-commands/users/login-command.ts159
-rw-r--r--shared/server-commands/users/login.ts19
-rw-r--r--shared/server-commands/users/notifications-command.ts85
-rw-r--r--shared/server-commands/users/registrations-command.ts151
-rw-r--r--shared/server-commands/users/subscriptions-command.ts83
-rw-r--r--shared/server-commands/users/two-factor-command.ts92
-rw-r--r--shared/server-commands/users/users-command.ts388
-rw-r--r--shared/server-commands/videos/blacklist-command.ts75
-rw-r--r--shared/server-commands/videos/captions-command.ts67
-rw-r--r--shared/server-commands/videos/change-ownership-command.ts68
-rw-r--r--shared/server-commands/videos/channel-syncs-command.ts55
-rw-r--r--shared/server-commands/videos/channels-command.ts202
-rw-r--r--shared/server-commands/videos/channels.ts29
-rw-r--r--shared/server-commands/videos/comments-command.ts159
-rw-r--r--shared/server-commands/videos/history-command.ts54
-rw-r--r--shared/server-commands/videos/imports-command.ts77
-rw-r--r--shared/server-commands/videos/index.ts21
-rw-r--r--shared/server-commands/videos/live-command.ts337
-rw-r--r--shared/server-commands/videos/live.ts128
-rw-r--r--shared/server-commands/videos/playlists-command.ts281
-rw-r--r--shared/server-commands/videos/services-command.ts29
-rw-r--r--shared/server-commands/videos/storyboard-command.ts19
-rw-r--r--shared/server-commands/videos/streaming-playlists-command.ts119
-rw-r--r--shared/server-commands/videos/video-passwords-command.ts55
-rw-r--r--shared/server-commands/videos/video-stats-command.ts56
-rw-r--r--shared/server-commands/videos/video-studio-command.ts67
-rw-r--r--shared/server-commands/videos/video-token-command.ts34
-rw-r--r--shared/server-commands/videos/videos-command.ts829
-rw-r--r--shared/server-commands/videos/views-command.ts51
76 files changed, 0 insertions, 7761 deletions
diff --git a/shared/server-commands/bulk/bulk-command.ts b/shared/server-commands/bulk/bulk-command.ts
deleted file mode 100644
index b5c5673ce..000000000
--- a/shared/server-commands/bulk/bulk-command.ts
+++ /dev/null
@@ -1,20 +0,0 @@
1import { BulkRemoveCommentsOfBody, HttpStatusCode } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/bulk/index.ts b/shared/server-commands/bulk/index.ts
deleted file mode 100644
index 391597243..000000000
--- a/shared/server-commands/bulk/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './bulk-command'
diff --git a/shared/server-commands/cli/cli-command.ts b/shared/server-commands/cli/cli-command.ts
deleted file mode 100644
index ab9738174..000000000
--- a/shared/server-commands/cli/cli-command.ts
+++ /dev/null
@@ -1,27 +0,0 @@
1import { exec } from 'child_process'
2import { AbstractCommand } from '../shared'
3
4export 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/shared/server-commands/cli/index.ts b/shared/server-commands/cli/index.ts
deleted file mode 100644
index 91b5abfbe..000000000
--- a/shared/server-commands/cli/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './cli-command'
diff --git a/shared/server-commands/custom-pages/custom-pages-command.ts b/shared/server-commands/custom-pages/custom-pages-command.ts
deleted file mode 100644
index cd869a8de..000000000
--- a/shared/server-commands/custom-pages/custom-pages-command.ts
+++ /dev/null
@@ -1,33 +0,0 @@
1import { CustomPage, HttpStatusCode } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/custom-pages/index.ts b/shared/server-commands/custom-pages/index.ts
deleted file mode 100644
index 58aed04f2..000000000
--- a/shared/server-commands/custom-pages/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './custom-pages-command'
diff --git a/shared/server-commands/feeds/feeds-command.ts b/shared/server-commands/feeds/feeds-command.ts
deleted file mode 100644
index 26763b43e..000000000
--- a/shared/server-commands/feeds/feeds-command.ts
+++ /dev/null
@@ -1,78 +0,0 @@
1import { buildUUID } from '@shared/extra-utils'
2import { HttpStatusCode } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5type FeedType = 'videos' | 'video-comments' | 'subscriptions'
6
7export 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/shared/server-commands/feeds/index.ts b/shared/server-commands/feeds/index.ts
deleted file mode 100644
index 662a22b6f..000000000
--- a/shared/server-commands/feeds/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './feeds-command'
diff --git a/shared/server-commands/index.ts b/shared/server-commands/index.ts
deleted file mode 100644
index a4581dbc0..000000000
--- a/shared/server-commands/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
1export * from './bulk'
2export * from './cli'
3export * from './custom-pages'
4export * from './feeds'
5export * from './logs'
6export * from './moderation'
7export * from './overviews'
8export * from './requests'
9export * from './runners'
10export * from './search'
11export * from './server'
12export * from './socket'
13export * from './users'
14export * from './videos'
diff --git a/shared/server-commands/logs/index.ts b/shared/server-commands/logs/index.ts
deleted file mode 100644
index 69452d7f0..000000000
--- a/shared/server-commands/logs/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './logs-command'
diff --git a/shared/server-commands/logs/logs-command.ts b/shared/server-commands/logs/logs-command.ts
deleted file mode 100644
index 1c5de7f59..000000000
--- a/shared/server-commands/logs/logs-command.ts
+++ /dev/null
@@ -1,56 +0,0 @@
1import { ClientLogCreate, HttpStatusCode, ServerLogLevel } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/moderation/abuses-command.ts b/shared/server-commands/moderation/abuses-command.ts
deleted file mode 100644
index 0db32ba46..000000000
--- a/shared/server-commands/moderation/abuses-command.ts
+++ /dev/null
@@ -1,228 +0,0 @@
1import { pick } from '@shared/core-utils'
2import {
3 AbuseFilter,
4 AbuseMessage,
5 AbusePredefinedReasonsString,
6 AbuseState,
7 AbuseUpdate,
8 AbuseVideoIs,
9 AdminAbuse,
10 HttpStatusCode,
11 ResultList,
12 UserAbuse
13} from '@shared/models'
14import { unwrapBody } from '../requests/requests'
15import { AbstractCommand, OverrideCommandOptions } from '../shared'
16
17export 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?: AbuseState
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?: AbuseState
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/shared/server-commands/moderation/index.ts b/shared/server-commands/moderation/index.ts
deleted file mode 100644
index b37643956..000000000
--- a/shared/server-commands/moderation/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './abuses-command'
diff --git a/shared/server-commands/overviews/index.ts b/shared/server-commands/overviews/index.ts
deleted file mode 100644
index e19551907..000000000
--- a/shared/server-commands/overviews/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './overviews-command'
diff --git a/shared/server-commands/overviews/overviews-command.ts b/shared/server-commands/overviews/overviews-command.ts
deleted file mode 100644
index 06b4892d2..000000000
--- a/shared/server-commands/overviews/overviews-command.ts
+++ /dev/null
@@ -1,23 +0,0 @@
1import { HttpStatusCode, VideosOverview } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/requests/index.ts b/shared/server-commands/requests/index.ts
deleted file mode 100644
index 802982301..000000000
--- a/shared/server-commands/requests/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './requests'
diff --git a/shared/server-commands/requests/requests.ts b/shared/server-commands/requests/requests.ts
deleted file mode 100644
index 8227017eb..000000000
--- a/shared/server-commands/requests/requests.ts
+++ /dev/null
@@ -1,259 +0,0 @@
1/* eslint-disable @typescript-eslint/no-floating-promises */
2
3import { decode } from 'querystring'
4import request from 'supertest'
5import { URL } from 'url'
6import { buildAbsoluteFixturePath, pick } from '@shared/core-utils'
7import { HttpStatusCode } from '@shared/models'
8
9export type CommonRequestParams = {
10 url: string
11 path?: string
12 contentType?: string
13 responseType?: string
14 range?: string
15 redirects?: number
16 accept?: string
17 host?: string
18 token?: string
19 headers?: { [ name: string ]: string }
20 type?: string
21 xForwardedFor?: string
22 expectedStatus?: HttpStatusCode
23}
24
25function makeRawRequest (options: {
26 url: string
27 token?: string
28 expectedStatus?: HttpStatusCode
29 range?: string
30 query?: { [ id: string ]: string }
31 method?: 'GET' | 'POST'
32 headers?: { [ name: string ]: string }
33}) {
34 const { host, protocol, pathname } = new URL(options.url)
35
36 const reqOptions = {
37 url: `${protocol}//${host}`,
38 path: pathname,
39 contentType: undefined,
40
41 ...pick(options, [ 'expectedStatus', 'range', 'token', 'query', 'headers' ])
42 }
43
44 if (options.method === 'POST') {
45 return makePostBodyRequest(reqOptions)
46 }
47
48 return makeGetRequest(reqOptions)
49}
50
51function makeGetRequest (options: CommonRequestParams & {
52 query?: any
53 rawQuery?: string
54}) {
55 const req = request(options.url).get(options.path)
56
57 if (options.query) req.query(options.query)
58 if (options.rawQuery) req.query(options.rawQuery)
59
60 return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
61}
62
63function makeHTMLRequest (url: string, path: string) {
64 return makeGetRequest({
65 url,
66 path,
67 accept: 'text/html',
68 expectedStatus: HttpStatusCode.OK_200
69 })
70}
71
72function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) {
73 return makeGetRequest({
74 url,
75 path,
76 expectedStatus,
77 accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8'
78 })
79}
80
81function makeDeleteRequest (options: CommonRequestParams & {
82 query?: any
83 rawQuery?: string
84}) {
85 const req = request(options.url).delete(options.path)
86
87 if (options.query) req.query(options.query)
88 if (options.rawQuery) req.query(options.rawQuery)
89
90 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
91}
92
93function makeUploadRequest (options: CommonRequestParams & {
94 method?: 'POST' | 'PUT'
95
96 fields: { [ fieldName: string ]: any }
97 attaches?: { [ attachName: string ]: any | any[] }
98}) {
99 let req = options.method === 'PUT'
100 ? request(options.url).put(options.path)
101 : request(options.url).post(options.path)
102
103 req = buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
104
105 buildFields(req, options.fields)
106
107 Object.keys(options.attaches || {}).forEach(attach => {
108 const value = options.attaches[attach]
109 if (!value) return
110
111 if (Array.isArray(value)) {
112 req.attach(attach, buildAbsoluteFixturePath(value[0]), value[1])
113 } else {
114 req.attach(attach, buildAbsoluteFixturePath(value))
115 }
116 })
117
118 return req
119}
120
121function makePostBodyRequest (options: CommonRequestParams & {
122 fields?: { [ fieldName: string ]: any }
123}) {
124 const req = request(options.url).post(options.path)
125 .send(options.fields)
126
127 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
128}
129
130function makePutBodyRequest (options: {
131 url: string
132 path: string
133 token?: string
134 fields: { [ fieldName: string ]: any }
135 expectedStatus?: HttpStatusCode
136 headers?: { [name: string]: string }
137}) {
138 const req = request(options.url).put(options.path)
139 .send(options.fields)
140
141 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
142}
143
144function decodeQueryString (path: string) {
145 return decode(path.split('?')[1])
146}
147
148// ---------------------------------------------------------------------------
149
150function unwrapBody <T> (test: request.Test): Promise<T> {
151 return test.then(res => res.body)
152}
153
154function unwrapText (test: request.Test): Promise<string> {
155 return test.then(res => res.text)
156}
157
158function unwrapBodyOrDecodeToJSON <T> (test: request.Test): Promise<T> {
159 return test.then(res => {
160 if (res.body instanceof Buffer) {
161 try {
162 return JSON.parse(new TextDecoder().decode(res.body))
163 } catch (err) {
164 console.error('Cannot decode JSON.', { res, body: res.body instanceof Buffer ? res.body.toString() : res.body })
165 throw err
166 }
167 }
168
169 if (res.text) {
170 try {
171 return JSON.parse(res.text)
172 } catch (err) {
173 console.error('Cannot decode json', { res, text: res.text })
174 throw err
175 }
176 }
177
178 return res.body
179 })
180}
181
182function unwrapTextOrDecode (test: request.Test): Promise<string> {
183 return test.then(res => res.text || new TextDecoder().decode(res.body))
184}
185
186// ---------------------------------------------------------------------------
187
188export {
189 makeHTMLRequest,
190 makeGetRequest,
191 decodeQueryString,
192 makeUploadRequest,
193 makePostBodyRequest,
194 makePutBodyRequest,
195 makeDeleteRequest,
196 makeRawRequest,
197 makeActivityPubGetRequest,
198 unwrapBody,
199 unwrapTextOrDecode,
200 unwrapBodyOrDecodeToJSON,
201 unwrapText
202}
203
204// ---------------------------------------------------------------------------
205
206function buildRequest (req: request.Test, options: CommonRequestParams) {
207 if (options.contentType) req.set('Accept', options.contentType)
208 if (options.responseType) req.responseType(options.responseType)
209 if (options.token) req.set('Authorization', 'Bearer ' + options.token)
210 if (options.range) req.set('Range', options.range)
211 if (options.accept) req.set('Accept', options.accept)
212 if (options.host) req.set('Host', options.host)
213 if (options.redirects) req.redirects(options.redirects)
214 if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor)
215 if (options.type) req.type(options.type)
216
217 Object.keys(options.headers || {}).forEach(name => {
218 req.set(name, options.headers[name])
219 })
220
221 return req.expect(res => {
222 if (options.expectedStatus && res.status !== options.expectedStatus) {
223 const err = new Error(`Expected status ${options.expectedStatus}, got ${res.status}. ` +
224 `\nThe server responded: "${res.body?.error ?? res.text}".\n` +
225 'You may take a closer look at the logs. To see how to do so, check out this page: ' +
226 'https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/development/tests.md#debug-server-logs');
227
228 (err as any).res = res
229
230 throw err
231 }
232
233 return res
234 })
235}
236
237function buildFields (req: request.Test, fields: { [ fieldName: string ]: any }, namespace?: string) {
238 if (!fields) return
239
240 let formKey: string
241
242 for (const key of Object.keys(fields)) {
243 if (namespace) formKey = `${namespace}[${key}]`
244 else formKey = key
245
246 if (fields[key] === undefined) continue
247
248 if (Array.isArray(fields[key]) && fields[key].length === 0) {
249 req.field(key, [])
250 continue
251 }
252
253 if (fields[key] !== null && typeof fields[key] === 'object') {
254 buildFields(req, fields[key], formKey)
255 } else {
256 req.field(formKey, fields[key])
257 }
258 }
259}
diff --git a/shared/server-commands/runners/index.ts b/shared/server-commands/runners/index.ts
deleted file mode 100644
index 9e8e1baf2..000000000
--- a/shared/server-commands/runners/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
1export * from './runner-jobs-command'
2export * from './runner-registration-tokens-command'
3export * from './runners-command'
diff --git a/shared/server-commands/runners/runner-jobs-command.ts b/shared/server-commands/runners/runner-jobs-command.ts
deleted file mode 100644
index 0a0ffb5d3..000000000
--- a/shared/server-commands/runners/runner-jobs-command.ts
+++ /dev/null
@@ -1,294 +0,0 @@
1import { omit, pick, wait } from '@shared/core-utils'
2import {
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 RunnerJobSuccessBody,
20 RunnerJobSuccessPayload,
21 RunnerJobType,
22 RunnerJobUpdateBody,
23 RunnerJobVODPayload
24} from '@shared/models'
25import { unwrapBody } from '../requests'
26import { waitJobs } from '../server'
27import { AbstractCommand, OverrideCommandOptions } from '../shared'
28
29export class RunnerJobsCommand extends AbstractCommand {
30
31 list (options: OverrideCommandOptions & ListRunnerJobsQuery = {}) {
32 const path = '/api/v1/runners/jobs'
33
34 return this.getRequestBody<ResultList<RunnerJobAdmin>>({
35 ...options,
36
37 path,
38 query: pick(options, [ 'start', 'count', 'sort', 'search', 'stateOneOf' ]),
39 implicitToken: true,
40 defaultExpectedStatus: HttpStatusCode.OK_200
41 })
42 }
43
44 cancelByAdmin (options: OverrideCommandOptions & { jobUUID: string }) {
45 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/cancel'
46
47 return this.postBodyRequest({
48 ...options,
49
50 path,
51 implicitToken: true,
52 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
53 })
54 }
55
56 deleteByAdmin (options: OverrideCommandOptions & { jobUUID: string }) {
57 const path = '/api/v1/runners/jobs/' + options.jobUUID
58
59 return this.deleteRequest({
60 ...options,
61
62 path,
63 implicitToken: true,
64 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
65 })
66 }
67
68 // ---------------------------------------------------------------------------
69
70 request (options: OverrideCommandOptions & RequestRunnerJobBody) {
71 const path = '/api/v1/runners/jobs/request'
72
73 return unwrapBody<RequestRunnerJobResult>(this.postBodyRequest({
74 ...options,
75
76 path,
77 fields: pick(options, [ 'runnerToken' ]),
78 implicitToken: false,
79 defaultExpectedStatus: HttpStatusCode.OK_200
80 }))
81 }
82
83 async requestVOD (options: OverrideCommandOptions & RequestRunnerJobBody) {
84 const vodTypes = new Set<RunnerJobType>([ 'vod-audio-merge-transcoding', 'vod-hls-transcoding', 'vod-web-video-transcoding' ])
85
86 const { availableJobs } = await this.request(options)
87
88 return {
89 availableJobs: availableJobs.filter(j => vodTypes.has(j.type))
90 } as RequestRunnerJobResult<RunnerJobVODPayload>
91 }
92
93 async requestLive (options: OverrideCommandOptions & RequestRunnerJobBody) {
94 const vodTypes = new Set<RunnerJobType>([ 'live-rtmp-hls-transcoding' ])
95
96 const { availableJobs } = await this.request(options)
97
98 return {
99 availableJobs: availableJobs.filter(j => vodTypes.has(j.type))
100 } as RequestRunnerJobResult<RunnerJobLiveRTMPHLSTranscodingPayload>
101 }
102
103 // ---------------------------------------------------------------------------
104
105 accept <T extends RunnerJobPayload = RunnerJobPayload> (options: OverrideCommandOptions & AcceptRunnerJobBody & { jobUUID: string }) {
106 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/accept'
107
108 return unwrapBody<AcceptRunnerJobResult<T>>(this.postBodyRequest({
109 ...options,
110
111 path,
112 fields: pick(options, [ 'runnerToken' ]),
113 implicitToken: false,
114 defaultExpectedStatus: HttpStatusCode.OK_200
115 }))
116 }
117
118 abort (options: OverrideCommandOptions & AbortRunnerJobBody & { jobUUID: string }) {
119 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/abort'
120
121 return this.postBodyRequest({
122 ...options,
123
124 path,
125 fields: pick(options, [ 'reason', 'jobToken', 'runnerToken' ]),
126 implicitToken: false,
127 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
128 })
129 }
130
131 update (options: OverrideCommandOptions & RunnerJobUpdateBody & { jobUUID: string }) {
132 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/update'
133
134 const { payload } = options
135 const attaches: { [id: string]: any } = {}
136 let payloadWithoutFiles = payload
137
138 if (isLiveRTMPHLSTranscodingUpdatePayload(payload)) {
139 if (payload.masterPlaylistFile) {
140 attaches[`payload[masterPlaylistFile]`] = payload.masterPlaylistFile
141 }
142
143 attaches[`payload[resolutionPlaylistFile]`] = payload.resolutionPlaylistFile
144 attaches[`payload[videoChunkFile]`] = payload.videoChunkFile
145
146 payloadWithoutFiles = omit(payloadWithoutFiles as any, [ 'masterPlaylistFile', 'resolutionPlaylistFile', 'videoChunkFile' ])
147 }
148
149 return this.postUploadRequest({
150 ...options,
151
152 path,
153 fields: {
154 ...pick(options, [ 'progress', 'jobToken', 'runnerToken' ]),
155
156 payload: payloadWithoutFiles
157 },
158 attaches,
159 implicitToken: false,
160 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
161 })
162 }
163
164 error (options: OverrideCommandOptions & ErrorRunnerJobBody & { jobUUID: string }) {
165 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/error'
166
167 return this.postBodyRequest({
168 ...options,
169
170 path,
171 fields: pick(options, [ 'message', 'jobToken', 'runnerToken' ]),
172 implicitToken: false,
173 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
174 })
175 }
176
177 success (options: OverrideCommandOptions & RunnerJobSuccessBody & { jobUUID: string }) {
178 const { payload } = options
179
180 const path = '/api/v1/runners/jobs/' + options.jobUUID + '/success'
181 const attaches: { [id: string]: any } = {}
182 let payloadWithoutFiles = payload
183
184 if ((isWebVideoOrAudioMergeTranscodingPayloadSuccess(payload) || isHLSTranscodingPayloadSuccess(payload)) && payload.videoFile) {
185 attaches[`payload[videoFile]`] = payload.videoFile
186
187 payloadWithoutFiles = omit(payloadWithoutFiles as any, [ 'videoFile' ])
188 }
189
190 if (isHLSTranscodingPayloadSuccess(payload) && payload.resolutionPlaylistFile) {
191 attaches[`payload[resolutionPlaylistFile]`] = payload.resolutionPlaylistFile
192
193 payloadWithoutFiles = omit(payloadWithoutFiles as any, [ 'resolutionPlaylistFile' ])
194 }
195
196 return this.postUploadRequest({
197 ...options,
198
199 path,
200 attaches,
201 fields: {
202 ...pick(options, [ 'jobToken', 'runnerToken' ]),
203
204 payload: payloadWithoutFiles
205 },
206 implicitToken: false,
207 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
208 })
209 }
210
211 getJobFile (options: OverrideCommandOptions & { url: string, jobToken: string, runnerToken: string }) {
212 const { host, protocol, pathname } = new URL(options.url)
213
214 return this.postBodyRequest({
215 url: `${protocol}//${host}`,
216 path: pathname,
217
218 fields: pick(options, [ 'jobToken', 'runnerToken' ]),
219 implicitToken: false,
220 defaultExpectedStatus: HttpStatusCode.OK_200
221 })
222 }
223
224 // ---------------------------------------------------------------------------
225
226 async autoAccept (options: OverrideCommandOptions & RequestRunnerJobBody & { type?: RunnerJobType }) {
227 const { availableJobs } = await this.request(options)
228
229 const job = options.type
230 ? availableJobs.find(j => j.type === options.type)
231 : availableJobs[0]
232
233 return this.accept({ ...options, jobUUID: job.uuid })
234 }
235
236 async autoProcessWebVideoJob (runnerToken: string, jobUUIDToProcess?: string) {
237 let jobUUID = jobUUIDToProcess
238
239 if (!jobUUID) {
240 const { availableJobs } = await this.request({ runnerToken })
241 jobUUID = availableJobs[0].uuid
242 }
243
244 const { job } = await this.accept({ runnerToken, jobUUID })
245 const jobToken = job.jobToken
246
247 const payload: RunnerJobSuccessPayload = { videoFile: 'video_short.mp4' }
248 await this.success({ runnerToken, jobUUID, jobToken, payload })
249
250 await waitJobs([ this.server ])
251
252 return job
253 }
254
255 async cancelAllJobs (options: { state?: RunnerJobState } = {}) {
256 const { state } = options
257
258 const { data } = await this.list({ count: 100 })
259
260 const allowedStates = new Set<RunnerJobState>([
261 RunnerJobState.PENDING,
262 RunnerJobState.PROCESSING,
263 RunnerJobState.WAITING_FOR_PARENT_JOB
264 ])
265
266 for (const job of data) {
267 if (state && job.state.id !== state) continue
268 else if (allowedStates.has(job.state.id) !== true) continue
269
270 await this.cancelByAdmin({ jobUUID: job.uuid })
271 }
272 }
273
274 async getJob (options: OverrideCommandOptions & { uuid: string }) {
275 const { data } = await this.list({ ...options, count: 100, sort: '-updatedAt' })
276
277 return data.find(j => j.uuid === options.uuid)
278 }
279
280 async requestLiveJob (runnerToken: string) {
281 let availableJobs: RequestRunnerJobResult<RunnerJobLiveRTMPHLSTranscodingPayload>['availableJobs'] = []
282
283 while (availableJobs.length === 0) {
284 const result = await this.requestLive({ runnerToken })
285 availableJobs = result.availableJobs
286
287 if (availableJobs.length === 1) break
288
289 await wait(150)
290 }
291
292 return availableJobs[0]
293 }
294}
diff --git a/shared/server-commands/runners/runner-registration-tokens-command.ts b/shared/server-commands/runners/runner-registration-tokens-command.ts
deleted file mode 100644
index e4f2e3d95..000000000
--- a/shared/server-commands/runners/runner-registration-tokens-command.ts
+++ /dev/null
@@ -1,55 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { HttpStatusCode, ResultList, RunnerRegistrationToken } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export 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/shared/server-commands/runners/runners-command.ts b/shared/server-commands/runners/runners-command.ts
deleted file mode 100644
index b0083e841..000000000
--- a/shared/server-commands/runners/runners-command.ts
+++ /dev/null
@@ -1,78 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { buildUUID } from '@shared/extra-utils'
3import { HttpStatusCode, RegisterRunnerBody, RegisterRunnerResult, ResultList, Runner, UnregisterRunnerBody } from '@shared/models'
4import { unwrapBody } from '../requests'
5import { AbstractCommand, OverrideCommandOptions } from '../shared'
6
7export class RunnersCommand extends AbstractCommand {
8
9 list (options: OverrideCommandOptions & {
10 start?: number
11 count?: number
12 sort?: string
13 } = {}) {
14 const path = '/api/v1/runners'
15
16 return this.getRequestBody<ResultList<Runner>>({
17 ...options,
18
19 path,
20 query: pick(options, [ 'start', 'count', 'sort' ]),
21 implicitToken: true,
22 defaultExpectedStatus: HttpStatusCode.OK_200
23 })
24 }
25
26 register (options: OverrideCommandOptions & RegisterRunnerBody) {
27 const path = '/api/v1/runners/register'
28
29 return unwrapBody<RegisterRunnerResult>(this.postBodyRequest({
30 ...options,
31
32 path,
33 fields: pick(options, [ 'name', 'registrationToken', 'description' ]),
34 implicitToken: true,
35 defaultExpectedStatus: HttpStatusCode.OK_200
36 }))
37 }
38
39 unregister (options: OverrideCommandOptions & UnregisterRunnerBody) {
40 const path = '/api/v1/runners/unregister'
41
42 return this.postBodyRequest({
43 ...options,
44
45 path,
46 fields: pick(options, [ 'runnerToken' ]),
47 implicitToken: false,
48 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
49 })
50 }
51
52 delete (options: OverrideCommandOptions & {
53 id: number
54 }) {
55 const path = '/api/v1/runners/' + options.id
56
57 return this.deleteRequest({
58 ...options,
59
60 path,
61 implicitToken: true,
62 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
63 })
64 }
65
66 // ---------------------------------------------------------------------------
67
68 async autoRegisterRunner () {
69 const { data } = await this.server.runnerRegistrationTokens.list({ sort: 'createdAt' })
70
71 const { runnerToken } = await this.register({
72 name: 'runner ' + buildUUID(),
73 registrationToken: data[0].registrationToken
74 })
75
76 return runnerToken
77 }
78}
diff --git a/shared/server-commands/search/index.ts b/shared/server-commands/search/index.ts
deleted file mode 100644
index 48dbe8ae9..000000000
--- a/shared/server-commands/search/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './search-command'
diff --git a/shared/server-commands/search/search-command.ts b/shared/server-commands/search/search-command.ts
deleted file mode 100644
index a5b498b66..000000000
--- a/shared/server-commands/search/search-command.ts
+++ /dev/null
@@ -1,98 +0,0 @@
1import {
2 HttpStatusCode,
3 ResultList,
4 Video,
5 VideoChannel,
6 VideoChannelsSearchQuery,
7 VideoPlaylist,
8 VideoPlaylistsSearchQuery,
9 VideosSearchQuery
10} from '@shared/models'
11import { AbstractCommand, OverrideCommandOptions } from '../shared'
12
13export 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/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}
diff --git a/shared/server-commands/shared/abstract-command.ts b/shared/server-commands/shared/abstract-command.ts
deleted file mode 100644
index 463acc26b..000000000
--- a/shared/server-commands/shared/abstract-command.ts
+++ /dev/null
@@ -1,223 +0,0 @@
1import { isAbsolute, join } from 'path'
2import { root } from '@shared/core-utils'
3import {
4 makeDeleteRequest,
5 makeGetRequest,
6 makePostBodyRequest,
7 makePutBodyRequest,
8 makeUploadRequest,
9 unwrapBody,
10 unwrapText
11} from '../requests/requests'
12import { PeerTubeServer } from '../server/server'
13
14export interface OverrideCommandOptions {
15 token?: string
16 expectedStatus?: number
17}
18
19interface InternalCommonCommandOptions extends OverrideCommandOptions {
20 // Default to server.url
21 url?: string
22
23 path: string
24 // If we automatically send the server token if the token is not provided
25 implicitToken: boolean
26 defaultExpectedStatus: number
27
28 // Common optional request parameters
29 contentType?: string
30 accept?: string
31 redirects?: number
32 range?: string
33 host?: string
34 headers?: { [ name: string ]: string }
35 requestType?: string
36 responseType?: string
37 xForwardedFor?: string
38}
39
40interface InternalGetCommandOptions extends InternalCommonCommandOptions {
41 query?: { [ id: string ]: any }
42}
43
44interface InternalDeleteCommandOptions extends InternalCommonCommandOptions {
45 query?: { [ id: string ]: any }
46 rawQuery?: string
47}
48
49abstract class AbstractCommand {
50
51 constructor (
52 protected server: PeerTubeServer
53 ) {
54
55 }
56
57 protected getRequestBody <T> (options: InternalGetCommandOptions) {
58 return unwrapBody<T>(this.getRequest(options))
59 }
60
61 protected getRequestText (options: InternalGetCommandOptions) {
62 return unwrapText(this.getRequest(options))
63 }
64
65 protected getRawRequest (options: Omit<InternalGetCommandOptions, 'path'>) {
66 const { url, range } = options
67 const { host, protocol, pathname } = new URL(url)
68
69 return this.getRequest({
70 ...options,
71
72 token: this.buildCommonRequestToken(options),
73 defaultExpectedStatus: this.buildExpectedStatus(options),
74
75 url: `${protocol}//${host}`,
76 path: pathname,
77 range
78 })
79 }
80
81 protected getRequest (options: InternalGetCommandOptions) {
82 const { query } = options
83
84 return makeGetRequest({
85 ...this.buildCommonRequestOptions(options),
86
87 query
88 })
89 }
90
91 protected deleteRequest (options: InternalDeleteCommandOptions) {
92 const { query, rawQuery } = options
93
94 return makeDeleteRequest({
95 ...this.buildCommonRequestOptions(options),
96
97 query,
98 rawQuery
99 })
100 }
101
102 protected putBodyRequest (options: InternalCommonCommandOptions & {
103 fields?: { [ fieldName: string ]: any }
104 headers?: { [name: string]: string }
105 }) {
106 const { fields, headers } = options
107
108 return makePutBodyRequest({
109 ...this.buildCommonRequestOptions(options),
110
111 fields,
112 headers
113 })
114 }
115
116 protected postBodyRequest (options: InternalCommonCommandOptions & {
117 fields?: { [ fieldName: string ]: any }
118 headers?: { [name: string]: string }
119 }) {
120 const { fields, headers } = options
121
122 return makePostBodyRequest({
123 ...this.buildCommonRequestOptions(options),
124
125 fields,
126 headers
127 })
128 }
129
130 protected postUploadRequest (options: InternalCommonCommandOptions & {
131 fields?: { [ fieldName: string ]: any }
132 attaches?: { [ fieldName: string ]: any }
133 }) {
134 const { fields, attaches } = options
135
136 return makeUploadRequest({
137 ...this.buildCommonRequestOptions(options),
138
139 method: 'POST',
140 fields,
141 attaches
142 })
143 }
144
145 protected putUploadRequest (options: InternalCommonCommandOptions & {
146 fields?: { [ fieldName: string ]: any }
147 attaches?: { [ fieldName: string ]: any }
148 }) {
149 const { fields, attaches } = options
150
151 return makeUploadRequest({
152 ...this.buildCommonRequestOptions(options),
153
154 method: 'PUT',
155 fields,
156 attaches
157 })
158 }
159
160 protected updateImageRequest (options: InternalCommonCommandOptions & {
161 fixture: string
162 fieldname: string
163 }) {
164 const filePath = isAbsolute(options.fixture)
165 ? options.fixture
166 : join(root(), 'server', 'tests', 'fixtures', options.fixture)
167
168 return this.postUploadRequest({
169 ...options,
170
171 fields: {},
172 attaches: { [options.fieldname]: filePath }
173 })
174 }
175
176 protected buildCommonRequestOptions (options: InternalCommonCommandOptions) {
177 const { url, path, redirects, contentType, accept, range, host, headers, requestType, xForwardedFor, responseType } = options
178
179 return {
180 url: url ?? this.server.url,
181 path,
182
183 token: this.buildCommonRequestToken(options),
184 expectedStatus: this.buildExpectedStatus(options),
185
186 redirects,
187 contentType,
188 range,
189 host,
190 accept,
191 headers,
192 type: requestType,
193 responseType,
194 xForwardedFor
195 }
196 }
197
198 protected buildCommonRequestToken (options: Pick<InternalCommonCommandOptions, 'token' | 'implicitToken'>) {
199 const { token } = options
200
201 const fallbackToken = options.implicitToken
202 ? this.server.accessToken
203 : undefined
204
205 return token !== undefined ? token : fallbackToken
206 }
207
208 protected buildExpectedStatus (options: Pick<InternalCommonCommandOptions, 'expectedStatus' | 'defaultExpectedStatus'>) {
209 const { expectedStatus, defaultExpectedStatus } = options
210
211 return expectedStatus !== undefined ? expectedStatus : defaultExpectedStatus
212 }
213
214 protected buildVideoPasswordHeader (videoPassword: string) {
215 return videoPassword !== undefined && videoPassword !== null
216 ? { 'x-peertube-video-password': videoPassword }
217 : undefined
218 }
219}
220
221export {
222 AbstractCommand
223}
diff --git a/shared/server-commands/shared/index.ts b/shared/server-commands/shared/index.ts
deleted file mode 100644
index e807ab4f7..000000000
--- a/shared/server-commands/shared/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './abstract-command'
diff --git a/shared/server-commands/socket/index.ts b/shared/server-commands/socket/index.ts
deleted file mode 100644
index 594329b2f..000000000
--- a/shared/server-commands/socket/index.ts
+++ /dev/null
@@ -1 +0,0 @@
1export * from './socket-io-command'
diff --git a/shared/server-commands/socket/socket-io-command.ts b/shared/server-commands/socket/socket-io-command.ts
deleted file mode 100644
index c28a86366..000000000
--- a/shared/server-commands/socket/socket-io-command.ts
+++ /dev/null
@@ -1,24 +0,0 @@
1import { io } from 'socket.io-client'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/users/accounts-command.ts b/shared/server-commands/users/accounts-command.ts
deleted file mode 100644
index 5844b330b..000000000
--- a/shared/server-commands/users/accounts-command.ts
+++ /dev/null
@@ -1,76 +0,0 @@
1import { Account, AccountVideoRate, ActorFollow, HttpStatusCode, ResultList, VideoRateType } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/users/accounts.ts b/shared/server-commands/users/accounts.ts
deleted file mode 100644
index 6387891f4..000000000
--- a/shared/server-commands/users/accounts.ts
+++ /dev/null
@@ -1,15 +0,0 @@
1import { PeerTubeServer } from '../server/server'
2
3async 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
13export {
14 setDefaultAccountAvatar
15}
diff --git a/shared/server-commands/users/blocklist-command.ts b/shared/server-commands/users/blocklist-command.ts
deleted file mode 100644
index 862d8945e..000000000
--- a/shared/server-commands/users/blocklist-command.ts
+++ /dev/null
@@ -1,165 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3import { AccountBlock, BlockStatus, HttpStatusCode, ResultList, ServerBlock } from '@shared/models'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6type ListBlocklistOptions = OverrideCommandOptions & {
7 start: number
8 count: number
9
10 sort?: string // default -createdAt
11
12 search?: string
13}
14
15export 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/shared/server-commands/users/index.ts b/shared/server-commands/users/index.ts
deleted file mode 100644
index 404756539..000000000
--- a/shared/server-commands/users/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
1export * from './accounts-command'
2export * from './accounts'
3export * from './blocklist-command'
4export * from './login'
5export * from './login-command'
6export * from './notifications-command'
7export * from './registrations-command'
8export * from './subscriptions-command'
9export * from './two-factor-command'
10export * from './users-command'
diff --git a/shared/server-commands/users/login-command.ts b/shared/server-commands/users/login-command.ts
deleted file mode 100644
index f2fc6d1c5..000000000
--- a/shared/server-commands/users/login-command.ts
+++ /dev/null
@@ -1,159 +0,0 @@
1import { HttpStatusCode, PeerTubeProblemDocument } from '@shared/models'
2import { unwrapBody } from '../requests'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5type LoginOptions = OverrideCommandOptions & {
6 client?: { id?: string, secret?: string }
7 user?: { username: string, password?: string }
8 otpToken?: string
9}
10
11export 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/shared/server-commands/users/login.ts b/shared/server-commands/users/login.ts
deleted file mode 100644
index f1df027d3..000000000
--- a/shared/server-commands/users/login.ts
+++ /dev/null
@@ -1,19 +0,0 @@
1import { PeerTubeServer } from '../server/server'
2
3function 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
17export {
18 setAccessTokensToServers
19}
diff --git a/shared/server-commands/users/notifications-command.ts b/shared/server-commands/users/notifications-command.ts
deleted file mode 100644
index 6bd815daa..000000000
--- a/shared/server-commands/users/notifications-command.ts
+++ /dev/null
@@ -1,85 +0,0 @@
1import { HttpStatusCode, ResultList, UserNotification, UserNotificationSetting } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/users/registrations-command.ts b/shared/server-commands/users/registrations-command.ts
deleted file mode 100644
index f57f54b34..000000000
--- a/shared/server-commands/users/registrations-command.ts
+++ /dev/null
@@ -1,151 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { HttpStatusCode, ResultList, UserRegistration, UserRegistrationRequest, UserRegistrationUpdateState } from '@shared/models'
3import { unwrapBody } from '../requests'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6export class RegistrationsCommand extends AbstractCommand {
7
8 register (options: OverrideCommandOptions & Partial<UserRegistrationRequest> & Pick<UserRegistrationRequest, 'username'>) {
9 const { password = 'password', email = options.username + '@example.com' } = options
10 const path = '/api/v1/users/register'
11
12 return this.postBodyRequest({
13 ...options,
14
15 path,
16 fields: {
17 ...pick(options, [ 'username', 'displayName', 'channel' ]),
18
19 password,
20 email
21 },
22 implicitToken: false,
23 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
24 })
25 }
26
27 requestRegistration (
28 options: OverrideCommandOptions & Partial<UserRegistrationRequest> & Pick<UserRegistrationRequest, 'username' | 'registrationReason'>
29 ) {
30 const { password = 'password', email = options.username + '@example.com' } = options
31 const path = '/api/v1/users/registrations/request'
32
33 return unwrapBody<UserRegistration>(this.postBodyRequest({
34 ...options,
35
36 path,
37 fields: {
38 ...pick(options, [ 'username', 'displayName', 'channel', 'registrationReason' ]),
39
40 password,
41 email
42 },
43 implicitToken: false,
44 defaultExpectedStatus: HttpStatusCode.OK_200
45 }))
46 }
47
48 // ---------------------------------------------------------------------------
49
50 accept (options: OverrideCommandOptions & { id: number } & UserRegistrationUpdateState) {
51 const { id } = options
52 const path = '/api/v1/users/registrations/' + id + '/accept'
53
54 return this.postBodyRequest({
55 ...options,
56
57 path,
58 fields: pick(options, [ 'moderationResponse', 'preventEmailDelivery' ]),
59 implicitToken: true,
60 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
61 })
62 }
63
64 reject (options: OverrideCommandOptions & { id: number } & UserRegistrationUpdateState) {
65 const { id } = options
66 const path = '/api/v1/users/registrations/' + id + '/reject'
67
68 return this.postBodyRequest({
69 ...options,
70
71 path,
72 fields: pick(options, [ 'moderationResponse', 'preventEmailDelivery' ]),
73 implicitToken: true,
74 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
75 })
76 }
77
78 // ---------------------------------------------------------------------------
79
80 delete (options: OverrideCommandOptions & {
81 id: number
82 }) {
83 const { id } = options
84 const path = '/api/v1/users/registrations/' + id
85
86 return this.deleteRequest({
87 ...options,
88
89 path,
90 implicitToken: true,
91 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
92 })
93 }
94
95 // ---------------------------------------------------------------------------
96
97 list (options: OverrideCommandOptions & {
98 start?: number
99 count?: number
100 sort?: string
101 search?: string
102 } = {}) {
103 const path = '/api/v1/users/registrations'
104
105 return this.getRequestBody<ResultList<UserRegistration>>({
106 ...options,
107
108 path,
109 query: pick(options, [ 'start', 'count', 'sort', 'search' ]),
110 implicitToken: true,
111 defaultExpectedStatus: HttpStatusCode.OK_200
112 })
113 }
114
115 // ---------------------------------------------------------------------------
116
117 askSendVerifyEmail (options: OverrideCommandOptions & {
118 email: string
119 }) {
120 const { email } = options
121 const path = '/api/v1/users/registrations/ask-send-verify-email'
122
123 return this.postBodyRequest({
124 ...options,
125
126 path,
127 fields: { email },
128 implicitToken: false,
129 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
130 })
131 }
132
133 verifyEmail (options: OverrideCommandOptions & {
134 registrationId: number
135 verificationString: string
136 }) {
137 const { registrationId, verificationString } = options
138 const path = '/api/v1/users/registrations/' + registrationId + '/verify-email'
139
140 return this.postBodyRequest({
141 ...options,
142
143 path,
144 fields: {
145 verificationString
146 },
147 implicitToken: false,
148 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
149 })
150 }
151}
diff --git a/shared/server-commands/users/subscriptions-command.ts b/shared/server-commands/users/subscriptions-command.ts
deleted file mode 100644
index b92f037f8..000000000
--- a/shared/server-commands/users/subscriptions-command.ts
+++ /dev/null
@@ -1,83 +0,0 @@
1import { HttpStatusCode, ResultList, VideoChannel } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/users/two-factor-command.ts b/shared/server-commands/users/two-factor-command.ts
deleted file mode 100644
index 5542acfda..000000000
--- a/shared/server-commands/users/two-factor-command.ts
+++ /dev/null
@@ -1,92 +0,0 @@
1import { TOTP } from 'otpauth'
2import { HttpStatusCode, TwoFactorEnableResult } from '@shared/models'
3import { unwrapBody } from '../requests'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6export 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/shared/server-commands/users/users-command.ts b/shared/server-commands/users/users-command.ts
deleted file mode 100644
index 5b39d3488..000000000
--- a/shared/server-commands/users/users-command.ts
+++ /dev/null
@@ -1,388 +0,0 @@
1import { omit, pick } from '@shared/core-utils'
2import {
3 HttpStatusCode,
4 MyUser,
5 ResultList,
6 ScopedToken,
7 User,
8 UserAdminFlag,
9 UserCreateResult,
10 UserRole,
11 UserUpdate,
12 UserUpdateMe,
13 UserVideoQuota,
14 UserVideoRate
15} from '@shared/models'
16import { unwrapBody } from '../requests'
17import { AbstractCommand, OverrideCommandOptions } from '../shared'
18
19export class UsersCommand extends AbstractCommand {
20
21 askResetPassword (options: OverrideCommandOptions & {
22 email: string
23 }) {
24 const { email } = options
25 const path = '/api/v1/users/ask-reset-password'
26
27 return this.postBodyRequest({
28 ...options,
29
30 path,
31 fields: { email },
32 implicitToken: false,
33 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
34 })
35 }
36
37 resetPassword (options: OverrideCommandOptions & {
38 userId: number
39 verificationString: string
40 password: string
41 }) {
42 const { userId, verificationString, password } = options
43 const path = '/api/v1/users/' + userId + '/reset-password'
44
45 return this.postBodyRequest({
46 ...options,
47
48 path,
49 fields: { password, verificationString },
50 implicitToken: false,
51 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
52 })
53 }
54
55 // ---------------------------------------------------------------------------
56
57 askSendVerifyEmail (options: OverrideCommandOptions & {
58 email: string
59 }) {
60 const { email } = options
61 const path = '/api/v1/users/ask-send-verify-email'
62
63 return this.postBodyRequest({
64 ...options,
65
66 path,
67 fields: { email },
68 implicitToken: false,
69 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
70 })
71 }
72
73 verifyEmail (options: OverrideCommandOptions & {
74 userId: number
75 verificationString: string
76 isPendingEmail?: boolean // default false
77 }) {
78 const { userId, verificationString, isPendingEmail = false } = options
79 const path = '/api/v1/users/' + userId + '/verify-email'
80
81 return this.postBodyRequest({
82 ...options,
83
84 path,
85 fields: {
86 verificationString,
87 isPendingEmail
88 },
89 implicitToken: false,
90 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
91 })
92 }
93
94 // ---------------------------------------------------------------------------
95
96 banUser (options: OverrideCommandOptions & {
97 userId: number
98 reason?: string
99 }) {
100 const { userId, reason } = options
101 const path = '/api/v1/users' + '/' + userId + '/block'
102
103 return this.postBodyRequest({
104 ...options,
105
106 path,
107 fields: { reason },
108 implicitToken: true,
109 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
110 })
111 }
112
113 unbanUser (options: OverrideCommandOptions & {
114 userId: number
115 }) {
116 const { userId } = options
117 const path = '/api/v1/users' + '/' + userId + '/unblock'
118
119 return this.postBodyRequest({
120 ...options,
121
122 path,
123 implicitToken: true,
124 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
125 })
126 }
127
128 // ---------------------------------------------------------------------------
129
130 getMyScopedTokens (options: OverrideCommandOptions = {}) {
131 const path = '/api/v1/users/scoped-tokens'
132
133 return this.getRequestBody<ScopedToken>({
134 ...options,
135
136 path,
137 implicitToken: true,
138 defaultExpectedStatus: HttpStatusCode.OK_200
139 })
140 }
141
142 renewMyScopedTokens (options: OverrideCommandOptions = {}) {
143 const path = '/api/v1/users/scoped-tokens'
144
145 return this.postBodyRequest({
146 ...options,
147
148 path,
149 implicitToken: true,
150 defaultExpectedStatus: HttpStatusCode.OK_200
151 })
152 }
153
154 // ---------------------------------------------------------------------------
155
156 create (options: OverrideCommandOptions & {
157 username: string
158 password?: string
159 videoQuota?: number
160 videoQuotaDaily?: number
161 role?: UserRole
162 adminFlags?: UserAdminFlag
163 }) {
164 const {
165 username,
166 adminFlags,
167 password = 'password',
168 videoQuota,
169 videoQuotaDaily,
170 role = UserRole.USER
171 } = options
172
173 const path = '/api/v1/users'
174
175 return unwrapBody<{ user: UserCreateResult }>(this.postBodyRequest({
176 ...options,
177
178 path,
179 fields: {
180 username,
181 password,
182 role,
183 adminFlags,
184 email: username + '@example.com',
185 videoQuota,
186 videoQuotaDaily
187 },
188 implicitToken: true,
189 defaultExpectedStatus: HttpStatusCode.OK_200
190 })).then(res => res.user)
191 }
192
193 async generate (username: string, role?: UserRole) {
194 const password = 'password'
195 const user = await this.create({ username, password, role })
196
197 const token = await this.server.login.getAccessToken({ username, password })
198
199 const me = await this.getMyInfo({ token })
200
201 return {
202 token,
203 userId: user.id,
204 userChannelId: me.videoChannels[0].id,
205 userChannelName: me.videoChannels[0].name,
206 password
207 }
208 }
209
210 async generateUserAndToken (username: string, role?: UserRole) {
211 const password = 'password'
212 await this.create({ username, password, role })
213
214 return this.server.login.getAccessToken({ username, password })
215 }
216
217 // ---------------------------------------------------------------------------
218
219 getMyInfo (options: OverrideCommandOptions = {}) {
220 const path = '/api/v1/users/me'
221
222 return this.getRequestBody<MyUser>({
223 ...options,
224
225 path,
226 implicitToken: true,
227 defaultExpectedStatus: HttpStatusCode.OK_200
228 })
229 }
230
231 getMyQuotaUsed (options: OverrideCommandOptions = {}) {
232 const path = '/api/v1/users/me/video-quota-used'
233
234 return this.getRequestBody<UserVideoQuota>({
235 ...options,
236
237 path,
238 implicitToken: true,
239 defaultExpectedStatus: HttpStatusCode.OK_200
240 })
241 }
242
243 getMyRating (options: OverrideCommandOptions & {
244 videoId: number | string
245 }) {
246 const { videoId } = options
247 const path = '/api/v1/users/me/videos/' + videoId + '/rating'
248
249 return this.getRequestBody<UserVideoRate>({
250 ...options,
251
252 path,
253 implicitToken: true,
254 defaultExpectedStatus: HttpStatusCode.OK_200
255 })
256 }
257
258 deleteMe (options: OverrideCommandOptions = {}) {
259 const path = '/api/v1/users/me'
260
261 return this.deleteRequest({
262 ...options,
263
264 path,
265 implicitToken: true,
266 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
267 })
268 }
269
270 updateMe (options: OverrideCommandOptions & UserUpdateMe) {
271 const path = '/api/v1/users/me'
272
273 const toSend: UserUpdateMe = omit(options, [ 'expectedStatus', 'token' ])
274
275 return this.putBodyRequest({
276 ...options,
277
278 path,
279 fields: toSend,
280 implicitToken: true,
281 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
282 })
283 }
284
285 updateMyAvatar (options: OverrideCommandOptions & {
286 fixture: string
287 }) {
288 const { fixture } = options
289 const path = '/api/v1/users/me/avatar/pick'
290
291 return this.updateImageRequest({
292 ...options,
293
294 path,
295 fixture,
296 fieldname: 'avatarfile',
297
298 implicitToken: true,
299 defaultExpectedStatus: HttpStatusCode.OK_200
300 })
301 }
302
303 // ---------------------------------------------------------------------------
304
305 get (options: OverrideCommandOptions & {
306 userId: number
307 withStats?: boolean // default false
308 }) {
309 const { userId, withStats } = options
310 const path = '/api/v1/users/' + userId
311
312 return this.getRequestBody<User>({
313 ...options,
314
315 path,
316 query: { withStats },
317 implicitToken: true,
318 defaultExpectedStatus: HttpStatusCode.OK_200
319 })
320 }
321
322 list (options: OverrideCommandOptions & {
323 start?: number
324 count?: number
325 sort?: string
326 search?: string
327 blocked?: boolean
328 } = {}) {
329 const path = '/api/v1/users'
330
331 return this.getRequestBody<ResultList<User>>({
332 ...options,
333
334 path,
335 query: pick(options, [ 'start', 'count', 'sort', 'search', 'blocked' ]),
336 implicitToken: true,
337 defaultExpectedStatus: HttpStatusCode.OK_200
338 })
339 }
340
341 remove (options: OverrideCommandOptions & {
342 userId: number
343 }) {
344 const { userId } = options
345 const path = '/api/v1/users/' + userId
346
347 return this.deleteRequest({
348 ...options,
349
350 path,
351 implicitToken: true,
352 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
353 })
354 }
355
356 update (options: OverrideCommandOptions & {
357 userId: number
358 email?: string
359 emailVerified?: boolean
360 videoQuota?: number
361 videoQuotaDaily?: number
362 password?: string
363 adminFlags?: UserAdminFlag
364 pluginAuth?: string
365 role?: UserRole
366 }) {
367 const path = '/api/v1/users/' + options.userId
368
369 const toSend: UserUpdate = {}
370 if (options.password !== undefined && options.password !== null) toSend.password = options.password
371 if (options.email !== undefined && options.email !== null) toSend.email = options.email
372 if (options.emailVerified !== undefined && options.emailVerified !== null) toSend.emailVerified = options.emailVerified
373 if (options.videoQuota !== undefined && options.videoQuota !== null) toSend.videoQuota = options.videoQuota
374 if (options.videoQuotaDaily !== undefined && options.videoQuotaDaily !== null) toSend.videoQuotaDaily = options.videoQuotaDaily
375 if (options.role !== undefined && options.role !== null) toSend.role = options.role
376 if (options.adminFlags !== undefined && options.adminFlags !== null) toSend.adminFlags = options.adminFlags
377 if (options.pluginAuth !== undefined) toSend.pluginAuth = options.pluginAuth
378
379 return this.putBodyRequest({
380 ...options,
381
382 path,
383 fields: toSend,
384 implicitToken: true,
385 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
386 })
387 }
388}
diff --git a/shared/server-commands/videos/blacklist-command.ts b/shared/server-commands/videos/blacklist-command.ts
deleted file mode 100644
index 47e23ebc8..000000000
--- a/shared/server-commands/videos/blacklist-command.ts
+++ /dev/null
@@ -1,75 +0,0 @@
1
2import { HttpStatusCode, ResultList, VideoBlacklist, VideoBlacklistType } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export class BlacklistCommand extends AbstractCommand {
6
7 add (options: OverrideCommandOptions & {
8 videoId: number | string
9 reason?: string
10 unfederate?: boolean
11 }) {
12 const { videoId, reason, unfederate } = options
13 const path = '/api/v1/videos/' + videoId + '/blacklist'
14
15 return this.postBodyRequest({
16 ...options,
17
18 path,
19 fields: { reason, unfederate },
20 implicitToken: true,
21 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
22 })
23 }
24
25 update (options: OverrideCommandOptions & {
26 videoId: number | string
27 reason?: string
28 }) {
29 const { videoId, reason } = options
30 const path = '/api/v1/videos/' + videoId + '/blacklist'
31
32 return this.putBodyRequest({
33 ...options,
34
35 path,
36 fields: { reason },
37 implicitToken: true,
38 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
39 })
40 }
41
42 remove (options: OverrideCommandOptions & {
43 videoId: number | string
44 }) {
45 const { videoId } = options
46 const path = '/api/v1/videos/' + videoId + '/blacklist'
47
48 return this.deleteRequest({
49 ...options,
50
51 path,
52 implicitToken: true,
53 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
54 })
55 }
56
57 list (options: OverrideCommandOptions & {
58 sort?: string
59 type?: VideoBlacklistType
60 } = {}) {
61 const { sort, type } = options
62 const path = '/api/v1/videos/blacklist/'
63
64 const query = { sort, type }
65
66 return this.getRequestBody<ResultList<VideoBlacklist>>({
67 ...options,
68
69 path,
70 query,
71 implicitToken: true,
72 defaultExpectedStatus: HttpStatusCode.OK_200
73 })
74 }
75}
diff --git a/shared/server-commands/videos/captions-command.ts b/shared/server-commands/videos/captions-command.ts
deleted file mode 100644
index a26fcb57d..000000000
--- a/shared/server-commands/videos/captions-command.ts
+++ /dev/null
@@ -1,67 +0,0 @@
1import { buildAbsoluteFixturePath } from '@shared/core-utils'
2import { HttpStatusCode, ResultList, VideoCaption } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export 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/shared/server-commands/videos/change-ownership-command.ts b/shared/server-commands/videos/change-ownership-command.ts
deleted file mode 100644
index ad4c726ef..000000000
--- a/shared/server-commands/videos/change-ownership-command.ts
+++ /dev/null
@@ -1,68 +0,0 @@
1
2import { HttpStatusCode, ResultList, VideoChangeOwnership } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export class ChangeOwnershipCommand extends AbstractCommand {
6
7 create (options: OverrideCommandOptions & {
8 videoId: number | string
9 username: string
10 }) {
11 const { videoId, username } = options
12 const path = '/api/v1/videos/' + videoId + '/give-ownership'
13
14 return this.postBodyRequest({
15 ...options,
16
17 path,
18 fields: { username },
19 implicitToken: true,
20 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
21 })
22 }
23
24 list (options: OverrideCommandOptions = {}) {
25 const path = '/api/v1/videos/ownership'
26
27 return this.getRequestBody<ResultList<VideoChangeOwnership>>({
28 ...options,
29
30 path,
31 query: { sort: '-createdAt' },
32 implicitToken: true,
33 defaultExpectedStatus: HttpStatusCode.OK_200
34 })
35 }
36
37 accept (options: OverrideCommandOptions & {
38 ownershipId: number
39 channelId: number
40 }) {
41 const { ownershipId, channelId } = options
42 const path = '/api/v1/videos/ownership/' + ownershipId + '/accept'
43
44 return this.postBodyRequest({
45 ...options,
46
47 path,
48 fields: { channelId },
49 implicitToken: true,
50 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
51 })
52 }
53
54 refuse (options: OverrideCommandOptions & {
55 ownershipId: number
56 }) {
57 const { ownershipId } = options
58 const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse'
59
60 return this.postBodyRequest({
61 ...options,
62
63 path,
64 implicitToken: true,
65 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
66 })
67 }
68}
diff --git a/shared/server-commands/videos/channel-syncs-command.ts b/shared/server-commands/videos/channel-syncs-command.ts
deleted file mode 100644
index de4a160ec..000000000
--- a/shared/server-commands/videos/channel-syncs-command.ts
+++ /dev/null
@@ -1,55 +0,0 @@
1import { HttpStatusCode, ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@shared/models'
2import { pick } from '@shared/core-utils'
3import { unwrapBody } from '../requests'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6export 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/shared/server-commands/videos/channels-command.ts b/shared/server-commands/videos/channels-command.ts
deleted file mode 100644
index 385d0fe73..000000000
--- a/shared/server-commands/videos/channels-command.ts
+++ /dev/null
@@ -1,202 +0,0 @@
1import { pick } from '@shared/core-utils'
2import {
3 ActorFollow,
4 HttpStatusCode,
5 ResultList,
6 VideoChannel,
7 VideoChannelCreate,
8 VideoChannelCreateResult,
9 VideoChannelUpdate,
10 VideosImportInChannelCreate
11} from '@shared/models'
12import { unwrapBody } from '../requests'
13import { AbstractCommand, OverrideCommandOptions } from '../shared'
14
15export 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/shared/server-commands/videos/channels.ts b/shared/server-commands/videos/channels.ts
deleted file mode 100644
index 3c0d4b723..000000000
--- a/shared/server-commands/videos/channels.ts
+++ /dev/null
@@ -1,29 +0,0 @@
1import { PeerTubeServer } from '../server/server'
2
3function 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
16async 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
26export {
27 setDefaultVideoChannel,
28 setDefaultChannelAvatar
29}
diff --git a/shared/server-commands/videos/comments-command.ts b/shared/server-commands/videos/comments-command.ts
deleted file mode 100644
index 0dab1b66a..000000000
--- a/shared/server-commands/videos/comments-command.ts
+++ /dev/null
@@ -1,159 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { HttpStatusCode, ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models'
3import { unwrapBody } from '../requests'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6export 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/shared/server-commands/videos/history-command.ts b/shared/server-commands/videos/history-command.ts
deleted file mode 100644
index d27afcff2..000000000
--- a/shared/server-commands/videos/history-command.ts
+++ /dev/null
@@ -1,54 +0,0 @@
1import { HttpStatusCode, ResultList, Video } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/videos/imports-command.ts b/shared/server-commands/videos/imports-command.ts
deleted file mode 100644
index e307a79be..000000000
--- a/shared/server-commands/videos/imports-command.ts
+++ /dev/null
@@ -1,77 +0,0 @@
1
2import { HttpStatusCode, ResultList } from '@shared/models'
3import { VideoImport, VideoImportCreate } from '../../models/videos'
4import { unwrapBody } from '../requests'
5import { AbstractCommand, OverrideCommandOptions } from '../shared'
6
7export class ImportsCommand extends AbstractCommand {
8
9 importVideo (options: OverrideCommandOptions & {
10 attributes: (VideoImportCreate | { torrentfile?: string, previewfile?: string, thumbnailfile?: string })
11 }) {
12 const { attributes } = options
13 const path = '/api/v1/videos/imports'
14
15 let attaches: any = {}
16 if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile }
17 if (attributes.thumbnailfile) attaches = { thumbnailfile: attributes.thumbnailfile }
18 if (attributes.previewfile) attaches = { previewfile: attributes.previewfile }
19
20 return unwrapBody<VideoImport>(this.postUploadRequest({
21 ...options,
22
23 path,
24 attaches,
25 fields: options.attributes,
26 implicitToken: true,
27 defaultExpectedStatus: HttpStatusCode.OK_200
28 }))
29 }
30
31 delete (options: OverrideCommandOptions & {
32 importId: number
33 }) {
34 const path = '/api/v1/videos/imports/' + options.importId
35
36 return this.deleteRequest({
37 ...options,
38
39 path,
40 implicitToken: true,
41 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
42 })
43 }
44
45 cancel (options: OverrideCommandOptions & {
46 importId: number
47 }) {
48 const path = '/api/v1/videos/imports/' + options.importId + '/cancel'
49
50 return this.postBodyRequest({
51 ...options,
52
53 path,
54 implicitToken: true,
55 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
56 })
57 }
58
59 getMyVideoImports (options: OverrideCommandOptions & {
60 sort?: string
61 targetUrl?: string
62 videoChannelSyncId?: number
63 search?: string
64 } = {}) {
65 const { sort, targetUrl, videoChannelSyncId, search } = options
66 const path = '/api/v1/users/me/videos/imports'
67
68 return this.getRequestBody<ResultList<VideoImport>>({
69 ...options,
70
71 path,
72 query: { sort, targetUrl, videoChannelSyncId, search },
73 implicitToken: true,
74 defaultExpectedStatus: HttpStatusCode.OK_200
75 })
76 }
77}
diff --git a/shared/server-commands/videos/index.ts b/shared/server-commands/videos/index.ts
deleted file mode 100644
index 106d80af0..000000000
--- a/shared/server-commands/videos/index.ts
+++ /dev/null
@@ -1,21 +0,0 @@
1export * from './blacklist-command'
2export * from './captions-command'
3export * from './change-ownership-command'
4export * from './channels'
5export * from './channels-command'
6export * from './channel-syncs-command'
7export * from './comments-command'
8export * from './history-command'
9export * from './imports-command'
10export * from './live-command'
11export * from './live'
12export * from './playlists-command'
13export * from './services-command'
14export * from './storyboard-command'
15export * from './streaming-playlists-command'
16export * from './comments-command'
17export * from './video-studio-command'
18export * from './video-token-command'
19export * from './views-command'
20export * from './videos-command'
21export * from './video-passwords-command'
diff --git a/shared/server-commands/videos/live-command.ts b/shared/server-commands/videos/live-command.ts
deleted file mode 100644
index 6006d9fe9..000000000
--- a/shared/server-commands/videos/live-command.ts
+++ /dev/null
@@ -1,337 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3import { readdir } from 'fs-extra'
4import { join } from 'path'
5import { omit, wait } from '@shared/core-utils'
6import {
7 HttpStatusCode,
8 LiveVideo,
9 LiveVideoCreate,
10 LiveVideoSession,
11 LiveVideoUpdate,
12 ResultList,
13 VideoCreateResult,
14 VideoDetails,
15 VideoPrivacy,
16 VideoState
17} from '@shared/models'
18import { unwrapBody } from '../requests'
19import { ObjectStorageCommand, PeerTubeServer } from '../server'
20import { AbstractCommand, OverrideCommandOptions } from '../shared'
21import { sendRTMPStream, testFfmpegStreamError } from './live'
22
23export class LiveCommand extends AbstractCommand {
24
25 get (options: OverrideCommandOptions & {
26 videoId: number | string
27 }) {
28 const path = '/api/v1/videos/live'
29
30 return this.getRequestBody<LiveVideo>({
31 ...options,
32
33 path: path + '/' + options.videoId,
34 implicitToken: true,
35 defaultExpectedStatus: HttpStatusCode.OK_200
36 })
37 }
38
39 // ---------------------------------------------------------------------------
40
41 listSessions (options: OverrideCommandOptions & {
42 videoId: number | string
43 }) {
44 const path = `/api/v1/videos/live/${options.videoId}/sessions`
45
46 return this.getRequestBody<ResultList<LiveVideoSession>>({
47 ...options,
48
49 path,
50 implicitToken: true,
51 defaultExpectedStatus: HttpStatusCode.OK_200
52 })
53 }
54
55 async findLatestSession (options: OverrideCommandOptions & {
56 videoId: number | string
57 }) {
58 const { data: sessions } = await this.listSessions(options)
59
60 return sessions[sessions.length - 1]
61 }
62
63 getReplaySession (options: OverrideCommandOptions & {
64 videoId: number | string
65 }) {
66 const path = `/api/v1/videos/${options.videoId}/live-session`
67
68 return this.getRequestBody<LiveVideoSession>({
69 ...options,
70
71 path,
72 implicitToken: true,
73 defaultExpectedStatus: HttpStatusCode.OK_200
74 })
75 }
76
77 // ---------------------------------------------------------------------------
78
79 update (options: OverrideCommandOptions & {
80 videoId: number | string
81 fields: LiveVideoUpdate
82 }) {
83 const { videoId, fields } = options
84 const path = '/api/v1/videos/live'
85
86 return this.putBodyRequest({
87 ...options,
88
89 path: path + '/' + videoId,
90 fields,
91 implicitToken: true,
92 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
93 })
94 }
95
96 async create (options: OverrideCommandOptions & {
97 fields: LiveVideoCreate
98 }) {
99 const { fields } = options
100 const path = '/api/v1/videos/live'
101
102 const attaches: any = {}
103 if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile
104 if (fields.previewfile) attaches.previewfile = fields.previewfile
105
106 const body = await unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
107 ...options,
108
109 path,
110 attaches,
111 fields: omit(fields, [ 'thumbnailfile', 'previewfile' ]),
112 implicitToken: true,
113 defaultExpectedStatus: HttpStatusCode.OK_200
114 }))
115
116 return body.video
117 }
118
119 async quickCreate (options: OverrideCommandOptions & {
120 saveReplay: boolean
121 permanentLive: boolean
122 privacy?: VideoPrivacy
123 videoPasswords?: string[]
124 }) {
125 const { saveReplay, permanentLive, privacy = VideoPrivacy.PUBLIC, videoPasswords } = options
126
127 const replaySettings = privacy === VideoPrivacy.PASSWORD_PROTECTED
128 ? { privacy: VideoPrivacy.PRIVATE }
129 : { privacy }
130
131 const { uuid } = await this.create({
132 ...options,
133
134 fields: {
135 name: 'live',
136 permanentLive,
137 saveReplay,
138 replaySettings,
139 channelId: this.server.store.channel.id,
140 privacy,
141 videoPasswords
142 }
143 })
144
145 const video = await this.server.videos.getWithToken({ id: uuid })
146 const live = await this.get({ videoId: uuid })
147
148 return { video, live }
149 }
150
151 // ---------------------------------------------------------------------------
152
153 async sendRTMPStreamInVideo (options: OverrideCommandOptions & {
154 videoId: number | string
155 fixtureName?: string
156 copyCodecs?: boolean
157 }) {
158 const { videoId, fixtureName, copyCodecs } = options
159 const videoLive = await this.get({ videoId })
160
161 return sendRTMPStream({ rtmpBaseUrl: videoLive.rtmpUrl, streamKey: videoLive.streamKey, fixtureName, copyCodecs })
162 }
163
164 async runAndTestStreamError (options: OverrideCommandOptions & {
165 videoId: number | string
166 shouldHaveError: boolean
167 }) {
168 const command = await this.sendRTMPStreamInVideo(options)
169
170 return testFfmpegStreamError(command, options.shouldHaveError)
171 }
172
173 // ---------------------------------------------------------------------------
174
175 waitUntilPublished (options: OverrideCommandOptions & {
176 videoId: number | string
177 }) {
178 const { videoId } = options
179 return this.waitUntilState({ videoId, state: VideoState.PUBLISHED })
180 }
181
182 waitUntilWaiting (options: OverrideCommandOptions & {
183 videoId: number | string
184 }) {
185 const { videoId } = options
186 return this.waitUntilState({ videoId, state: VideoState.WAITING_FOR_LIVE })
187 }
188
189 waitUntilEnded (options: OverrideCommandOptions & {
190 videoId: number | string
191 }) {
192 const { videoId } = options
193 return this.waitUntilState({ videoId, state: VideoState.LIVE_ENDED })
194 }
195
196 async waitUntilSegmentGeneration (options: OverrideCommandOptions & {
197 server: PeerTubeServer
198 videoUUID: string
199 playlistNumber: number
200 segment: number
201 objectStorage?: ObjectStorageCommand
202 objectStorageBaseUrl?: string
203 }) {
204 const {
205 server,
206 objectStorage,
207 playlistNumber,
208 segment,
209 videoUUID,
210 objectStorageBaseUrl
211 } = options
212
213 const segmentName = `${playlistNumber}-00000${segment}.ts`
214 const baseUrl = objectStorage
215 ? join(objectStorageBaseUrl || objectStorage.getMockPlaylistBaseUrl(), 'hls')
216 : server.url + '/static/streaming-playlists/hls'
217
218 let error = true
219
220 while (error) {
221 try {
222 // Check fragment exists
223 await this.getRawRequest({
224 ...options,
225
226 url: `${baseUrl}/${videoUUID}/${segmentName}`,
227 implicitToken: false,
228 defaultExpectedStatus: HttpStatusCode.OK_200
229 })
230
231 const video = await server.videos.get({ id: videoUUID })
232 const hlsPlaylist = video.streamingPlaylists[0]
233
234 // Check SHA generation
235 const shaBody = await server.streamingPlaylists.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url, withRetry: !!objectStorage })
236 if (!shaBody[segmentName]) {
237 throw new Error('Segment SHA does not exist')
238 }
239
240 // Check fragment is in m3u8 playlist
241 const subPlaylist = await server.streamingPlaylists.get({ url: `${baseUrl}/${video.uuid}/${playlistNumber}.m3u8` })
242 if (!subPlaylist.includes(segmentName)) throw new Error('Fragment does not exist in playlist')
243
244 error = false
245 } catch {
246 error = true
247 await wait(100)
248 }
249 }
250 }
251
252 async waitUntilReplacedByReplay (options: OverrideCommandOptions & {
253 videoId: number | string
254 }) {
255 let video: VideoDetails
256
257 do {
258 video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId })
259
260 await wait(500)
261 } while (video.isLive === true || video.state.id !== VideoState.PUBLISHED)
262 }
263
264 // ---------------------------------------------------------------------------
265
266 getSegmentFile (options: OverrideCommandOptions & {
267 videoUUID: string
268 playlistNumber: number
269 segment: number
270 objectStorage?: ObjectStorageCommand
271 }) {
272 const { playlistNumber, segment, videoUUID, objectStorage } = options
273
274 const segmentName = `${playlistNumber}-00000${segment}.ts`
275 const baseUrl = objectStorage
276 ? objectStorage.getMockPlaylistBaseUrl()
277 : `${this.server.url}/static/streaming-playlists/hls`
278
279 const url = `${baseUrl}/${videoUUID}/${segmentName}`
280
281 return this.getRawRequest({
282 ...options,
283
284 url,
285 implicitToken: false,
286 defaultExpectedStatus: HttpStatusCode.OK_200
287 })
288 }
289
290 getPlaylistFile (options: OverrideCommandOptions & {
291 videoUUID: string
292 playlistName: string
293 objectStorage?: ObjectStorageCommand
294 }) {
295 const { playlistName, videoUUID, objectStorage } = options
296
297 const baseUrl = objectStorage
298 ? objectStorage.getMockPlaylistBaseUrl()
299 : `${this.server.url}/static/streaming-playlists/hls`
300
301 const url = `${baseUrl}/${videoUUID}/${playlistName}`
302
303 return this.getRawRequest({
304 ...options,
305
306 url,
307 implicitToken: false,
308 defaultExpectedStatus: HttpStatusCode.OK_200
309 })
310 }
311
312 // ---------------------------------------------------------------------------
313
314 async countPlaylists (options: OverrideCommandOptions & {
315 videoUUID: string
316 }) {
317 const basePath = this.server.servers.buildDirectory('streaming-playlists')
318 const hlsPath = join(basePath, 'hls', options.videoUUID)
319
320 const files = await readdir(hlsPath)
321
322 return files.filter(f => f.endsWith('.m3u8')).length
323 }
324
325 private async waitUntilState (options: OverrideCommandOptions & {
326 videoId: number | string
327 state: VideoState
328 }) {
329 let video: VideoDetails
330
331 do {
332 video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId })
333
334 await wait(500)
335 } while (video.state.id !== options.state)
336 }
337}
diff --git a/shared/server-commands/videos/live.ts b/shared/server-commands/videos/live.ts
deleted file mode 100644
index cebadb1db..000000000
--- a/shared/server-commands/videos/live.ts
+++ /dev/null
@@ -1,128 +0,0 @@
1import ffmpeg, { FfmpegCommand } from 'fluent-ffmpeg'
2import { truncate } from 'lodash'
3import { buildAbsoluteFixturePath, wait } from '@shared/core-utils'
4import { VideoDetails, VideoInclude, VideoPrivacy } from '@shared/models'
5import { PeerTubeServer } from '../server/server'
6
7function sendRTMPStream (options: {
8 rtmpBaseUrl: string
9 streamKey: string
10 fixtureName?: string // default video_short.mp4
11 copyCodecs?: boolean // default false
12}) {
13 const { rtmpBaseUrl, streamKey, fixtureName = 'video_short.mp4', copyCodecs = false } = options
14
15 const fixture = buildAbsoluteFixturePath(fixtureName)
16
17 const command = ffmpeg(fixture)
18 command.inputOption('-stream_loop -1')
19 command.inputOption('-re')
20
21 if (copyCodecs) {
22 command.outputOption('-c copy')
23 } else {
24 command.outputOption('-c:v libx264')
25 command.outputOption('-g 120')
26 command.outputOption('-x264-params "no-scenecut=1"')
27 command.outputOption('-r 60')
28 }
29
30 command.outputOption('-f flv')
31
32 const rtmpUrl = rtmpBaseUrl + '/' + streamKey
33 command.output(rtmpUrl)
34
35 command.on('error', err => {
36 if (err?.message?.includes('Exiting normally')) return
37
38 if (process.env.DEBUG) console.error(err)
39 })
40
41 if (process.env.DEBUG) {
42 command.on('stderr', data => console.log(data))
43 command.on('stdout', data => console.log(data))
44 }
45
46 command.run()
47
48 return command
49}
50
51function waitFfmpegUntilError (command: FfmpegCommand, successAfterMS = 10000) {
52 return new Promise<void>((res, rej) => {
53 command.on('error', err => {
54 return rej(err)
55 })
56
57 setTimeout(() => {
58 res()
59 }, successAfterMS)
60 })
61}
62
63async function testFfmpegStreamError (command: FfmpegCommand, shouldHaveError: boolean) {
64 let error: Error
65
66 try {
67 await waitFfmpegUntilError(command, 45000)
68 } catch (err) {
69 error = err
70 }
71
72 await stopFfmpeg(command)
73
74 if (shouldHaveError && !error) throw new Error('Ffmpeg did not have an error')
75 if (!shouldHaveError && error) throw error
76}
77
78async function stopFfmpeg (command: FfmpegCommand) {
79 command.kill('SIGINT')
80
81 await wait(500)
82}
83
84async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], videoId: string) {
85 for (const server of servers) {
86 await server.live.waitUntilPublished({ videoId })
87 }
88}
89
90async function waitUntilLiveWaitingOnAllServers (servers: PeerTubeServer[], videoId: string) {
91 for (const server of servers) {
92 await server.live.waitUntilWaiting({ videoId })
93 }
94}
95
96async function waitUntilLiveReplacedByReplayOnAllServers (servers: PeerTubeServer[], videoId: string) {
97 for (const server of servers) {
98 await server.live.waitUntilReplacedByReplay({ videoId })
99 }
100}
101
102async function findExternalSavedVideo (server: PeerTubeServer, liveDetails: VideoDetails) {
103 const include = VideoInclude.BLACKLISTED
104 const privacyOneOf = [ VideoPrivacy.INTERNAL, VideoPrivacy.PRIVATE, VideoPrivacy.PUBLIC, VideoPrivacy.UNLISTED ]
105
106 const { data } = await server.videos.list({ token: server.accessToken, sort: '-publishedAt', include, privacyOneOf })
107
108 const videoNameSuffix = ` - ${new Date(liveDetails.publishedAt).toLocaleString()}`
109 const truncatedVideoName = truncate(liveDetails.name, {
110 length: 120 - videoNameSuffix.length
111 })
112 const toFind = truncatedVideoName + videoNameSuffix
113
114 return data.find(v => v.name === toFind)
115}
116
117export {
118 sendRTMPStream,
119 waitFfmpegUntilError,
120 testFfmpegStreamError,
121 stopFfmpeg,
122
123 waitUntilLivePublishedOnAllServers,
124 waitUntilLiveReplacedByReplayOnAllServers,
125 waitUntilLiveWaitingOnAllServers,
126
127 findExternalSavedVideo
128}
diff --git a/shared/server-commands/videos/playlists-command.ts b/shared/server-commands/videos/playlists-command.ts
deleted file mode 100644
index da3bef7b0..000000000
--- a/shared/server-commands/videos/playlists-command.ts
+++ /dev/null
@@ -1,281 +0,0 @@
1import { omit, pick } from '@shared/core-utils'
2import {
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,
16 VideoPlaylistUpdate
17} from '@shared/models'
18import { unwrapBody } from '../requests'
19import { AbstractCommand, OverrideCommandOptions } from '../shared'
20
21export class PlaylistsCommand extends AbstractCommand {
22
23 list (options: OverrideCommandOptions & {
24 start?: number
25 count?: number
26 sort?: string
27 playlistType?: VideoPlaylistType
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
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
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/shared/server-commands/videos/services-command.ts b/shared/server-commands/videos/services-command.ts
deleted file mode 100644
index 06760df42..000000000
--- a/shared/server-commands/videos/services-command.ts
+++ /dev/null
@@ -1,29 +0,0 @@
1import { HttpStatusCode } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/videos/storyboard-command.ts b/shared/server-commands/videos/storyboard-command.ts
deleted file mode 100644
index 06d90fc12..000000000
--- a/shared/server-commands/videos/storyboard-command.ts
+++ /dev/null
@@ -1,19 +0,0 @@
1import { HttpStatusCode, Storyboard } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/videos/streaming-playlists-command.ts b/shared/server-commands/videos/streaming-playlists-command.ts
deleted file mode 100644
index b988ac4b2..000000000
--- a/shared/server-commands/videos/streaming-playlists-command.ts
+++ /dev/null
@@ -1,119 +0,0 @@
1import { wait } from '@shared/core-utils'
2import { HttpStatusCode } from '@shared/models'
3import { unwrapBody, unwrapBodyOrDecodeToJSON, unwrapTextOrDecode } from '../requests'
4import { AbstractCommand, OverrideCommandOptions } from '../shared'
5
6export 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/shared/server-commands/videos/video-passwords-command.ts b/shared/server-commands/videos/video-passwords-command.ts
deleted file mode 100644
index bf10335b4..000000000
--- a/shared/server-commands/videos/video-passwords-command.ts
+++ /dev/null
@@ -1,55 +0,0 @@
1import { HttpStatusCode, ResultList, VideoPassword } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3export class VideoPasswordsCommand extends AbstractCommand {
4
5 list (options: OverrideCommandOptions & {
6 videoId: number | string
7 start?: number
8 count?: number
9 sort?: string
10 }) {
11 const { start, count, sort, videoId } = options
12 const path = '/api/v1/videos/' + videoId + '/passwords'
13
14 return this.getRequestBody<ResultList<VideoPassword>>({
15 ...options,
16
17 path,
18 query: { start, count, sort },
19 implicitToken: true,
20 defaultExpectedStatus: HttpStatusCode.OK_200
21 })
22 }
23
24 updateAll (options: OverrideCommandOptions & {
25 videoId: number | string
26 passwords: string[]
27 }) {
28 const { videoId, passwords } = options
29 const path = `/api/v1/videos/${videoId}/passwords`
30
31 return this.putBodyRequest({
32 ...options,
33 path,
34 fields: { passwords },
35 implicitToken: true,
36 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
37 })
38 }
39
40 remove (options: OverrideCommandOptions & {
41 id: number
42 videoId: number | string
43 }) {
44 const { id, videoId } = options
45 const path = `/api/v1/videos/${videoId}/passwords/${id}`
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/shared/server-commands/videos/video-stats-command.ts b/shared/server-commands/videos/video-stats-command.ts
deleted file mode 100644
index b9b99bfb5..000000000
--- a/shared/server-commands/videos/video-stats-command.ts
+++ /dev/null
@@ -1,56 +0,0 @@
1import { pick } from '@shared/core-utils'
2import { HttpStatusCode, VideoStatsOverall, VideoStatsRetention, VideoStatsTimeserie, VideoStatsTimeserieMetric } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export class VideoStatsCommand extends AbstractCommand {
6
7 getOverallStats (options: OverrideCommandOptions & {
8 videoId: number | string
9 startDate?: string
10 endDate?: string
11 }) {
12 const path = '/api/v1/videos/' + options.videoId + '/stats/overall'
13
14 return this.getRequestBody<VideoStatsOverall>({
15 ...options,
16 path,
17
18 query: pick(options, [ 'startDate', 'endDate' ]),
19
20 implicitToken: true,
21 defaultExpectedStatus: HttpStatusCode.OK_200
22 })
23 }
24
25 getTimeserieStats (options: OverrideCommandOptions & {
26 videoId: number | string
27 metric: VideoStatsTimeserieMetric
28 startDate?: Date
29 endDate?: Date
30 }) {
31 const path = '/api/v1/videos/' + options.videoId + '/stats/timeseries/' + options.metric
32
33 return this.getRequestBody<VideoStatsTimeserie>({
34 ...options,
35 path,
36
37 query: pick(options, [ 'startDate', 'endDate' ]),
38 implicitToken: true,
39 defaultExpectedStatus: HttpStatusCode.OK_200
40 })
41 }
42
43 getRetentionStats (options: OverrideCommandOptions & {
44 videoId: number | string
45 }) {
46 const path = '/api/v1/videos/' + options.videoId + '/stats/retention'
47
48 return this.getRequestBody<VideoStatsRetention>({
49 ...options,
50 path,
51
52 implicitToken: true,
53 defaultExpectedStatus: HttpStatusCode.OK_200
54 })
55 }
56}
diff --git a/shared/server-commands/videos/video-studio-command.ts b/shared/server-commands/videos/video-studio-command.ts
deleted file mode 100644
index 675cd84b7..000000000
--- a/shared/server-commands/videos/video-studio-command.ts
+++ /dev/null
@@ -1,67 +0,0 @@
1import { HttpStatusCode, VideoStudioTask } from '@shared/models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared'
3
4export 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/shared/server-commands/videos/video-token-command.ts b/shared/server-commands/videos/video-token-command.ts
deleted file mode 100644
index c4ed29a8c..000000000
--- a/shared/server-commands/videos/video-token-command.ts
+++ /dev/null
@@ -1,34 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3import { HttpStatusCode, VideoToken } from '@shared/models'
4import { unwrapBody } from '../requests'
5import { AbstractCommand, OverrideCommandOptions } from '../shared'
6
7export 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/shared/server-commands/videos/videos-command.ts b/shared/server-commands/videos/videos-command.ts
deleted file mode 100644
index 4c3513ed4..000000000
--- a/shared/server-commands/videos/videos-command.ts
+++ /dev/null
@@ -1,829 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3import { expect } from 'chai'
4import { createReadStream, stat } from 'fs-extra'
5import got, { Response as GotResponse } from 'got'
6import validator from 'validator'
7import { buildAbsoluteFixturePath, getAllPrivacies, omit, pick, wait } from '@shared/core-utils'
8import { buildUUID } from '@shared/extra-utils'
9import {
10 HttpStatusCode,
11 ResultList,
12 UserVideoRateType,
13 Video,
14 VideoCreate,
15 VideoCreateResult,
16 VideoDetails,
17 VideoFileMetadata,
18 VideoInclude,
19 VideoPrivacy,
20 VideosCommonQuery,
21 VideoTranscodingCreate
22} from '@shared/models'
23import { VideoSource } from '@shared/models/videos/video-source'
24import { unwrapBody } from '../requests'
25import { waitJobs } from '../server'
26import { AbstractCommand, OverrideCommandOptions } from '../shared'
27
28export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
29 fixture?: string
30 thumbnailfile?: string
31 previewfile?: string
32}
33
34export class VideosCommand extends AbstractCommand {
35
36 getCategories (options: OverrideCommandOptions = {}) {
37 const path = '/api/v1/videos/categories'
38
39 return this.getRequestBody<{ [id: number]: string }>({
40 ...options,
41 path,
42
43 implicitToken: false,
44 defaultExpectedStatus: HttpStatusCode.OK_200
45 })
46 }
47
48 getLicences (options: OverrideCommandOptions = {}) {
49 const path = '/api/v1/videos/licences'
50
51 return this.getRequestBody<{ [id: number]: string }>({
52 ...options,
53 path,
54
55 implicitToken: false,
56 defaultExpectedStatus: HttpStatusCode.OK_200
57 })
58 }
59
60 getLanguages (options: OverrideCommandOptions = {}) {
61 const path = '/api/v1/videos/languages'
62
63 return this.getRequestBody<{ [id: string]: string }>({
64 ...options,
65 path,
66
67 implicitToken: false,
68 defaultExpectedStatus: HttpStatusCode.OK_200
69 })
70 }
71
72 getPrivacies (options: OverrideCommandOptions = {}) {
73 const path = '/api/v1/videos/privacies'
74
75 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
76 ...options,
77 path,
78
79 implicitToken: false,
80 defaultExpectedStatus: HttpStatusCode.OK_200
81 })
82 }
83
84 // ---------------------------------------------------------------------------
85
86 getDescription (options: OverrideCommandOptions & {
87 descriptionPath: string
88 }) {
89 return this.getRequestBody<{ description: string }>({
90 ...options,
91 path: options.descriptionPath,
92
93 implicitToken: false,
94 defaultExpectedStatus: HttpStatusCode.OK_200
95 })
96 }
97
98 getFileMetadata (options: OverrideCommandOptions & {
99 url: string
100 }) {
101 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
102 ...options,
103
104 url: options.url,
105 implicitToken: false,
106 defaultExpectedStatus: HttpStatusCode.OK_200
107 }))
108 }
109
110 // ---------------------------------------------------------------------------
111
112 rate (options: OverrideCommandOptions & {
113 id: number | string
114 rating: UserVideoRateType
115 videoPassword?: string
116 }) {
117 const { id, rating, videoPassword } = options
118 const path = '/api/v1/videos/' + id + '/rate'
119
120 return this.putBodyRequest({
121 ...options,
122
123 path,
124 fields: { rating },
125 headers: this.buildVideoPasswordHeader(videoPassword),
126 implicitToken: true,
127 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
128 })
129 }
130
131 // ---------------------------------------------------------------------------
132
133 get (options: OverrideCommandOptions & {
134 id: number | string
135 }) {
136 const path = '/api/v1/videos/' + options.id
137
138 return this.getRequestBody<VideoDetails>({
139 ...options,
140
141 path,
142 implicitToken: false,
143 defaultExpectedStatus: HttpStatusCode.OK_200
144 })
145 }
146
147 getWithToken (options: OverrideCommandOptions & {
148 id: number | string
149 }) {
150 return this.get({
151 ...options,
152
153 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
154 })
155 }
156
157 getWithPassword (options: OverrideCommandOptions & {
158 id: number | string
159 password?: string
160 }) {
161 const path = '/api/v1/videos/' + options.id
162
163 return this.getRequestBody<VideoDetails>({
164 ...options,
165 headers:{
166 'x-peertube-video-password': options.password
167 },
168 path,
169 implicitToken: false,
170 defaultExpectedStatus: HttpStatusCode.OK_200
171 })
172 }
173
174 getSource (options: OverrideCommandOptions & {
175 id: number | string
176 }) {
177 const path = '/api/v1/videos/' + options.id + '/source'
178
179 return this.getRequestBody<VideoSource>({
180 ...options,
181
182 path,
183 implicitToken: true,
184 defaultExpectedStatus: HttpStatusCode.OK_200
185 })
186 }
187
188 async getId (options: OverrideCommandOptions & {
189 uuid: number | string
190 }) {
191 const { uuid } = options
192
193 if (validator.isUUID('' + uuid) === false) return uuid as number
194
195 const { id } = await this.get({ ...options, id: uuid })
196
197 return id
198 }
199
200 async listFiles (options: OverrideCommandOptions & {
201 id: number | string
202 }) {
203 const video = await this.get(options)
204
205 const files = video.files || []
206 const hlsFiles = video.streamingPlaylists[0]?.files || []
207
208 return files.concat(hlsFiles)
209 }
210
211 // ---------------------------------------------------------------------------
212
213 listMyVideos (options: OverrideCommandOptions & {
214 start?: number
215 count?: number
216 sort?: string
217 search?: string
218 isLive?: boolean
219 channelId?: number
220 } = {}) {
221 const path = '/api/v1/users/me/videos'
222
223 return this.getRequestBody<ResultList<Video>>({
224 ...options,
225
226 path,
227 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
228 implicitToken: true,
229 defaultExpectedStatus: HttpStatusCode.OK_200
230 })
231 }
232
233 listMySubscriptionVideos (options: OverrideCommandOptions & VideosCommonQuery = {}) {
234 const { sort = '-createdAt' } = options
235 const path = '/api/v1/users/me/subscriptions/videos'
236
237 return this.getRequestBody<ResultList<Video>>({
238 ...options,
239
240 path,
241 query: { sort, ...this.buildListQuery(options) },
242 implicitToken: true,
243 defaultExpectedStatus: HttpStatusCode.OK_200
244 })
245 }
246
247 // ---------------------------------------------------------------------------
248
249 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
250 const path = '/api/v1/videos'
251
252 const query = this.buildListQuery(options)
253
254 return this.getRequestBody<ResultList<Video>>({
255 ...options,
256
257 path,
258 query: { sort: 'name', ...query },
259 implicitToken: false,
260 defaultExpectedStatus: HttpStatusCode.OK_200
261 })
262 }
263
264 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
265 return this.list({
266 ...options,
267
268 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
269 })
270 }
271
272 listAllForAdmin (options: OverrideCommandOptions & VideosCommonQuery = {}) {
273 const include = VideoInclude.NOT_PUBLISHED_STATE | VideoInclude.BLACKLISTED | VideoInclude.BLOCKED_OWNER
274 const nsfw = 'both'
275 const privacyOneOf = getAllPrivacies()
276
277 return this.list({
278 ...options,
279
280 include,
281 nsfw,
282 privacyOneOf,
283
284 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
285 })
286 }
287
288 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
289 handle: string
290 }) {
291 const { handle, search } = options
292 const path = '/api/v1/accounts/' + handle + '/videos'
293
294 return this.getRequestBody<ResultList<Video>>({
295 ...options,
296
297 path,
298 query: { search, ...this.buildListQuery(options) },
299 implicitToken: true,
300 defaultExpectedStatus: HttpStatusCode.OK_200
301 })
302 }
303
304 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
305 handle: string
306 }) {
307 const { handle } = options
308 const path = '/api/v1/video-channels/' + handle + '/videos'
309
310 return this.getRequestBody<ResultList<Video>>({
311 ...options,
312
313 path,
314 query: this.buildListQuery(options),
315 implicitToken: true,
316 defaultExpectedStatus: HttpStatusCode.OK_200
317 })
318 }
319
320 // ---------------------------------------------------------------------------
321
322 async find (options: OverrideCommandOptions & {
323 name: string
324 }) {
325 const { data } = await this.list(options)
326
327 return data.find(v => v.name === options.name)
328 }
329
330 // ---------------------------------------------------------------------------
331
332 update (options: OverrideCommandOptions & {
333 id: number | string
334 attributes?: VideoEdit
335 }) {
336 const { id, attributes = {} } = options
337 const path = '/api/v1/videos/' + id
338
339 // Upload request
340 if (attributes.thumbnailfile || attributes.previewfile) {
341 const attaches: any = {}
342 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
343 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
344
345 return this.putUploadRequest({
346 ...options,
347
348 path,
349 fields: options.attributes,
350 attaches: {
351 thumbnailfile: attributes.thumbnailfile,
352 previewfile: attributes.previewfile
353 },
354 implicitToken: true,
355 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
356 })
357 }
358
359 return this.putBodyRequest({
360 ...options,
361
362 path,
363 fields: options.attributes,
364 implicitToken: true,
365 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
366 })
367 }
368
369 remove (options: OverrideCommandOptions & {
370 id: number | string
371 }) {
372 const path = '/api/v1/videos/' + options.id
373
374 return unwrapBody(this.deleteRequest({
375 ...options,
376
377 path,
378 implicitToken: true,
379 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
380 }))
381 }
382
383 async removeAll () {
384 const { data } = await this.list()
385
386 for (const v of data) {
387 await this.remove({ id: v.id })
388 }
389 }
390
391 // ---------------------------------------------------------------------------
392
393 async upload (options: OverrideCommandOptions & {
394 attributes?: VideoEdit
395 mode?: 'legacy' | 'resumable' // default legacy
396 waitTorrentGeneration?: boolean // default true
397 completedExpectedStatus?: HttpStatusCode
398 } = {}) {
399 const { mode = 'legacy', waitTorrentGeneration = true } = options
400 let defaultChannelId = 1
401
402 try {
403 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
404 defaultChannelId = videoChannels[0].id
405 } catch (e) { /* empty */ }
406
407 // Override default attributes
408 const attributes = {
409 name: 'my super video',
410 category: 5,
411 licence: 4,
412 language: 'zh',
413 channelId: defaultChannelId,
414 nsfw: true,
415 waitTranscoding: false,
416 description: 'my super description',
417 support: 'my super support text',
418 tags: [ 'tag' ],
419 privacy: VideoPrivacy.PUBLIC,
420 commentsEnabled: true,
421 downloadEnabled: true,
422 fixture: 'video_short.webm',
423
424 ...options.attributes
425 }
426
427 const created = mode === 'legacy'
428 ? await this.buildLegacyUpload({ ...options, attributes })
429 : await this.buildResumeUpload({ ...options, path: '/api/v1/videos/upload-resumable', attributes })
430
431 // Wait torrent generation
432 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
433 if (expectedStatus === HttpStatusCode.OK_200 && waitTorrentGeneration) {
434 let video: VideoDetails
435
436 do {
437 video = await this.getWithToken({ ...options, id: created.uuid })
438
439 await wait(50)
440 } while (!video.files[0].torrentUrl)
441 }
442
443 return created
444 }
445
446 async buildLegacyUpload (options: OverrideCommandOptions & {
447 attributes: VideoEdit
448 }): Promise<VideoCreateResult> {
449 const path = '/api/v1/videos/upload'
450
451 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
452 ...options,
453
454 path,
455 fields: this.buildUploadFields(options.attributes),
456 attaches: this.buildUploadAttaches(options.attributes),
457 implicitToken: true,
458 defaultExpectedStatus: HttpStatusCode.OK_200
459 })).then(body => body.video || body as any)
460 }
461
462 async buildResumeUpload (options: OverrideCommandOptions & {
463 path: string
464 attributes: { fixture?: string } & { [id: string]: any }
465 completedExpectedStatus?: HttpStatusCode // When the upload is finished
466 }): Promise<VideoCreateResult> {
467 const { path, attributes, expectedStatus = HttpStatusCode.OK_200, completedExpectedStatus } = options
468
469 let size = 0
470 let videoFilePath: string
471 let mimetype = 'video/mp4'
472
473 if (attributes.fixture) {
474 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
475 size = (await stat(videoFilePath)).size
476
477 if (videoFilePath.endsWith('.mkv')) {
478 mimetype = 'video/x-matroska'
479 } else if (videoFilePath.endsWith('.webm')) {
480 mimetype = 'video/webm'
481 }
482 }
483
484 // Do not check status automatically, we'll check it manually
485 const initializeSessionRes = await this.prepareResumableUpload({
486 ...options,
487
488 path,
489 expectedStatus: null,
490 attributes,
491 size,
492 mimetype
493 })
494 const initStatus = initializeSessionRes.status
495
496 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
497 const locationHeader = initializeSessionRes.header['location']
498 expect(locationHeader).to.not.be.undefined
499
500 const pathUploadId = locationHeader.split('?')[1]
501
502 const result = await this.sendResumableChunks({
503 ...options,
504
505 path,
506 pathUploadId,
507 videoFilePath,
508 size,
509 expectedStatus: completedExpectedStatus
510 })
511
512 if (result.statusCode === HttpStatusCode.OK_200) {
513 await this.endResumableUpload({
514 ...options,
515
516 expectedStatus: HttpStatusCode.NO_CONTENT_204,
517 path,
518 pathUploadId
519 })
520 }
521
522 return result.body?.video || result.body as any
523 }
524
525 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
526 ? HttpStatusCode.CREATED_201
527 : expectedStatus
528
529 expect(initStatus).to.equal(expectedInitStatus)
530
531 return initializeSessionRes.body.video || initializeSessionRes.body
532 }
533
534 async prepareResumableUpload (options: OverrideCommandOptions & {
535 path: string
536 attributes: { fixture?: string } & { [id: string]: any }
537 size: number
538 mimetype: string
539
540 originalName?: string
541 lastModified?: number
542 }) {
543 const { path, attributes, originalName, lastModified, size, mimetype } = options
544
545 const attaches = this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ]))
546
547 const uploadOptions = {
548 ...options,
549
550 path,
551 headers: {
552 'X-Upload-Content-Type': mimetype,
553 'X-Upload-Content-Length': size.toString()
554 },
555 fields: {
556 filename: attributes.fixture,
557 originalName,
558 lastModified,
559
560 ...this.buildUploadFields(options.attributes)
561 },
562
563 // Fixture will be sent later
564 attaches: this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ])),
565 implicitToken: true,
566
567 defaultExpectedStatus: null
568 }
569
570 if (Object.keys(attaches).length === 0) return this.postBodyRequest(uploadOptions)
571
572 return this.postUploadRequest(uploadOptions)
573 }
574
575 sendResumableChunks (options: OverrideCommandOptions & {
576 pathUploadId: string
577 path: string
578 videoFilePath: string
579 size: number
580 contentLength?: number
581 contentRangeBuilder?: (start: number, chunk: any) => string
582 digestBuilder?: (chunk: any) => string
583 }) {
584 const {
585 path,
586 pathUploadId,
587 videoFilePath,
588 size,
589 contentLength,
590 contentRangeBuilder,
591 digestBuilder,
592 expectedStatus = HttpStatusCode.OK_200
593 } = options
594
595 let start = 0
596
597 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
598 const url = this.server.url
599
600 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
601 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
602 readable.on('data', async function onData (chunk) {
603 try {
604 readable.pause()
605
606 const byterangeStart = start + chunk.length - 1
607
608 const headers = {
609 'Authorization': 'Bearer ' + token,
610 'Content-Type': 'application/octet-stream',
611 'Content-Range': contentRangeBuilder
612 ? contentRangeBuilder(start, chunk)
613 : `bytes ${start}-${byterangeStart}/${size}`,
614 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
615 }
616
617 if (digestBuilder) {
618 Object.assign(headers, { digest: digestBuilder(chunk) })
619 }
620
621 const res = await got<{ video: VideoCreateResult }>({
622 url,
623 method: 'put',
624 headers,
625 path: path + '?' + pathUploadId,
626 body: chunk,
627 responseType: 'json',
628 throwHttpErrors: false
629 })
630
631 start += chunk.length
632
633 // Last request, check final status
634 if (byterangeStart + 1 === size) {
635 if (res.statusCode === expectedStatus) {
636 return resolve(res)
637 }
638
639 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
640 readable.off('data', onData)
641
642 // eslint-disable-next-line max-len
643 const message = `Incorrect transient behaviour sending intermediary chunks. Status code is ${res.statusCode} instead of ${expectedStatus}`
644 return reject(new Error(message))
645 }
646 }
647
648 readable.resume()
649 } catch (err) {
650 reject(err)
651 }
652 })
653 })
654 }
655
656 endResumableUpload (options: OverrideCommandOptions & {
657 path: string
658 pathUploadId: string
659 }) {
660 return this.deleteRequest({
661 ...options,
662
663 path: options.path,
664 rawQuery: options.pathUploadId,
665 implicitToken: true,
666 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
667 })
668 }
669
670 quickUpload (options: OverrideCommandOptions & {
671 name: string
672 nsfw?: boolean
673 privacy?: VideoPrivacy
674 fixture?: string
675 videoPasswords?: string[]
676 }) {
677 const attributes: VideoEdit = { name: options.name }
678 if (options.nsfw) attributes.nsfw = options.nsfw
679 if (options.privacy) attributes.privacy = options.privacy
680 if (options.fixture) attributes.fixture = options.fixture
681 if (options.videoPasswords) attributes.videoPasswords = options.videoPasswords
682
683 return this.upload({ ...options, attributes })
684 }
685
686 async randomUpload (options: OverrideCommandOptions & {
687 wait?: boolean // default true
688 additionalParams?: VideoEdit & { prefixName?: string }
689 } = {}) {
690 const { wait = true, additionalParams } = options
691 const prefixName = additionalParams?.prefixName || ''
692 const name = prefixName + buildUUID()
693
694 const attributes = { name, ...additionalParams }
695
696 const result = await this.upload({ ...options, attributes })
697
698 if (wait) await waitJobs([ this.server ])
699
700 return { ...result, name }
701 }
702
703 // ---------------------------------------------------------------------------
704
705 replaceSourceFile (options: OverrideCommandOptions & {
706 videoId: number | string
707 fixture: string
708 completedExpectedStatus?: HttpStatusCode
709 }) {
710 return this.buildResumeUpload({
711 ...options,
712
713 path: '/api/v1/videos/' + options.videoId + '/source/replace-resumable',
714 attributes: { fixture: options.fixture }
715 })
716 }
717
718 // ---------------------------------------------------------------------------
719
720 removeHLSPlaylist (options: OverrideCommandOptions & {
721 videoId: number | string
722 }) {
723 const path = '/api/v1/videos/' + options.videoId + '/hls'
724
725 return this.deleteRequest({
726 ...options,
727
728 path,
729 implicitToken: true,
730 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
731 })
732 }
733
734 removeHLSFile (options: OverrideCommandOptions & {
735 videoId: number | string
736 fileId: number
737 }) {
738 const path = '/api/v1/videos/' + options.videoId + '/hls/' + options.fileId
739
740 return this.deleteRequest({
741 ...options,
742
743 path,
744 implicitToken: true,
745 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
746 })
747 }
748
749 removeAllWebVideoFiles (options: OverrideCommandOptions & {
750 videoId: number | string
751 }) {
752 const path = '/api/v1/videos/' + options.videoId + '/web-videos'
753
754 return this.deleteRequest({
755 ...options,
756
757 path,
758 implicitToken: true,
759 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
760 })
761 }
762
763 removeWebVideoFile (options: OverrideCommandOptions & {
764 videoId: number | string
765 fileId: number
766 }) {
767 const path = '/api/v1/videos/' + options.videoId + '/web-videos/' + options.fileId
768
769 return this.deleteRequest({
770 ...options,
771
772 path,
773 implicitToken: true,
774 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
775 })
776 }
777
778 runTranscoding (options: OverrideCommandOptions & VideoTranscodingCreate & {
779 videoId: number | string
780 }) {
781 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
782
783 return this.postBodyRequest({
784 ...options,
785
786 path,
787 fields: pick(options, [ 'transcodingType', 'forceTranscoding' ]),
788 implicitToken: true,
789 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
790 })
791 }
792
793 // ---------------------------------------------------------------------------
794
795 private buildListQuery (options: VideosCommonQuery) {
796 return pick(options, [
797 'start',
798 'count',
799 'sort',
800 'nsfw',
801 'isLive',
802 'categoryOneOf',
803 'licenceOneOf',
804 'languageOneOf',
805 'privacyOneOf',
806 'tagsOneOf',
807 'tagsAllOf',
808 'isLocal',
809 'include',
810 'skipCount'
811 ])
812 }
813
814 private buildUploadFields (attributes: VideoEdit) {
815 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
816 }
817
818 private buildUploadAttaches (attributes: VideoEdit) {
819 const attaches: { [ name: string ]: string } = {}
820
821 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
822 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
823 }
824
825 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)
826
827 return attaches
828 }
829}
diff --git a/shared/server-commands/videos/views-command.ts b/shared/server-commands/videos/views-command.ts
deleted file mode 100644
index bdb8daaa4..000000000
--- a/shared/server-commands/videos/views-command.ts
+++ /dev/null
@@ -1,51 +0,0 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2import { HttpStatusCode, VideoViewEvent } from '@shared/models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared'
4
5export 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}