]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/server-commands/server/server.ts
feat: show contained playlists under My videos (#5125)
[github/Chocobozzz/PeerTube.git] / shared / server-commands / server / server.ts
CommitLineData
254d3579
C
1import { ChildProcess, fork } from 'child_process'
2import { copy } from 'fs-extra'
3import { join } from 'path'
c55e3d72 4import { parallelTests, randomInt, root } from '@shared/core-utils'
a3b472a1 5import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@shared/models'
254d3579
C
6import { BulkCommand } from '../bulk'
7import { CLICommand } from '../cli'
8import { CustomPagesCommand } from '../custom-pages'
9import { FeedCommand } from '../feeds'
10import { LogsCommand } from '../logs'
c55e3d72 11import { SQLCommand } from '../miscs'
254d3579
C
12import { AbusesCommand } from '../moderation'
13import { OverviewsCommand } from '../overviews'
14import { SearchCommand } from '../search'
15import { SocketIOCommand } from '../socket'
56f47830
C
16import {
17 AccountsCommand,
18 BlocklistCommand,
19 LoginCommand,
20 NotificationsCommand,
21 SubscriptionsCommand,
22 TwoFactorCommand,
23 UsersCommand
24} from '../users'
254d3579
C
25import {
26 BlacklistCommand,
27 CaptionsCommand,
28 ChangeOwnershipCommand,
29 ChannelsCommand,
2a491182 30 ChannelSyncsCommand,
254d3579
C
31 HistoryCommand,
32 ImportsCommand,
33 LiveCommand,
34 PlaylistsCommand,
35 ServicesCommand,
36 StreamingPlaylistsCommand,
b2111066 37 VideosCommand,
92e66e04 38 VideoStudioCommand,
b2111066 39 ViewsCommand
254d3579
C
40} from '../videos'
41import { CommentsCommand } from '../videos/comments-command'
b2111066 42import { VideoStatsCommand } from '../videos/video-stats-command'
254d3579
C
43import { ConfigCommand } from './config-command'
44import { ContactFormCommand } from './contact-form-command'
45import { DebugCommand } from './debug-command'
46import { FollowsCommand } from './follows-command'
47import { JobsCommand } from './jobs-command'
fd3c2e87 48import { MetricsCommand } from './metrics-command'
c55e3d72 49import { ObjectStorageCommand } from './object-storage-command'
254d3579
C
50import { PluginsCommand } from './plugins-command'
51import { RedundancyCommand } from './redundancy-command'
52import { ServersCommand } from './servers-command'
53import { StatsCommand } from './stats-command'
54
55export type RunServerOptions = {
56 hideLogs?: boolean
2e980ed3
C
57 nodeArgs?: string[]
58 peertubeArgs?: string[]
0305db28 59 env?: { [ id: string ]: string }
254d3579
C
60}
61
62export class PeerTubeServer {
63 app?: ChildProcess
64
65 url: string
66 host?: string
67 hostname?: string
68 port?: number
69
70 rtmpPort?: number
df1db951 71 rtmpsPort?: number
254d3579
C
72
73 parallel?: boolean
74 internalServerNumber: number
75
76 serverNumber?: number
77 customConfigFile?: string
78
79 store?: {
80 client?: {
81 id?: string
82 secret?: string
83 }
84
85 user?: {
86 username: string
87 password: string
88 email?: string
89 }
90
91 channel?: VideoChannel
a3b472a1 92 videoChannelSync?: Partial<VideoChannelSync>
254d3579 93
83903cb6
C
94 video?: Video
95 videoCreated?: VideoCreateResult
96 videoDetails?: VideoDetails
254d3579
C
97
98 videos?: { id: number, uuid: string }[]
99 }
100
101 accessToken?: string
102 refreshToken?: string
103
104 bulk?: BulkCommand
105 cli?: CLICommand
106 customPage?: CustomPagesCommand
107 feed?: FeedCommand
108 logs?: LogsCommand
109 abuses?: AbusesCommand
110 overviews?: OverviewsCommand
111 search?: SearchCommand
112 contactForm?: ContactFormCommand
113 debug?: DebugCommand
114 follows?: FollowsCommand
115 jobs?: JobsCommand
fd3c2e87 116 metrics?: MetricsCommand
254d3579
C
117 plugins?: PluginsCommand
118 redundancy?: RedundancyCommand
119 stats?: StatsCommand
120 config?: ConfigCommand
121 socketIO?: SocketIOCommand
122 accounts?: AccountsCommand
123 blocklist?: BlocklistCommand
124 subscriptions?: SubscriptionsCommand
125 live?: LiveCommand
126 services?: ServicesCommand
127 blacklist?: BlacklistCommand
128 captions?: CaptionsCommand
129 changeOwnership?: ChangeOwnershipCommand
130 playlists?: PlaylistsCommand
131 history?: HistoryCommand
132 imports?: ImportsCommand
2a491182 133 channelSyncs?: ChannelSyncsCommand
254d3579
C
134 streamingPlaylists?: StreamingPlaylistsCommand
135 channels?: ChannelsCommand
136 comments?: CommentsCommand
137 sql?: SQLCommand
138 notifications?: NotificationsCommand
139 servers?: ServersCommand
140 login?: LoginCommand
141 users?: UsersCommand
0305db28 142 objectStorage?: ObjectStorageCommand
92e66e04 143 videoStudio?: VideoStudioCommand
254d3579 144 videos?: VideosCommand
b2111066
C
145 videoStats?: VideoStatsCommand
146 views?: ViewsCommand
56f47830 147 twoFactor?: TwoFactorCommand
254d3579
C
148
149 constructor (options: { serverNumber: number } | { url: string }) {
150 if ((options as any).url) {
151 this.setUrl((options as any).url)
152 } else {
153 this.setServerNumber((options as any).serverNumber)
154 }
155
156 this.store = {
157 client: {
158 id: null,
159 secret: null
160 },
161 user: {
162 username: null,
163 password: null
164 }
165 }
166
167 this.assignCommands()
168 }
169
170 setServerNumber (serverNumber: number) {
171 this.serverNumber = serverNumber
172
173 this.parallel = parallelTests()
174
175 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
176 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
df1db951 177 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
254d3579
C
178 this.port = 9000 + this.internalServerNumber
179
180 this.url = `http://localhost:${this.port}`
181 this.host = `localhost:${this.port}`
182 this.hostname = 'localhost'
183 }
184
185 setUrl (url: string) {
186 const parsed = new URL(url)
187
188 this.url = url
189 this.host = parsed.host
190 this.hostname = parsed.hostname
191 this.port = parseInt(parsed.port)
192 }
193
6c5f0d3a 194 getDirectoryPath (directoryName: string) {
195 const testDirectory = 'test' + this.internalServerNumber
196
197 return join(root(), testDirectory, directoryName)
198 }
199
2e980ed3 200 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
254d3579
C
201 await ServersCommand.flushTests(this.internalServerNumber)
202
2e980ed3 203 return this.run(configOverride, options)
254d3579
C
204 }
205
2e980ed3 206 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
254d3579
C
207 // These actions are async so we need to be sure that they have both been done
208 const serverRunString = {
209 'HTTP server listening': false
210 }
211 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
212 serverRunString[key] = false
213
214 const regexps = {
215 client_id: 'Client id: (.+)',
216 client_secret: 'Client secret: (.+)',
217 user_username: 'Username: (.+)',
218 user_password: 'User password: (.+)'
219 }
220
221 await this.assignCustomConfigFile()
222
223 const configOverride = this.buildConfigOverride()
224
225 if (configOverrideArg !== undefined) {
226 Object.assign(configOverride, configOverrideArg)
227 }
228
229 // Share the environment
230 const env = Object.create(process.env)
231 env['NODE_ENV'] = 'test'
232 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
233 env['NODE_CONFIG'] = JSON.stringify(configOverride)
234
0305db28
JB
235 if (options.env) {
236 Object.assign(env, options.env)
237 }
238
7298cad6 239 const execArgv = options.nodeArgs || []
8f5a1f36
C
240 // FIXME: too slow :/
241 // execArgv.push('--enable-source-maps')
7298cad6 242
254d3579
C
243 const forkOptions = {
244 silent: true,
245 env,
246 detached: true,
7298cad6 247 execArgv
254d3579
C
248 }
249
9270bd3a 250 const peertubeArgs = options.peertubeArgs || []
9270bd3a 251
0305db28 252 return new Promise<void>((res, rej) => {
08642a76 253 const self = this
f307255e 254 let aggregatedLogs = ''
08642a76 255
9270bd3a 256 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
0305db28 257
f307255e 258 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
706a450f
C
259 const onParentExit = () => {
260 if (!this.app || !this.app.pid) return
261
262 try {
263 process.kill(self.app.pid)
264 } catch { /* empty */ }
0305db28
JB
265 }
266
706a450f
C
267 this.app.on('exit', onPeerTubeExit)
268 process.on('exit', onParentExit)
0305db28 269
254d3579
C
270 this.app.stdout.on('data', function onStdout (data) {
271 let dontContinue = false
272
f307255e
C
273 const log: string = data.toString()
274 aggregatedLogs += log
275
254d3579
C
276 // Capture things if we want to
277 for (const key of Object.keys(regexps)) {
278 const regexp = regexps[key]
f307255e 279 const matches = log.match(regexp)
254d3579 280 if (matches !== null) {
08642a76
C
281 if (key === 'client_id') self.store.client.id = matches[1]
282 else if (key === 'client_secret') self.store.client.secret = matches[1]
283 else if (key === 'user_username') self.store.user.username = matches[1]
284 else if (key === 'user_password') self.store.user.password = matches[1]
254d3579
C
285 }
286 }
287
288 // Check if all required sentences are here
289 for (const key of Object.keys(serverRunString)) {
f307255e 290 if (log.includes(key)) serverRunString[key] = true
254d3579
C
291 if (serverRunString[key] === false) dontContinue = true
292 }
293
294 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
295 if (dontContinue === true) return
296
297 if (options.hideLogs === false) {
f307255e 298 console.log(log)
254d3579 299 } else {
706a450f 300 process.removeListener('exit', onParentExit)
08642a76 301 self.app.stdout.removeListener('data', onStdout)
706a450f 302 self.app.removeListener('exit', onPeerTubeExit)
254d3579
C
303 }
304
254d3579
C
305 res()
306 })
307 })
308 }
309
310 async kill () {
311 if (!this.app) return
312
313 await this.sql.cleanup()
314
315 process.kill(-this.app.pid)
316
317 this.app = null
318 }
319
320 private randomServer () {
321 const low = 10
322 const high = 10000
323
324 return randomInt(low, high)
325 }
326
327 private randomRTMP () {
328 const low = 1900
329 const high = 2100
330
331 return randomInt(low, high)
332 }
333
334 private async assignCustomConfigFile () {
335 if (this.internalServerNumber === this.serverNumber) return
336
337 const basePath = join(root(), 'config')
338
339 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
340 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
341
342 this.customConfigFile = tmpConfigFile
343 }
344
345 private buildConfigOverride () {
346 if (!this.parallel) return {}
347
348 return {
349 listen: {
350 port: this.port
351 },
352 webserver: {
353 port: this.port
354 },
355 database: {
356 suffix: '_test' + this.internalServerNumber
357 },
358 storage: {
6c5f0d3a 359 tmp: this.getDirectoryPath('tmp') + '/',
360 bin: this.getDirectoryPath('bin') + '/',
361 avatars: this.getDirectoryPath('avatars') + '/',
362 videos: this.getDirectoryPath('videos') + '/',
363 streaming_playlists: this.getDirectoryPath('streaming-playlists') + '/',
364 redundancy: this.getDirectoryPath('redundancy') + '/',
365 logs: this.getDirectoryPath('logs') + '/',
366 previews: this.getDirectoryPath('previews') + '/',
367 thumbnails: this.getDirectoryPath('thumbnails') + '/',
368 torrents: this.getDirectoryPath('torrents') + '/',
369 captions: this.getDirectoryPath('captions') + '/',
370 cache: this.getDirectoryPath('cache') + '/',
371 plugins: this.getDirectoryPath('plugins') + '/',
372 well_known: this.getDirectoryPath('well-known') + '/'
254d3579
C
373 },
374 admin: {
375 email: `admin${this.internalServerNumber}@example.com`
376 },
377 live: {
378 rtmp: {
379 port: this.rtmpPort
380 }
381 }
382 }
383 }
384
385 private assignCommands () {
386 this.bulk = new BulkCommand(this)
387 this.cli = new CLICommand(this)
388 this.customPage = new CustomPagesCommand(this)
389 this.feed = new FeedCommand(this)
390 this.logs = new LogsCommand(this)
391 this.abuses = new AbusesCommand(this)
392 this.overviews = new OverviewsCommand(this)
393 this.search = new SearchCommand(this)
394 this.contactForm = new ContactFormCommand(this)
395 this.debug = new DebugCommand(this)
396 this.follows = new FollowsCommand(this)
397 this.jobs = new JobsCommand(this)
fd3c2e87 398 this.metrics = new MetricsCommand(this)
254d3579
C
399 this.plugins = new PluginsCommand(this)
400 this.redundancy = new RedundancyCommand(this)
401 this.stats = new StatsCommand(this)
402 this.config = new ConfigCommand(this)
403 this.socketIO = new SocketIOCommand(this)
404 this.accounts = new AccountsCommand(this)
405 this.blocklist = new BlocklistCommand(this)
406 this.subscriptions = new SubscriptionsCommand(this)
407 this.live = new LiveCommand(this)
408 this.services = new ServicesCommand(this)
409 this.blacklist = new BlacklistCommand(this)
410 this.captions = new CaptionsCommand(this)
411 this.changeOwnership = new ChangeOwnershipCommand(this)
412 this.playlists = new PlaylistsCommand(this)
413 this.history = new HistoryCommand(this)
414 this.imports = new ImportsCommand(this)
2a491182 415 this.channelSyncs = new ChannelSyncsCommand(this)
254d3579
C
416 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
417 this.channels = new ChannelsCommand(this)
418 this.comments = new CommentsCommand(this)
419 this.sql = new SQLCommand(this)
420 this.notifications = new NotificationsCommand(this)
421 this.servers = new ServersCommand(this)
422 this.login = new LoginCommand(this)
423 this.users = new UsersCommand(this)
424 this.videos = new VideosCommand(this)
0305db28 425 this.objectStorage = new ObjectStorageCommand(this)
92e66e04 426 this.videoStudio = new VideoStudioCommand(this)
b2111066
C
427 this.videoStats = new VideoStatsCommand(this)
428 this.views = new ViewsCommand(this)
56f47830 429 this.twoFactor = new TwoFactorCommand(this)
254d3579
C
430 }
431}