1 import { ChildProcess, fork } from 'child_process'
2 import { copy } from 'fs-extra'
3 import { join } from 'path'
4 import { root } from '@server/helpers/core-utils'
5 import { randomInt } from '@shared/core-utils'
6 import { Video, VideoChannel, VideoCreateResult, VideoDetails } from '../../models/videos'
7 import { BulkCommand } from '../bulk'
8 import { CLICommand } from '../cli'
9 import { CustomPagesCommand } from '../custom-pages'
10 import { FeedCommand } from '../feeds'
11 import { LogsCommand } from '../logs'
12 import { parallelTests, SQLCommand } from '../miscs'
13 import { AbusesCommand } from '../moderation'
14 import { OverviewsCommand } from '../overviews'
15 import { SearchCommand } from '../search'
16 import { SocketIOCommand } from '../socket'
17 import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users'
21 ChangeOwnershipCommand,
28 StreamingPlaylistsCommand,
31 import { CommentsCommand } from '../videos/comments-command'
32 import { ConfigCommand } from './config-command'
33 import { ContactFormCommand } from './contact-form-command'
34 import { DebugCommand } from './debug-command'
35 import { FollowsCommand } from './follows-command'
36 import { JobsCommand } from './jobs-command'
37 import { PluginsCommand } from './plugins-command'
38 import { RedundancyCommand } from './redundancy-command'
39 import { ServersCommand } from './servers-command'
40 import { StatsCommand } from './stats-command'
41 import { ObjectStorageCommand } from './object-storage-command'
43 export type RunServerOptions = {
46 peertubeArgs?: string[]
47 env?: { [ id: string ]: string }
50 export class PeerTubeServer {
62 internalServerNumber: number
65 customConfigFile?: string
79 channel?: VideoChannel
82 videoCreated?: VideoCreateResult
83 videoDetails?: VideoDetails
85 videos?: { id: number, uuid: string }[]
93 customPage?: CustomPagesCommand
96 abuses?: AbusesCommand
97 overviews?: OverviewsCommand
98 search?: SearchCommand
99 contactForm?: ContactFormCommand
101 follows?: FollowsCommand
103 plugins?: PluginsCommand
104 redundancy?: RedundancyCommand
106 config?: ConfigCommand
107 socketIO?: SocketIOCommand
108 accounts?: AccountsCommand
109 blocklist?: BlocklistCommand
110 subscriptions?: SubscriptionsCommand
112 services?: ServicesCommand
113 blacklist?: BlacklistCommand
114 captions?: CaptionsCommand
115 changeOwnership?: ChangeOwnershipCommand
116 playlists?: PlaylistsCommand
117 history?: HistoryCommand
118 imports?: ImportsCommand
119 streamingPlaylists?: StreamingPlaylistsCommand
120 channels?: ChannelsCommand
121 comments?: CommentsCommand
123 notifications?: NotificationsCommand
124 servers?: ServersCommand
127 objectStorage?: ObjectStorageCommand
128 videos?: VideosCommand
130 constructor (options: { serverNumber: number } | { url: string }) {
131 if ((options as any).url) {
132 this.setUrl((options as any).url)
134 this.setServerNumber((options as any).serverNumber)
148 this.assignCommands()
151 setServerNumber (serverNumber: number) {
152 this.serverNumber = serverNumber
154 this.parallel = parallelTests()
156 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
157 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
158 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
159 this.port = 9000 + this.internalServerNumber
161 this.url = `http://localhost:${this.port}`
162 this.host = `localhost:${this.port}`
163 this.hostname = 'localhost'
166 setUrl (url: string) {
167 const parsed = new URL(url)
170 this.host = parsed.host
171 this.hostname = parsed.hostname
172 this.port = parseInt(parsed.port)
175 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
176 await ServersCommand.flushTests(this.internalServerNumber)
178 return this.run(configOverride, options)
181 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
182 // These actions are async so we need to be sure that they have both been done
183 const serverRunString = {
184 'HTTP server listening': false
186 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
187 serverRunString[key] = false
190 client_id: 'Client id: (.+)',
191 client_secret: 'Client secret: (.+)',
192 user_username: 'Username: (.+)',
193 user_password: 'User password: (.+)'
196 await this.assignCustomConfigFile()
198 const configOverride = this.buildConfigOverride()
200 if (configOverrideArg !== undefined) {
201 Object.assign(configOverride, configOverrideArg)
204 // Share the environment
205 const env = Object.create(process.env)
206 env['NODE_ENV'] = 'test'
207 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
208 env['NODE_CONFIG'] = JSON.stringify(configOverride)
211 Object.assign(env, options.env)
214 const forkOptions = {
218 execArgv: options.nodeArgs || []
221 return new Promise<void>((res, rej) => {
224 this.app = fork(join(root(), 'dist', 'server.js'), options.peertubeArgs || [], forkOptions)
226 const onPeerTubeExit = () => rej(new Error('Process exited'))
227 const onParentExit = () => {
228 if (!this.app || !this.app.pid) return
231 process.kill(self.app.pid)
232 } catch { /* empty */ }
235 this.app.on('exit', onPeerTubeExit)
236 process.on('exit', onParentExit)
238 this.app.stdout.on('data', function onStdout (data) {
239 let dontContinue = false
241 // Capture things if we want to
242 for (const key of Object.keys(regexps)) {
243 const regexp = regexps[key]
244 const matches = data.toString().match(regexp)
245 if (matches !== null) {
246 if (key === 'client_id') self.store.client.id = matches[1]
247 else if (key === 'client_secret') self.store.client.secret = matches[1]
248 else if (key === 'user_username') self.store.user.username = matches[1]
249 else if (key === 'user_password') self.store.user.password = matches[1]
253 // Check if all required sentences are here
254 for (const key of Object.keys(serverRunString)) {
255 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
256 if (serverRunString[key] === false) dontContinue = true
259 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
260 if (dontContinue === true) return
262 if (options.hideLogs === false) {
263 console.log(data.toString())
265 process.removeListener('exit', onParentExit)
266 self.app.stdout.removeListener('data', onStdout)
267 self.app.removeListener('exit', onPeerTubeExit)
276 if (!this.app) return
278 await this.sql.cleanup()
280 process.kill(-this.app.pid)
285 private randomServer () {
289 return randomInt(low, high)
292 private randomRTMP () {
296 return randomInt(low, high)
299 private async assignCustomConfigFile () {
300 if (this.internalServerNumber === this.serverNumber) return
302 const basePath = join(root(), 'config')
304 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
305 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
307 this.customConfigFile = tmpConfigFile
310 private buildConfigOverride () {
311 if (!this.parallel) return {}
321 suffix: '_test' + this.internalServerNumber
324 tmp: `test${this.internalServerNumber}/tmp/`,
325 bin: `test${this.internalServerNumber}/bin/`,
326 avatars: `test${this.internalServerNumber}/avatars/`,
327 videos: `test${this.internalServerNumber}/videos/`,
328 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
329 redundancy: `test${this.internalServerNumber}/redundancy/`,
330 logs: `test${this.internalServerNumber}/logs/`,
331 previews: `test${this.internalServerNumber}/previews/`,
332 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
333 torrents: `test${this.internalServerNumber}/torrents/`,
334 captions: `test${this.internalServerNumber}/captions/`,
335 cache: `test${this.internalServerNumber}/cache/`,
336 plugins: `test${this.internalServerNumber}/plugins/`
339 email: `admin${this.internalServerNumber}@example.com`
349 private assignCommands () {
350 this.bulk = new BulkCommand(this)
351 this.cli = new CLICommand(this)
352 this.customPage = new CustomPagesCommand(this)
353 this.feed = new FeedCommand(this)
354 this.logs = new LogsCommand(this)
355 this.abuses = new AbusesCommand(this)
356 this.overviews = new OverviewsCommand(this)
357 this.search = new SearchCommand(this)
358 this.contactForm = new ContactFormCommand(this)
359 this.debug = new DebugCommand(this)
360 this.follows = new FollowsCommand(this)
361 this.jobs = new JobsCommand(this)
362 this.plugins = new PluginsCommand(this)
363 this.redundancy = new RedundancyCommand(this)
364 this.stats = new StatsCommand(this)
365 this.config = new ConfigCommand(this)
366 this.socketIO = new SocketIOCommand(this)
367 this.accounts = new AccountsCommand(this)
368 this.blocklist = new BlocklistCommand(this)
369 this.subscriptions = new SubscriptionsCommand(this)
370 this.live = new LiveCommand(this)
371 this.services = new ServicesCommand(this)
372 this.blacklist = new BlacklistCommand(this)
373 this.captions = new CaptionsCommand(this)
374 this.changeOwnership = new ChangeOwnershipCommand(this)
375 this.playlists = new PlaylistsCommand(this)
376 this.history = new HistoryCommand(this)
377 this.imports = new ImportsCommand(this)
378 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
379 this.channels = new ChannelsCommand(this)
380 this.comments = new CommentsCommand(this)
381 this.sql = new SQLCommand(this)
382 this.notifications = new NotificationsCommand(this)
383 this.servers = new ServersCommand(this)
384 this.login = new LoginCommand(this)
385 this.users = new UsersCommand(this)
386 this.videos = new VideosCommand(this)
387 this.objectStorage = new ObjectStorageCommand(this)