aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/server-commands/src/videos
diff options
context:
space:
mode:
Diffstat (limited to 'packages/server-commands/src/videos')
-rw-r--r--packages/server-commands/src/videos/blacklist-command.ts74
-rw-r--r--packages/server-commands/src/videos/captions-command.ts67
-rw-r--r--packages/server-commands/src/videos/change-ownership-command.ts67
-rw-r--r--packages/server-commands/src/videos/channel-syncs-command.ts55
-rw-r--r--packages/server-commands/src/videos/channels-command.ts202
-rw-r--r--packages/server-commands/src/videos/channels.ts29
-rw-r--r--packages/server-commands/src/videos/comments-command.ts159
-rw-r--r--packages/server-commands/src/videos/history-command.ts54
-rw-r--r--packages/server-commands/src/videos/imports-command.ts76
-rw-r--r--packages/server-commands/src/videos/index.ts22
-rw-r--r--packages/server-commands/src/videos/live-command.ts339
-rw-r--r--packages/server-commands/src/videos/live.ts129
-rw-r--r--packages/server-commands/src/videos/playlists-command.ts281
-rw-r--r--packages/server-commands/src/videos/services-command.ts29
-rw-r--r--packages/server-commands/src/videos/storyboard-command.ts19
-rw-r--r--packages/server-commands/src/videos/streaming-playlists-command.ts119
-rw-r--r--packages/server-commands/src/videos/video-passwords-command.ts56
-rw-r--r--packages/server-commands/src/videos/video-stats-command.ts62
-rw-r--r--packages/server-commands/src/videos/video-studio-command.ts67
-rw-r--r--packages/server-commands/src/videos/video-token-command.ts34
-rw-r--r--packages/server-commands/src/videos/videos-command.ts831
-rw-r--r--packages/server-commands/src/videos/views-command.ts51
22 files changed, 2822 insertions, 0 deletions
diff --git a/packages/server-commands/src/videos/blacklist-command.ts b/packages/server-commands/src/videos/blacklist-command.ts
new file mode 100644
index 000000000..d41001e26
--- /dev/null
+++ b/packages/server-commands/src/videos/blacklist-command.ts
@@ -0,0 +1,74 @@
1import { HttpStatusCode, ResultList, VideoBlacklist, VideoBlacklistType_Type } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
3
4export class BlacklistCommand extends AbstractCommand {
5
6 add (options: OverrideCommandOptions & {
7 videoId: number | string
8 reason?: string
9 unfederate?: boolean
10 }) {
11 const { videoId, reason, unfederate } = options
12 const path = '/api/v1/videos/' + videoId + '/blacklist'
13
14 return this.postBodyRequest({
15 ...options,
16
17 path,
18 fields: { reason, unfederate },
19 implicitToken: true,
20 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
21 })
22 }
23
24 update (options: OverrideCommandOptions & {
25 videoId: number | string
26 reason?: string
27 }) {
28 const { videoId, reason } = options
29 const path = '/api/v1/videos/' + videoId + '/blacklist'
30
31 return this.putBodyRequest({
32 ...options,
33
34 path,
35 fields: { reason },
36 implicitToken: true,
37 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
38 })
39 }
40
41 remove (options: OverrideCommandOptions & {
42 videoId: number | string
43 }) {
44 const { videoId } = options
45 const path = '/api/v1/videos/' + videoId + '/blacklist'
46
47 return this.deleteRequest({
48 ...options,
49
50 path,
51 implicitToken: true,
52 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
53 })
54 }
55
56 list (options: OverrideCommandOptions & {
57 sort?: string
58 type?: VideoBlacklistType_Type
59 } = {}) {
60 const { sort, type } = options
61 const path = '/api/v1/videos/blacklist/'
62
63 const query = { sort, type }
64
65 return this.getRequestBody<ResultList<VideoBlacklist>>({
66 ...options,
67
68 path,
69 query,
70 implicitToken: true,
71 defaultExpectedStatus: HttpStatusCode.OK_200
72 })
73 }
74}
diff --git a/packages/server-commands/src/videos/captions-command.ts b/packages/server-commands/src/videos/captions-command.ts
new file mode 100644
index 000000000..a8336aa27
--- /dev/null
+++ b/packages/server-commands/src/videos/captions-command.ts
@@ -0,0 +1,67 @@
1import { HttpStatusCode, ResultList, VideoCaption } from '@peertube/peertube-models'
2import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
3import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/change-ownership-command.ts b/packages/server-commands/src/videos/change-ownership-command.ts
new file mode 100644
index 000000000..1dc7c2c0f
--- /dev/null
+++ b/packages/server-commands/src/videos/change-ownership-command.ts
@@ -0,0 +1,67 @@
1import { HttpStatusCode, ResultList, VideoChangeOwnership } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
3
4export class ChangeOwnershipCommand extends AbstractCommand {
5
6 create (options: OverrideCommandOptions & {
7 videoId: number | string
8 username: string
9 }) {
10 const { videoId, username } = options
11 const path = '/api/v1/videos/' + videoId + '/give-ownership'
12
13 return this.postBodyRequest({
14 ...options,
15
16 path,
17 fields: { username },
18 implicitToken: true,
19 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
20 })
21 }
22
23 list (options: OverrideCommandOptions = {}) {
24 const path = '/api/v1/videos/ownership'
25
26 return this.getRequestBody<ResultList<VideoChangeOwnership>>({
27 ...options,
28
29 path,
30 query: { sort: '-createdAt' },
31 implicitToken: true,
32 defaultExpectedStatus: HttpStatusCode.OK_200
33 })
34 }
35
36 accept (options: OverrideCommandOptions & {
37 ownershipId: number
38 channelId: number
39 }) {
40 const { ownershipId, channelId } = options
41 const path = '/api/v1/videos/ownership/' + ownershipId + '/accept'
42
43 return this.postBodyRequest({
44 ...options,
45
46 path,
47 fields: { channelId },
48 implicitToken: true,
49 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
50 })
51 }
52
53 refuse (options: OverrideCommandOptions & {
54 ownershipId: number
55 }) {
56 const { ownershipId } = options
57 const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse'
58
59 return this.postBodyRequest({
60 ...options,
61
62 path,
63 implicitToken: true,
64 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
65 })
66 }
67}
diff --git a/packages/server-commands/src/videos/channel-syncs-command.ts b/packages/server-commands/src/videos/channel-syncs-command.ts
new file mode 100644
index 000000000..718000c8a
--- /dev/null
+++ b/packages/server-commands/src/videos/channel-syncs-command.ts
@@ -0,0 +1,55 @@
1import { HttpStatusCode, ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@peertube/peertube-models'
2import { pick } from '@peertube/peertube-core-utils'
3import { unwrapBody } from '../requests/index.js'
4import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/channels-command.ts b/packages/server-commands/src/videos/channels-command.ts
new file mode 100644
index 000000000..772677d39
--- /dev/null
+++ b/packages/server-commands/src/videos/channels-command.ts
@@ -0,0 +1,202 @@
1import { pick } from '@peertube/peertube-core-utils'
2import {
3 ActorFollow,
4 HttpStatusCode,
5 ResultList,
6 VideoChannel,
7 VideoChannelCreate,
8 VideoChannelCreateResult,
9 VideoChannelUpdate,
10 VideosImportInChannelCreate
11} from '@peertube/peertube-models'
12import { unwrapBody } from '../requests/index.js'
13import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/channels.ts b/packages/server-commands/src/videos/channels.ts
new file mode 100644
index 000000000..e3487d024
--- /dev/null
+++ b/packages/server-commands/src/videos/channels.ts
@@ -0,0 +1,29 @@
1import { PeerTubeServer } from '../server/server.js'
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/packages/server-commands/src/videos/comments-command.ts b/packages/server-commands/src/videos/comments-command.ts
new file mode 100644
index 000000000..4835ae1fb
--- /dev/null
+++ b/packages/server-commands/src/videos/comments-command.ts
@@ -0,0 +1,159 @@
1import { pick } from '@peertube/peertube-core-utils'
2import { HttpStatusCode, ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@peertube/peertube-models'
3import { unwrapBody } from '../requests/index.js'
4import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/history-command.ts b/packages/server-commands/src/videos/history-command.ts
new file mode 100644
index 000000000..fd032504a
--- /dev/null
+++ b/packages/server-commands/src/videos/history-command.ts
@@ -0,0 +1,54 @@
1import { HttpStatusCode, ResultList, Video } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/imports-command.ts b/packages/server-commands/src/videos/imports-command.ts
new file mode 100644
index 000000000..1a1931d64
--- /dev/null
+++ b/packages/server-commands/src/videos/imports-command.ts
@@ -0,0 +1,76 @@
1
2import { HttpStatusCode, ResultList, VideoImport, VideoImportCreate } from '@peertube/peertube-models'
3import { unwrapBody } from '../requests/index.js'
4import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
5
6export class ImportsCommand extends AbstractCommand {
7
8 importVideo (options: OverrideCommandOptions & {
9 attributes: (VideoImportCreate | { torrentfile?: string, previewfile?: string, thumbnailfile?: string })
10 }) {
11 const { attributes } = options
12 const path = '/api/v1/videos/imports'
13
14 let attaches: any = {}
15 if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile }
16 if (attributes.thumbnailfile) attaches = { thumbnailfile: attributes.thumbnailfile }
17 if (attributes.previewfile) attaches = { previewfile: attributes.previewfile }
18
19 return unwrapBody<VideoImport>(this.postUploadRequest({
20 ...options,
21
22 path,
23 attaches,
24 fields: options.attributes,
25 implicitToken: true,
26 defaultExpectedStatus: HttpStatusCode.OK_200
27 }))
28 }
29
30 delete (options: OverrideCommandOptions & {
31 importId: number
32 }) {
33 const path = '/api/v1/videos/imports/' + options.importId
34
35 return this.deleteRequest({
36 ...options,
37
38 path,
39 implicitToken: true,
40 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
41 })
42 }
43
44 cancel (options: OverrideCommandOptions & {
45 importId: number
46 }) {
47 const path = '/api/v1/videos/imports/' + options.importId + '/cancel'
48
49 return this.postBodyRequest({
50 ...options,
51
52 path,
53 implicitToken: true,
54 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
55 })
56 }
57
58 getMyVideoImports (options: OverrideCommandOptions & {
59 sort?: string
60 targetUrl?: string
61 videoChannelSyncId?: number
62 search?: string
63 } = {}) {
64 const { sort, targetUrl, videoChannelSyncId, search } = options
65 const path = '/api/v1/users/me/videos/imports'
66
67 return this.getRequestBody<ResultList<VideoImport>>({
68 ...options,
69
70 path,
71 query: { sort, targetUrl, videoChannelSyncId, search },
72 implicitToken: true,
73 defaultExpectedStatus: HttpStatusCode.OK_200
74 })
75 }
76}
diff --git a/packages/server-commands/src/videos/index.ts b/packages/server-commands/src/videos/index.ts
new file mode 100644
index 000000000..970026d51
--- /dev/null
+++ b/packages/server-commands/src/videos/index.ts
@@ -0,0 +1,22 @@
1export * from './blacklist-command.js'
2export * from './captions-command.js'
3export * from './change-ownership-command.js'
4export * from './channels.js'
5export * from './channels-command.js'
6export * from './channel-syncs-command.js'
7export * from './comments-command.js'
8export * from './history-command.js'
9export * from './imports-command.js'
10export * from './live-command.js'
11export * from './live.js'
12export * from './playlists-command.js'
13export * from './services-command.js'
14export * from './storyboard-command.js'
15export * from './streaming-playlists-command.js'
16export * from './comments-command.js'
17export * from './video-studio-command.js'
18export * from './video-token-command.js'
19export * from './views-command.js'
20export * from './videos-command.js'
21export * from './video-passwords-command.js'
22export * from './video-stats-command.js'
diff --git a/packages/server-commands/src/videos/live-command.ts b/packages/server-commands/src/videos/live-command.ts
new file mode 100644
index 000000000..793b64f40
--- /dev/null
+++ b/packages/server-commands/src/videos/live-command.ts
@@ -0,0 +1,339 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3import { readdir } from 'fs/promises'
4import { join } from 'path'
5import { omit, wait } from '@peertube/peertube-core-utils'
6import {
7 HttpStatusCode,
8 LiveVideo,
9 LiveVideoCreate,
10 LiveVideoSession,
11 LiveVideoUpdate,
12 ResultList,
13 VideoCreateResult,
14 VideoDetails,
15 VideoPrivacy,
16 VideoPrivacyType,
17 VideoState,
18 VideoStateType
19} from '@peertube/peertube-models'
20import { unwrapBody } from '../requests/index.js'
21import { ObjectStorageCommand, PeerTubeServer } from '../server/index.js'
22import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
23import { sendRTMPStream, testFfmpegStreamError } from './live.js'
24
25export class LiveCommand extends AbstractCommand {
26
27 get (options: OverrideCommandOptions & {
28 videoId: number | string
29 }) {
30 const path = '/api/v1/videos/live'
31
32 return this.getRequestBody<LiveVideo>({
33 ...options,
34
35 path: path + '/' + options.videoId,
36 implicitToken: true,
37 defaultExpectedStatus: HttpStatusCode.OK_200
38 })
39 }
40
41 // ---------------------------------------------------------------------------
42
43 listSessions (options: OverrideCommandOptions & {
44 videoId: number | string
45 }) {
46 const path = `/api/v1/videos/live/${options.videoId}/sessions`
47
48 return this.getRequestBody<ResultList<LiveVideoSession>>({
49 ...options,
50
51 path,
52 implicitToken: true,
53 defaultExpectedStatus: HttpStatusCode.OK_200
54 })
55 }
56
57 async findLatestSession (options: OverrideCommandOptions & {
58 videoId: number | string
59 }) {
60 const { data: sessions } = await this.listSessions(options)
61
62 return sessions[sessions.length - 1]
63 }
64
65 getReplaySession (options: OverrideCommandOptions & {
66 videoId: number | string
67 }) {
68 const path = `/api/v1/videos/${options.videoId}/live-session`
69
70 return this.getRequestBody<LiveVideoSession>({
71 ...options,
72
73 path,
74 implicitToken: true,
75 defaultExpectedStatus: HttpStatusCode.OK_200
76 })
77 }
78
79 // ---------------------------------------------------------------------------
80
81 update (options: OverrideCommandOptions & {
82 videoId: number | string
83 fields: LiveVideoUpdate
84 }) {
85 const { videoId, fields } = options
86 const path = '/api/v1/videos/live'
87
88 return this.putBodyRequest({
89 ...options,
90
91 path: path + '/' + videoId,
92 fields,
93 implicitToken: true,
94 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
95 })
96 }
97
98 async create (options: OverrideCommandOptions & {
99 fields: LiveVideoCreate
100 }) {
101 const { fields } = options
102 const path = '/api/v1/videos/live'
103
104 const attaches: any = {}
105 if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile
106 if (fields.previewfile) attaches.previewfile = fields.previewfile
107
108 const body = await unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
109 ...options,
110
111 path,
112 attaches,
113 fields: omit(fields, [ 'thumbnailfile', 'previewfile' ]),
114 implicitToken: true,
115 defaultExpectedStatus: HttpStatusCode.OK_200
116 }))
117
118 return body.video
119 }
120
121 async quickCreate (options: OverrideCommandOptions & {
122 saveReplay: boolean
123 permanentLive: boolean
124 privacy?: VideoPrivacyType
125 videoPasswords?: string[]
126 }) {
127 const { saveReplay, permanentLive, privacy = VideoPrivacy.PUBLIC, videoPasswords } = options
128
129 const replaySettings = privacy === VideoPrivacy.PASSWORD_PROTECTED
130 ? { privacy: VideoPrivacy.PRIVATE }
131 : { privacy }
132
133 const { uuid } = await this.create({
134 ...options,
135
136 fields: {
137 name: 'live',
138 permanentLive,
139 saveReplay,
140 replaySettings,
141 channelId: this.server.store.channel.id,
142 privacy,
143 videoPasswords
144 }
145 })
146
147 const video = await this.server.videos.getWithToken({ id: uuid })
148 const live = await this.get({ videoId: uuid })
149
150 return { video, live }
151 }
152
153 // ---------------------------------------------------------------------------
154
155 async sendRTMPStreamInVideo (options: OverrideCommandOptions & {
156 videoId: number | string
157 fixtureName?: string
158 copyCodecs?: boolean
159 }) {
160 const { videoId, fixtureName, copyCodecs } = options
161 const videoLive = await this.get({ videoId })
162
163 return sendRTMPStream({ rtmpBaseUrl: videoLive.rtmpUrl, streamKey: videoLive.streamKey, fixtureName, copyCodecs })
164 }
165
166 async runAndTestStreamError (options: OverrideCommandOptions & {
167 videoId: number | string
168 shouldHaveError: boolean
169 }) {
170 const command = await this.sendRTMPStreamInVideo(options)
171
172 return testFfmpegStreamError(command, options.shouldHaveError)
173 }
174
175 // ---------------------------------------------------------------------------
176
177 waitUntilPublished (options: OverrideCommandOptions & {
178 videoId: number | string
179 }) {
180 const { videoId } = options
181 return this.waitUntilState({ videoId, state: VideoState.PUBLISHED })
182 }
183
184 waitUntilWaiting (options: OverrideCommandOptions & {
185 videoId: number | string
186 }) {
187 const { videoId } = options
188 return this.waitUntilState({ videoId, state: VideoState.WAITING_FOR_LIVE })
189 }
190
191 waitUntilEnded (options: OverrideCommandOptions & {
192 videoId: number | string
193 }) {
194 const { videoId } = options
195 return this.waitUntilState({ videoId, state: VideoState.LIVE_ENDED })
196 }
197
198 async waitUntilSegmentGeneration (options: OverrideCommandOptions & {
199 server: PeerTubeServer
200 videoUUID: string
201 playlistNumber: number
202 segment: number
203 objectStorage?: ObjectStorageCommand
204 objectStorageBaseUrl?: string
205 }) {
206 const {
207 server,
208 objectStorage,
209 playlistNumber,
210 segment,
211 videoUUID,
212 objectStorageBaseUrl
213 } = options
214
215 const segmentName = `${playlistNumber}-00000${segment}.ts`
216 const baseUrl = objectStorage
217 ? join(objectStorageBaseUrl || objectStorage.getMockPlaylistBaseUrl(), 'hls')
218 : server.url + '/static/streaming-playlists/hls'
219
220 let error = true
221
222 while (error) {
223 try {
224 // Check fragment exists
225 await this.getRawRequest({
226 ...options,
227
228 url: `${baseUrl}/${videoUUID}/${segmentName}`,
229 implicitToken: false,
230 defaultExpectedStatus: HttpStatusCode.OK_200
231 })
232
233 const video = await server.videos.get({ id: videoUUID })
234 const hlsPlaylist = video.streamingPlaylists[0]
235
236 // Check SHA generation
237 const shaBody = await server.streamingPlaylists.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url, withRetry: !!objectStorage })
238 if (!shaBody[segmentName]) {
239 throw new Error('Segment SHA does not exist')
240 }
241
242 // Check fragment is in m3u8 playlist
243 const subPlaylist = await server.streamingPlaylists.get({ url: `${baseUrl}/${video.uuid}/${playlistNumber}.m3u8` })
244 if (!subPlaylist.includes(segmentName)) throw new Error('Fragment does not exist in playlist')
245
246 error = false
247 } catch {
248 error = true
249 await wait(100)
250 }
251 }
252 }
253
254 async waitUntilReplacedByReplay (options: OverrideCommandOptions & {
255 videoId: number | string
256 }) {
257 let video: VideoDetails
258
259 do {
260 video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId })
261
262 await wait(500)
263 } while (video.isLive === true || video.state.id !== VideoState.PUBLISHED)
264 }
265
266 // ---------------------------------------------------------------------------
267
268 getSegmentFile (options: OverrideCommandOptions & {
269 videoUUID: string
270 playlistNumber: number
271 segment: number
272 objectStorage?: ObjectStorageCommand
273 }) {
274 const { playlistNumber, segment, videoUUID, objectStorage } = options
275
276 const segmentName = `${playlistNumber}-00000${segment}.ts`
277 const baseUrl = objectStorage
278 ? objectStorage.getMockPlaylistBaseUrl()
279 : `${this.server.url}/static/streaming-playlists/hls`
280
281 const url = `${baseUrl}/${videoUUID}/${segmentName}`
282
283 return this.getRawRequest({
284 ...options,
285
286 url,
287 implicitToken: false,
288 defaultExpectedStatus: HttpStatusCode.OK_200
289 })
290 }
291
292 getPlaylistFile (options: OverrideCommandOptions & {
293 videoUUID: string
294 playlistName: string
295 objectStorage?: ObjectStorageCommand
296 }) {
297 const { playlistName, videoUUID, objectStorage } = options
298
299 const baseUrl = objectStorage
300 ? objectStorage.getMockPlaylistBaseUrl()
301 : `${this.server.url}/static/streaming-playlists/hls`
302
303 const url = `${baseUrl}/${videoUUID}/${playlistName}`
304
305 return this.getRawRequest({
306 ...options,
307
308 url,
309 implicitToken: false,
310 defaultExpectedStatus: HttpStatusCode.OK_200
311 })
312 }
313
314 // ---------------------------------------------------------------------------
315
316 async countPlaylists (options: OverrideCommandOptions & {
317 videoUUID: string
318 }) {
319 const basePath = this.server.servers.buildDirectory('streaming-playlists')
320 const hlsPath = join(basePath, 'hls', options.videoUUID)
321
322 const files = await readdir(hlsPath)
323
324 return files.filter(f => f.endsWith('.m3u8')).length
325 }
326
327 private async waitUntilState (options: OverrideCommandOptions & {
328 videoId: number | string
329 state: VideoStateType
330 }) {
331 let video: VideoDetails
332
333 do {
334 video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId })
335
336 await wait(500)
337 } while (video.state.id !== options.state)
338 }
339}
diff --git a/packages/server-commands/src/videos/live.ts b/packages/server-commands/src/videos/live.ts
new file mode 100644
index 000000000..05bfa1113
--- /dev/null
+++ b/packages/server-commands/src/videos/live.ts
@@ -0,0 +1,129 @@
1import { wait } from '@peertube/peertube-core-utils'
2import { VideoDetails, VideoInclude, VideoPrivacy } from '@peertube/peertube-models'
3import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
4import ffmpeg, { FfmpegCommand } from 'fluent-ffmpeg'
5import truncate from 'lodash-es/truncate.js'
6import { PeerTubeServer } from '../server/server.js'
7
8function sendRTMPStream (options: {
9 rtmpBaseUrl: string
10 streamKey: string
11 fixtureName?: string // default video_short.mp4
12 copyCodecs?: boolean // default false
13}) {
14 const { rtmpBaseUrl, streamKey, fixtureName = 'video_short.mp4', copyCodecs = false } = options
15
16 const fixture = buildAbsoluteFixturePath(fixtureName)
17
18 const command = ffmpeg(fixture)
19 command.inputOption('-stream_loop -1')
20 command.inputOption('-re')
21
22 if (copyCodecs) {
23 command.outputOption('-c copy')
24 } else {
25 command.outputOption('-c:v libx264')
26 command.outputOption('-g 120')
27 command.outputOption('-x264-params "no-scenecut=1"')
28 command.outputOption('-r 60')
29 }
30
31 command.outputOption('-f flv')
32
33 const rtmpUrl = rtmpBaseUrl + '/' + streamKey
34 command.output(rtmpUrl)
35
36 command.on('error', err => {
37 if (err?.message?.includes('Exiting normally')) return
38
39 if (process.env.DEBUG) console.error(err)
40 })
41
42 if (process.env.DEBUG) {
43 command.on('stderr', data => console.log(data))
44 command.on('stdout', data => console.log(data))
45 }
46
47 command.run()
48
49 return command
50}
51
52function waitFfmpegUntilError (command: FfmpegCommand, successAfterMS = 10000) {
53 return new Promise<void>((res, rej) => {
54 command.on('error', err => {
55 return rej(err)
56 })
57
58 setTimeout(() => {
59 res()
60 }, successAfterMS)
61 })
62}
63
64async function testFfmpegStreamError (command: FfmpegCommand, shouldHaveError: boolean) {
65 let error: Error
66
67 try {
68 await waitFfmpegUntilError(command, 45000)
69 } catch (err) {
70 error = err
71 }
72
73 await stopFfmpeg(command)
74
75 if (shouldHaveError && !error) throw new Error('Ffmpeg did not have an error')
76 if (!shouldHaveError && error) throw error
77}
78
79async function stopFfmpeg (command: FfmpegCommand) {
80 command.kill('SIGINT')
81
82 await wait(500)
83}
84
85async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], videoId: string) {
86 for (const server of servers) {
87 await server.live.waitUntilPublished({ videoId })
88 }
89}
90
91async function waitUntilLiveWaitingOnAllServers (servers: PeerTubeServer[], videoId: string) {
92 for (const server of servers) {
93 await server.live.waitUntilWaiting({ videoId })
94 }
95}
96
97async function waitUntilLiveReplacedByReplayOnAllServers (servers: PeerTubeServer[], videoId: string) {
98 for (const server of servers) {
99 await server.live.waitUntilReplacedByReplay({ videoId })
100 }
101}
102
103async function findExternalSavedVideo (server: PeerTubeServer, liveDetails: VideoDetails) {
104 const include = VideoInclude.BLACKLISTED
105 const privacyOneOf = [ VideoPrivacy.INTERNAL, VideoPrivacy.PRIVATE, VideoPrivacy.PUBLIC, VideoPrivacy.UNLISTED ]
106
107 const { data } = await server.videos.list({ token: server.accessToken, sort: '-publishedAt', include, privacyOneOf })
108
109 const videoNameSuffix = ` - ${new Date(liveDetails.publishedAt).toLocaleString()}`
110 const truncatedVideoName = truncate(liveDetails.name, {
111 length: 120 - videoNameSuffix.length
112 })
113 const toFind = truncatedVideoName + videoNameSuffix
114
115 return data.find(v => v.name === toFind)
116}
117
118export {
119 sendRTMPStream,
120 waitFfmpegUntilError,
121 testFfmpegStreamError,
122 stopFfmpeg,
123
124 waitUntilLivePublishedOnAllServers,
125 waitUntilLiveReplacedByReplayOnAllServers,
126 waitUntilLiveWaitingOnAllServers,
127
128 findExternalSavedVideo
129}
diff --git a/packages/server-commands/src/videos/playlists-command.ts b/packages/server-commands/src/videos/playlists-command.ts
new file mode 100644
index 000000000..2e483f318
--- /dev/null
+++ b/packages/server-commands/src/videos/playlists-command.ts
@@ -0,0 +1,281 @@
1import { omit, pick } from '@peertube/peertube-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_Type,
16 VideoPlaylistUpdate
17} from '@peertube/peertube-models'
18import { unwrapBody } from '../requests/index.js'
19import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
20
21export class PlaylistsCommand extends AbstractCommand {
22
23 list (options: OverrideCommandOptions & {
24 start?: number
25 count?: number
26 sort?: string
27 playlistType?: VideoPlaylistType_Type
28 }) {
29 const path = '/api/v1/video-playlists'
30 const query = pick(options, [ 'start', 'count', 'sort', 'playlistType' ])
31
32 return this.getRequestBody<ResultList<VideoPlaylist>>({
33 ...options,
34
35 path,
36 query,
37 implicitToken: false,
38 defaultExpectedStatus: HttpStatusCode.OK_200
39 })
40 }
41
42 listByChannel (options: OverrideCommandOptions & {
43 handle: string
44 start?: number
45 count?: number
46 sort?: string
47 playlistType?: VideoPlaylistType_Type
48 }) {
49 const path = '/api/v1/video-channels/' + options.handle + '/video-playlists'
50 const query = pick(options, [ 'start', 'count', 'sort', 'playlistType' ])
51
52 return this.getRequestBody<ResultList<VideoPlaylist>>({
53 ...options,
54
55 path,
56 query,
57 implicitToken: false,
58 defaultExpectedStatus: HttpStatusCode.OK_200
59 })
60 }
61
62 listByAccount (options: OverrideCommandOptions & {
63 handle: string
64 start?: number
65 count?: number
66 sort?: string
67 search?: string
68 playlistType?: VideoPlaylistType_Type
69 }) {
70 const path = '/api/v1/accounts/' + options.handle + '/video-playlists'
71 const query = pick(options, [ 'start', 'count', 'sort', 'search', 'playlistType' ])
72
73 return this.getRequestBody<ResultList<VideoPlaylist>>({
74 ...options,
75
76 path,
77 query,
78 implicitToken: false,
79 defaultExpectedStatus: HttpStatusCode.OK_200
80 })
81 }
82
83 get (options: OverrideCommandOptions & {
84 playlistId: number | string
85 }) {
86 const { playlistId } = options
87 const path = '/api/v1/video-playlists/' + playlistId
88
89 return this.getRequestBody<VideoPlaylist>({
90 ...options,
91
92 path,
93 implicitToken: false,
94 defaultExpectedStatus: HttpStatusCode.OK_200
95 })
96 }
97
98 listVideos (options: OverrideCommandOptions & {
99 playlistId: number | string
100 start?: number
101 count?: number
102 query?: { nsfw?: BooleanBothQuery }
103 }) {
104 const path = '/api/v1/video-playlists/' + options.playlistId + '/videos'
105 const query = options.query ?? {}
106
107 return this.getRequestBody<ResultList<VideoPlaylistElement>>({
108 ...options,
109
110 path,
111 query: {
112 ...query,
113 start: options.start,
114 count: options.count
115 },
116 implicitToken: true,
117 defaultExpectedStatus: HttpStatusCode.OK_200
118 })
119 }
120
121 delete (options: OverrideCommandOptions & {
122 playlistId: number | string
123 }) {
124 const path = '/api/v1/video-playlists/' + options.playlistId
125
126 return this.deleteRequest({
127 ...options,
128
129 path,
130 implicitToken: true,
131 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
132 })
133 }
134
135 async create (options: OverrideCommandOptions & {
136 attributes: VideoPlaylistCreate
137 }) {
138 const path = '/api/v1/video-playlists'
139
140 const fields = omit(options.attributes, [ 'thumbnailfile' ])
141
142 const attaches = options.attributes.thumbnailfile
143 ? { thumbnailfile: options.attributes.thumbnailfile }
144 : {}
145
146 const body = await unwrapBody<{ videoPlaylist: VideoPlaylistCreateResult }>(this.postUploadRequest({
147 ...options,
148
149 path,
150 fields,
151 attaches,
152 implicitToken: true,
153 defaultExpectedStatus: HttpStatusCode.OK_200
154 }))
155
156 return body.videoPlaylist
157 }
158
159 update (options: OverrideCommandOptions & {
160 attributes: VideoPlaylistUpdate
161 playlistId: number | string
162 }) {
163 const path = '/api/v1/video-playlists/' + options.playlistId
164
165 const fields = omit(options.attributes, [ 'thumbnailfile' ])
166
167 const attaches = options.attributes.thumbnailfile
168 ? { thumbnailfile: options.attributes.thumbnailfile }
169 : {}
170
171 return this.putUploadRequest({
172 ...options,
173
174 path,
175 fields,
176 attaches,
177 implicitToken: true,
178 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
179 })
180 }
181
182 async addElement (options: OverrideCommandOptions & {
183 playlistId: number | string
184 attributes: VideoPlaylistElementCreate | { videoId: string }
185 }) {
186 const attributes = {
187 ...options.attributes,
188
189 videoId: await this.server.videos.getId({ ...options, uuid: options.attributes.videoId })
190 }
191
192 const path = '/api/v1/video-playlists/' + options.playlistId + '/videos'
193
194 const body = await unwrapBody<{ videoPlaylistElement: VideoPlaylistElementCreateResult }>(this.postBodyRequest({
195 ...options,
196
197 path,
198 fields: attributes,
199 implicitToken: true,
200 defaultExpectedStatus: HttpStatusCode.OK_200
201 }))
202
203 return body.videoPlaylistElement
204 }
205
206 updateElement (options: OverrideCommandOptions & {
207 playlistId: number | string
208 elementId: number | string
209 attributes: VideoPlaylistElementUpdate
210 }) {
211 const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId
212
213 return this.putBodyRequest({
214 ...options,
215
216 path,
217 fields: options.attributes,
218 implicitToken: true,
219 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
220 })
221 }
222
223 removeElement (options: OverrideCommandOptions & {
224 playlistId: number | string
225 elementId: number
226 }) {
227 const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId
228
229 return this.deleteRequest({
230 ...options,
231
232 path,
233 implicitToken: true,
234 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
235 })
236 }
237
238 reorderElements (options: OverrideCommandOptions & {
239 playlistId: number | string
240 attributes: VideoPlaylistReorder
241 }) {
242 const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/reorder'
243
244 return this.postBodyRequest({
245 ...options,
246
247 path,
248 fields: options.attributes,
249 implicitToken: true,
250 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
251 })
252 }
253
254 getPrivacies (options: OverrideCommandOptions = {}) {
255 const path = '/api/v1/video-playlists/privacies'
256
257 return this.getRequestBody<{ [ id: number ]: string }>({
258 ...options,
259
260 path,
261 implicitToken: false,
262 defaultExpectedStatus: HttpStatusCode.OK_200
263 })
264 }
265
266 videosExist (options: OverrideCommandOptions & {
267 videoIds: number[]
268 }) {
269 const { videoIds } = options
270 const path = '/api/v1/users/me/video-playlists/videos-exist'
271
272 return this.getRequestBody<VideoExistInPlaylist>({
273 ...options,
274
275 path,
276 query: { videoIds },
277 implicitToken: true,
278 defaultExpectedStatus: HttpStatusCode.OK_200
279 })
280 }
281}
diff --git a/packages/server-commands/src/videos/services-command.ts b/packages/server-commands/src/videos/services-command.ts
new file mode 100644
index 000000000..ade10cd3a
--- /dev/null
+++ b/packages/server-commands/src/videos/services-command.ts
@@ -0,0 +1,29 @@
1import { HttpStatusCode } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/storyboard-command.ts b/packages/server-commands/src/videos/storyboard-command.ts
new file mode 100644
index 000000000..a692ad612
--- /dev/null
+++ b/packages/server-commands/src/videos/storyboard-command.ts
@@ -0,0 +1,19 @@
1import { HttpStatusCode, Storyboard } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/streaming-playlists-command.ts b/packages/server-commands/src/videos/streaming-playlists-command.ts
new file mode 100644
index 000000000..2406dd023
--- /dev/null
+++ b/packages/server-commands/src/videos/streaming-playlists-command.ts
@@ -0,0 +1,119 @@
1import { wait } from '@peertube/peertube-core-utils'
2import { HttpStatusCode } from '@peertube/peertube-models'
3import { unwrapBody, unwrapBodyOrDecodeToJSON, unwrapTextOrDecode } from '../requests/index.js'
4import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/video-passwords-command.ts b/packages/server-commands/src/videos/video-passwords-command.ts
new file mode 100644
index 000000000..7a56311ca
--- /dev/null
+++ b/packages/server-commands/src/videos/video-passwords-command.ts
@@ -0,0 +1,56 @@
1import { HttpStatusCode, ResultList, VideoPassword } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
3
4export class VideoPasswordsCommand extends AbstractCommand {
5
6 list (options: OverrideCommandOptions & {
7 videoId: number | string
8 start?: number
9 count?: number
10 sort?: string
11 }) {
12 const { start, count, sort, videoId } = options
13 const path = '/api/v1/videos/' + videoId + '/passwords'
14
15 return this.getRequestBody<ResultList<VideoPassword>>({
16 ...options,
17
18 path,
19 query: { start, count, sort },
20 implicitToken: true,
21 defaultExpectedStatus: HttpStatusCode.OK_200
22 })
23 }
24
25 updateAll (options: OverrideCommandOptions & {
26 videoId: number | string
27 passwords: string[]
28 }) {
29 const { videoId, passwords } = options
30 const path = `/api/v1/videos/${videoId}/passwords`
31
32 return this.putBodyRequest({
33 ...options,
34 path,
35 fields: { passwords },
36 implicitToken: true,
37 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
38 })
39 }
40
41 remove (options: OverrideCommandOptions & {
42 id: number
43 videoId: number | string
44 }) {
45 const { id, videoId } = options
46 const path = `/api/v1/videos/${videoId}/passwords/${id}`
47
48 return this.deleteRequest({
49 ...options,
50
51 path,
52 implicitToken: true,
53 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
54 })
55 }
56}
diff --git a/packages/server-commands/src/videos/video-stats-command.ts b/packages/server-commands/src/videos/video-stats-command.ts
new file mode 100644
index 000000000..1b7a9b592
--- /dev/null
+++ b/packages/server-commands/src/videos/video-stats-command.ts
@@ -0,0 +1,62 @@
1import { pick } from '@peertube/peertube-core-utils'
2import {
3 HttpStatusCode,
4 VideoStatsOverall,
5 VideoStatsRetention,
6 VideoStatsTimeserie,
7 VideoStatsTimeserieMetric
8} from '@peertube/peertube-models'
9import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
10
11export class VideoStatsCommand extends AbstractCommand {
12
13 getOverallStats (options: OverrideCommandOptions & {
14 videoId: number | string
15 startDate?: string
16 endDate?: string
17 }) {
18 const path = '/api/v1/videos/' + options.videoId + '/stats/overall'
19
20 return this.getRequestBody<VideoStatsOverall>({
21 ...options,
22 path,
23
24 query: pick(options, [ 'startDate', 'endDate' ]),
25
26 implicitToken: true,
27 defaultExpectedStatus: HttpStatusCode.OK_200
28 })
29 }
30
31 getTimeserieStats (options: OverrideCommandOptions & {
32 videoId: number | string
33 metric: VideoStatsTimeserieMetric
34 startDate?: Date
35 endDate?: Date
36 }) {
37 const path = '/api/v1/videos/' + options.videoId + '/stats/timeseries/' + options.metric
38
39 return this.getRequestBody<VideoStatsTimeserie>({
40 ...options,
41 path,
42
43 query: pick(options, [ 'startDate', 'endDate' ]),
44 implicitToken: true,
45 defaultExpectedStatus: HttpStatusCode.OK_200
46 })
47 }
48
49 getRetentionStats (options: OverrideCommandOptions & {
50 videoId: number | string
51 }) {
52 const path = '/api/v1/videos/' + options.videoId + '/stats/retention'
53
54 return this.getRequestBody<VideoStatsRetention>({
55 ...options,
56 path,
57
58 implicitToken: true,
59 defaultExpectedStatus: HttpStatusCode.OK_200
60 })
61 }
62}
diff --git a/packages/server-commands/src/videos/video-studio-command.ts b/packages/server-commands/src/videos/video-studio-command.ts
new file mode 100644
index 000000000..8c5ff169a
--- /dev/null
+++ b/packages/server-commands/src/videos/video-studio-command.ts
@@ -0,0 +1,67 @@
1import { HttpStatusCode, VideoStudioTask } from '@peertube/peertube-models'
2import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/video-token-command.ts b/packages/server-commands/src/videos/video-token-command.ts
new file mode 100644
index 000000000..5812e484a
--- /dev/null
+++ b/packages/server-commands/src/videos/video-token-command.ts
@@ -0,0 +1,34 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3import { HttpStatusCode, VideoToken } from '@peertube/peertube-models'
4import { unwrapBody } from '../requests/index.js'
5import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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/packages/server-commands/src/videos/videos-command.ts b/packages/server-commands/src/videos/videos-command.ts
new file mode 100644
index 000000000..72dc58a4b
--- /dev/null
+++ b/packages/server-commands/src/videos/videos-command.ts
@@ -0,0 +1,831 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3import { expect } from 'chai'
4import { createReadStream } from 'fs'
5import { stat } from 'fs/promises'
6import got, { Response as GotResponse } from 'got'
7import validator from 'validator'
8import { getAllPrivacies, omit, pick, wait } from '@peertube/peertube-core-utils'
9import {
10 HttpStatusCode,
11 HttpStatusCodeType,
12 ResultList,
13 UserVideoRateType,
14 Video,
15 VideoCreate,
16 VideoCreateResult,
17 VideoDetails,
18 VideoFileMetadata,
19 VideoInclude,
20 VideoPrivacy,
21 VideoPrivacyType,
22 VideosCommonQuery,
23 VideoSource,
24 VideoTranscodingCreate
25} from '@peertube/peertube-models'
26import { buildAbsoluteFixturePath, buildUUID } from '@peertube/peertube-node-utils'
27import { unwrapBody } from '../requests/index.js'
28import { waitJobs } from '../server/jobs.js'
29import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
30
31export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
32 fixture?: string
33 thumbnailfile?: string
34 previewfile?: string
35}
36
37export class VideosCommand extends AbstractCommand {
38
39 getCategories (options: OverrideCommandOptions = {}) {
40 const path = '/api/v1/videos/categories'
41
42 return this.getRequestBody<{ [id: number]: string }>({
43 ...options,
44 path,
45
46 implicitToken: false,
47 defaultExpectedStatus: HttpStatusCode.OK_200
48 })
49 }
50
51 getLicences (options: OverrideCommandOptions = {}) {
52 const path = '/api/v1/videos/licences'
53
54 return this.getRequestBody<{ [id: number]: string }>({
55 ...options,
56 path,
57
58 implicitToken: false,
59 defaultExpectedStatus: HttpStatusCode.OK_200
60 })
61 }
62
63 getLanguages (options: OverrideCommandOptions = {}) {
64 const path = '/api/v1/videos/languages'
65
66 return this.getRequestBody<{ [id: string]: string }>({
67 ...options,
68 path,
69
70 implicitToken: false,
71 defaultExpectedStatus: HttpStatusCode.OK_200
72 })
73 }
74
75 getPrivacies (options: OverrideCommandOptions = {}) {
76 const path = '/api/v1/videos/privacies'
77
78 return this.getRequestBody<{ [id in VideoPrivacyType]: string }>({
79 ...options,
80 path,
81
82 implicitToken: false,
83 defaultExpectedStatus: HttpStatusCode.OK_200
84 })
85 }
86
87 // ---------------------------------------------------------------------------
88
89 getDescription (options: OverrideCommandOptions & {
90 descriptionPath: string
91 }) {
92 return this.getRequestBody<{ description: string }>({
93 ...options,
94 path: options.descriptionPath,
95
96 implicitToken: false,
97 defaultExpectedStatus: HttpStatusCode.OK_200
98 })
99 }
100
101 getFileMetadata (options: OverrideCommandOptions & {
102 url: string
103 }) {
104 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
105 ...options,
106
107 url: options.url,
108 implicitToken: false,
109 defaultExpectedStatus: HttpStatusCode.OK_200
110 }))
111 }
112
113 // ---------------------------------------------------------------------------
114
115 rate (options: OverrideCommandOptions & {
116 id: number | string
117 rating: UserVideoRateType
118 videoPassword?: string
119 }) {
120 const { id, rating, videoPassword } = options
121 const path = '/api/v1/videos/' + id + '/rate'
122
123 return this.putBodyRequest({
124 ...options,
125
126 path,
127 fields: { rating },
128 headers: this.buildVideoPasswordHeader(videoPassword),
129 implicitToken: true,
130 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
131 })
132 }
133
134 // ---------------------------------------------------------------------------
135
136 get (options: OverrideCommandOptions & {
137 id: number | string
138 }) {
139 const path = '/api/v1/videos/' + options.id
140
141 return this.getRequestBody<VideoDetails>({
142 ...options,
143
144 path,
145 implicitToken: false,
146 defaultExpectedStatus: HttpStatusCode.OK_200
147 })
148 }
149
150 getWithToken (options: OverrideCommandOptions & {
151 id: number | string
152 }) {
153 return this.get({
154 ...options,
155
156 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
157 })
158 }
159
160 getWithPassword (options: OverrideCommandOptions & {
161 id: number | string
162 password?: string
163 }) {
164 const path = '/api/v1/videos/' + options.id
165
166 return this.getRequestBody<VideoDetails>({
167 ...options,
168 headers:{
169 'x-peertube-video-password': options.password
170 },
171 path,
172 implicitToken: false,
173 defaultExpectedStatus: HttpStatusCode.OK_200
174 })
175 }
176
177 getSource (options: OverrideCommandOptions & {
178 id: number | string
179 }) {
180 const path = '/api/v1/videos/' + options.id + '/source'
181
182 return this.getRequestBody<VideoSource>({
183 ...options,
184
185 path,
186 implicitToken: true,
187 defaultExpectedStatus: HttpStatusCode.OK_200
188 })
189 }
190
191 async getId (options: OverrideCommandOptions & {
192 uuid: number | string
193 }) {
194 const { uuid } = options
195
196 if (validator.default.isUUID('' + uuid) === false) return uuid as number
197
198 const { id } = await this.get({ ...options, id: uuid })
199
200 return id
201 }
202
203 async listFiles (options: OverrideCommandOptions & {
204 id: number | string
205 }) {
206 const video = await this.get(options)
207
208 const files = video.files || []
209 const hlsFiles = video.streamingPlaylists[0]?.files || []
210
211 return files.concat(hlsFiles)
212 }
213
214 // ---------------------------------------------------------------------------
215
216 listMyVideos (options: OverrideCommandOptions & {
217 start?: number
218 count?: number
219 sort?: string
220 search?: string
221 isLive?: boolean
222 channelId?: number
223 } = {}) {
224 const path = '/api/v1/users/me/videos'
225
226 return this.getRequestBody<ResultList<Video>>({
227 ...options,
228
229 path,
230 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
231 implicitToken: true,
232 defaultExpectedStatus: HttpStatusCode.OK_200
233 })
234 }
235
236 listMySubscriptionVideos (options: OverrideCommandOptions & VideosCommonQuery = {}) {
237 const { sort = '-createdAt' } = options
238 const path = '/api/v1/users/me/subscriptions/videos'
239
240 return this.getRequestBody<ResultList<Video>>({
241 ...options,
242
243 path,
244 query: { sort, ...this.buildListQuery(options) },
245 implicitToken: true,
246 defaultExpectedStatus: HttpStatusCode.OK_200
247 })
248 }
249
250 // ---------------------------------------------------------------------------
251
252 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
253 const path = '/api/v1/videos'
254
255 const query = this.buildListQuery(options)
256
257 return this.getRequestBody<ResultList<Video>>({
258 ...options,
259
260 path,
261 query: { sort: 'name', ...query },
262 implicitToken: false,
263 defaultExpectedStatus: HttpStatusCode.OK_200
264 })
265 }
266
267 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
268 return this.list({
269 ...options,
270
271 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
272 })
273 }
274
275 listAllForAdmin (options: OverrideCommandOptions & VideosCommonQuery = {}) {
276 const include = VideoInclude.NOT_PUBLISHED_STATE | VideoInclude.BLACKLISTED | VideoInclude.BLOCKED_OWNER
277 const nsfw = 'both'
278 const privacyOneOf = getAllPrivacies()
279
280 return this.list({
281 ...options,
282
283 include,
284 nsfw,
285 privacyOneOf,
286
287 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
288 })
289 }
290
291 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
292 handle: string
293 }) {
294 const { handle, search } = options
295 const path = '/api/v1/accounts/' + handle + '/videos'
296
297 return this.getRequestBody<ResultList<Video>>({
298 ...options,
299
300 path,
301 query: { search, ...this.buildListQuery(options) },
302 implicitToken: true,
303 defaultExpectedStatus: HttpStatusCode.OK_200
304 })
305 }
306
307 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
308 handle: string
309 }) {
310 const { handle } = options
311 const path = '/api/v1/video-channels/' + handle + '/videos'
312
313 return this.getRequestBody<ResultList<Video>>({
314 ...options,
315
316 path,
317 query: this.buildListQuery(options),
318 implicitToken: true,
319 defaultExpectedStatus: HttpStatusCode.OK_200
320 })
321 }
322
323 // ---------------------------------------------------------------------------
324
325 async find (options: OverrideCommandOptions & {
326 name: string
327 }) {
328 const { data } = await this.list(options)
329
330 return data.find(v => v.name === options.name)
331 }
332
333 // ---------------------------------------------------------------------------
334
335 update (options: OverrideCommandOptions & {
336 id: number | string
337 attributes?: VideoEdit
338 }) {
339 const { id, attributes = {} } = options
340 const path = '/api/v1/videos/' + id
341
342 // Upload request
343 if (attributes.thumbnailfile || attributes.previewfile) {
344 const attaches: any = {}
345 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
346 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
347
348 return this.putUploadRequest({
349 ...options,
350
351 path,
352 fields: options.attributes,
353 attaches: {
354 thumbnailfile: attributes.thumbnailfile,
355 previewfile: attributes.previewfile
356 },
357 implicitToken: true,
358 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
359 })
360 }
361
362 return this.putBodyRequest({
363 ...options,
364
365 path,
366 fields: options.attributes,
367 implicitToken: true,
368 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
369 })
370 }
371
372 remove (options: OverrideCommandOptions & {
373 id: number | string
374 }) {
375 const path = '/api/v1/videos/' + options.id
376
377 return unwrapBody(this.deleteRequest({
378 ...options,
379
380 path,
381 implicitToken: true,
382 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
383 }))
384 }
385
386 async removeAll () {
387 const { data } = await this.list()
388
389 for (const v of data) {
390 await this.remove({ id: v.id })
391 }
392 }
393
394 // ---------------------------------------------------------------------------
395
396 async upload (options: OverrideCommandOptions & {
397 attributes?: VideoEdit
398 mode?: 'legacy' | 'resumable' // default legacy
399 waitTorrentGeneration?: boolean // default true
400 completedExpectedStatus?: HttpStatusCodeType
401 } = {}) {
402 const { mode = 'legacy', waitTorrentGeneration = true } = options
403 let defaultChannelId = 1
404
405 try {
406 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
407 defaultChannelId = videoChannels[0].id
408 } catch (e) { /* empty */ }
409
410 // Override default attributes
411 const attributes = {
412 name: 'my super video',
413 category: 5,
414 licence: 4,
415 language: 'zh',
416 channelId: defaultChannelId,
417 nsfw: true,
418 waitTranscoding: false,
419 description: 'my super description',
420 support: 'my super support text',
421 tags: [ 'tag' ],
422 privacy: VideoPrivacy.PUBLIC,
423 commentsEnabled: true,
424 downloadEnabled: true,
425 fixture: 'video_short.webm',
426
427 ...options.attributes
428 }
429
430 const created = mode === 'legacy'
431 ? await this.buildLegacyUpload({ ...options, attributes })
432 : await this.buildResumeUpload({ ...options, path: '/api/v1/videos/upload-resumable', attributes })
433
434 // Wait torrent generation
435 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
436 if (expectedStatus === HttpStatusCode.OK_200 && waitTorrentGeneration) {
437 let video: VideoDetails
438
439 do {
440 video = await this.getWithToken({ ...options, id: created.uuid })
441
442 await wait(50)
443 } while (!video.files[0].torrentUrl)
444 }
445
446 return created
447 }
448
449 async buildLegacyUpload (options: OverrideCommandOptions & {
450 attributes: VideoEdit
451 }): Promise<VideoCreateResult> {
452 const path = '/api/v1/videos/upload'
453
454 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
455 ...options,
456
457 path,
458 fields: this.buildUploadFields(options.attributes),
459 attaches: this.buildUploadAttaches(options.attributes),
460 implicitToken: true,
461 defaultExpectedStatus: HttpStatusCode.OK_200
462 })).then(body => body.video || body as any)
463 }
464
465 async buildResumeUpload (options: OverrideCommandOptions & {
466 path: string
467 attributes: { fixture?: string } & { [id: string]: any }
468 completedExpectedStatus?: HttpStatusCodeType // When the upload is finished
469 }): Promise<VideoCreateResult> {
470 const { path, attributes, expectedStatus = HttpStatusCode.OK_200, completedExpectedStatus } = options
471
472 let size = 0
473 let videoFilePath: string
474 let mimetype = 'video/mp4'
475
476 if (attributes.fixture) {
477 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
478 size = (await stat(videoFilePath)).size
479
480 if (videoFilePath.endsWith('.mkv')) {
481 mimetype = 'video/x-matroska'
482 } else if (videoFilePath.endsWith('.webm')) {
483 mimetype = 'video/webm'
484 }
485 }
486
487 // Do not check status automatically, we'll check it manually
488 const initializeSessionRes = await this.prepareResumableUpload({
489 ...options,
490
491 path,
492 expectedStatus: null,
493 attributes,
494 size,
495 mimetype
496 })
497 const initStatus = initializeSessionRes.status
498
499 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
500 const locationHeader = initializeSessionRes.header['location']
501 expect(locationHeader).to.not.be.undefined
502
503 const pathUploadId = locationHeader.split('?')[1]
504
505 const result = await this.sendResumableChunks({
506 ...options,
507
508 path,
509 pathUploadId,
510 videoFilePath,
511 size,
512 expectedStatus: completedExpectedStatus
513 })
514
515 if (result.statusCode === HttpStatusCode.OK_200) {
516 await this.endResumableUpload({
517 ...options,
518
519 expectedStatus: HttpStatusCode.NO_CONTENT_204,
520 path,
521 pathUploadId
522 })
523 }
524
525 return result.body?.video || result.body as any
526 }
527
528 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
529 ? HttpStatusCode.CREATED_201
530 : expectedStatus
531
532 expect(initStatus).to.equal(expectedInitStatus)
533
534 return initializeSessionRes.body.video || initializeSessionRes.body
535 }
536
537 async prepareResumableUpload (options: OverrideCommandOptions & {
538 path: string
539 attributes: { fixture?: string } & { [id: string]: any }
540 size: number
541 mimetype: string
542
543 originalName?: string
544 lastModified?: number
545 }) {
546 const { path, attributes, originalName, lastModified, size, mimetype } = options
547
548 const attaches = this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ]))
549
550 const uploadOptions = {
551 ...options,
552
553 path,
554 headers: {
555 'X-Upload-Content-Type': mimetype,
556 'X-Upload-Content-Length': size.toString()
557 },
558 fields: {
559 filename: attributes.fixture,
560 originalName,
561 lastModified,
562
563 ...this.buildUploadFields(options.attributes)
564 },
565
566 // Fixture will be sent later
567 attaches: this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ])),
568 implicitToken: true,
569
570 defaultExpectedStatus: null
571 }
572
573 if (Object.keys(attaches).length === 0) return this.postBodyRequest(uploadOptions)
574
575 return this.postUploadRequest(uploadOptions)
576 }
577
578 sendResumableChunks (options: OverrideCommandOptions & {
579 pathUploadId: string
580 path: string
581 videoFilePath: string
582 size: number
583 contentLength?: number
584 contentRangeBuilder?: (start: number, chunk: any) => string
585 digestBuilder?: (chunk: any) => string
586 }) {
587 const {
588 path,
589 pathUploadId,
590 videoFilePath,
591 size,
592 contentLength,
593 contentRangeBuilder,
594 digestBuilder,
595 expectedStatus = HttpStatusCode.OK_200
596 } = options
597
598 let start = 0
599
600 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
601
602 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
603 const server = this.server
604 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
605 readable.on('data', async function onData (chunk) {
606 try {
607 readable.pause()
608
609 const byterangeStart = start + chunk.length - 1
610
611 const headers = {
612 'Authorization': 'Bearer ' + token,
613 'Content-Type': 'application/octet-stream',
614 'Content-Range': contentRangeBuilder
615 ? contentRangeBuilder(start, chunk)
616 : `bytes ${start}-${byterangeStart}/${size}`,
617 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
618 }
619
620 if (digestBuilder) {
621 Object.assign(headers, { digest: digestBuilder(chunk) })
622 }
623
624 const res = await got<{ video: VideoCreateResult }>({
625 url: new URL(path + '?' + pathUploadId, server.url).toString(),
626 method: 'put',
627 headers,
628 body: chunk,
629 responseType: 'json',
630 throwHttpErrors: false
631 })
632
633 start += chunk.length
634
635 // Last request, check final status
636 if (byterangeStart + 1 === size) {
637 if (res.statusCode === expectedStatus) {
638 return resolve(res)
639 }
640
641 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
642 readable.off('data', onData)
643
644 // eslint-disable-next-line max-len
645 const message = `Incorrect transient behaviour sending intermediary chunks. Status code is ${res.statusCode} instead of ${expectedStatus}`
646 return reject(new Error(message))
647 }
648 }
649
650 readable.resume()
651 } catch (err) {
652 reject(err)
653 }
654 })
655 })
656 }
657
658 endResumableUpload (options: OverrideCommandOptions & {
659 path: string
660 pathUploadId: string
661 }) {
662 return this.deleteRequest({
663 ...options,
664
665 path: options.path,
666 rawQuery: options.pathUploadId,
667 implicitToken: true,
668 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
669 })
670 }
671
672 quickUpload (options: OverrideCommandOptions & {
673 name: string
674 nsfw?: boolean
675 privacy?: VideoPrivacyType
676 fixture?: string
677 videoPasswords?: string[]
678 }) {
679 const attributes: VideoEdit = { name: options.name }
680 if (options.nsfw) attributes.nsfw = options.nsfw
681 if (options.privacy) attributes.privacy = options.privacy
682 if (options.fixture) attributes.fixture = options.fixture
683 if (options.videoPasswords) attributes.videoPasswords = options.videoPasswords
684
685 return this.upload({ ...options, attributes })
686 }
687
688 async randomUpload (options: OverrideCommandOptions & {
689 wait?: boolean // default true
690 additionalParams?: VideoEdit & { prefixName?: string }
691 } = {}) {
692 const { wait = true, additionalParams } = options
693 const prefixName = additionalParams?.prefixName || ''
694 const name = prefixName + buildUUID()
695
696 const attributes = { name, ...additionalParams }
697
698 const result = await this.upload({ ...options, attributes })
699
700 if (wait) await waitJobs([ this.server ])
701
702 return { ...result, name }
703 }
704
705 // ---------------------------------------------------------------------------
706
707 replaceSourceFile (options: OverrideCommandOptions & {
708 videoId: number | string
709 fixture: string
710 completedExpectedStatus?: HttpStatusCodeType
711 }) {
712 return this.buildResumeUpload({
713 ...options,
714
715 path: '/api/v1/videos/' + options.videoId + '/source/replace-resumable',
716 attributes: { fixture: options.fixture }
717 })
718 }
719
720 // ---------------------------------------------------------------------------
721
722 removeHLSPlaylist (options: OverrideCommandOptions & {
723 videoId: number | string
724 }) {
725 const path = '/api/v1/videos/' + options.videoId + '/hls'
726
727 return this.deleteRequest({
728 ...options,
729
730 path,
731 implicitToken: true,
732 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
733 })
734 }
735
736 removeHLSFile (options: OverrideCommandOptions & {
737 videoId: number | string
738 fileId: number
739 }) {
740 const path = '/api/v1/videos/' + options.videoId + '/hls/' + options.fileId
741
742 return this.deleteRequest({
743 ...options,
744
745 path,
746 implicitToken: true,
747 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
748 })
749 }
750
751 removeAllWebVideoFiles (options: OverrideCommandOptions & {
752 videoId: number | string
753 }) {
754 const path = '/api/v1/videos/' + options.videoId + '/web-videos'
755
756 return this.deleteRequest({
757 ...options,
758
759 path,
760 implicitToken: true,
761 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
762 })
763 }
764
765 removeWebVideoFile (options: OverrideCommandOptions & {
766 videoId: number | string
767 fileId: number
768 }) {
769 const path = '/api/v1/videos/' + options.videoId + '/web-videos/' + options.fileId
770
771 return this.deleteRequest({
772 ...options,
773
774 path,
775 implicitToken: true,
776 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
777 })
778 }
779
780 runTranscoding (options: OverrideCommandOptions & VideoTranscodingCreate & {
781 videoId: number | string
782 }) {
783 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
784
785 return this.postBodyRequest({
786 ...options,
787
788 path,
789 fields: pick(options, [ 'transcodingType', 'forceTranscoding' ]),
790 implicitToken: true,
791 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
792 })
793 }
794
795 // ---------------------------------------------------------------------------
796
797 private buildListQuery (options: VideosCommonQuery) {
798 return pick(options, [
799 'start',
800 'count',
801 'sort',
802 'nsfw',
803 'isLive',
804 'categoryOneOf',
805 'licenceOneOf',
806 'languageOneOf',
807 'privacyOneOf',
808 'tagsOneOf',
809 'tagsAllOf',
810 'isLocal',
811 'include',
812 'skipCount'
813 ])
814 }
815
816 private buildUploadFields (attributes: VideoEdit) {
817 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
818 }
819
820 private buildUploadAttaches (attributes: VideoEdit) {
821 const attaches: { [ name: string ]: string } = {}
822
823 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
824 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
825 }
826
827 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)
828
829 return attaches
830 }
831}
diff --git a/packages/server-commands/src/videos/views-command.ts b/packages/server-commands/src/videos/views-command.ts
new file mode 100644
index 000000000..048bd3fda
--- /dev/null
+++ b/packages/server-commands/src/videos/views-command.ts
@@ -0,0 +1,51 @@
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2import { HttpStatusCode, VideoViewEvent } from '@peertube/peertube-models'
3import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
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}