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 {
61 internalServerNumber: number
64 customConfigFile?: string
78 channel?: VideoChannel
81 videoCreated?: VideoCreateResult
82 videoDetails?: VideoDetails
84 videos?: { id: number, uuid: string }[]
92 customPage?: CustomPagesCommand
95 abuses?: AbusesCommand
96 overviews?: OverviewsCommand
97 search?: SearchCommand
98 contactForm?: ContactFormCommand
100 follows?: FollowsCommand
102 plugins?: PluginsCommand
103 redundancy?: RedundancyCommand
105 config?: ConfigCommand
106 socketIO?: SocketIOCommand
107 accounts?: AccountsCommand
108 blocklist?: BlocklistCommand
109 subscriptions?: SubscriptionsCommand
111 services?: ServicesCommand
112 blacklist?: BlacklistCommand
113 captions?: CaptionsCommand
114 changeOwnership?: ChangeOwnershipCommand
115 playlists?: PlaylistsCommand
116 history?: HistoryCommand
117 imports?: ImportsCommand
118 streamingPlaylists?: StreamingPlaylistsCommand
119 channels?: ChannelsCommand
120 comments?: CommentsCommand
122 notifications?: NotificationsCommand
123 servers?: ServersCommand
126 objectStorage?: ObjectStorageCommand
127 videos?: VideosCommand
129 constructor (options: { serverNumber: number } | { url: string }) {
130 if ((options as any).url) {
131 this.setUrl((options as any).url)
133 this.setServerNumber((options as any).serverNumber)
147 this.assignCommands()
150 setServerNumber (serverNumber: number) {
151 this.serverNumber = serverNumber
153 this.parallel = parallelTests()
155 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
156 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
157 this.port = 9000 + this.internalServerNumber
159 this.url = `http://localhost:${this.port}`
160 this.host = `localhost:${this.port}`
161 this.hostname = 'localhost'
164 setUrl (url: string) {
165 const parsed = new URL(url)
168 this.host = parsed.host
169 this.hostname = parsed.hostname
170 this.port = parseInt(parsed.port)
173 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
174 await ServersCommand.flushTests(this.internalServerNumber)
176 return this.run(configOverride, options)
179 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
180 // These actions are async so we need to be sure that they have both been done
181 const serverRunString = {
182 'HTTP server listening': false
184 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
185 serverRunString[key] = false
188 client_id: 'Client id: (.+)',
189 client_secret: 'Client secret: (.+)',
190 user_username: 'Username: (.+)',
191 user_password: 'User password: (.+)'
194 await this.assignCustomConfigFile()
196 const configOverride = this.buildConfigOverride()
198 if (configOverrideArg !== undefined) {
199 Object.assign(configOverride, configOverrideArg)
202 // Share the environment
203 const env = Object.create(process.env)
204 env['NODE_ENV'] = 'test'
205 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
206 env['NODE_CONFIG'] = JSON.stringify(configOverride)
209 Object.assign(env, options.env)
212 const forkOptions = {
216 execArgv: options.nodeArgs || []
219 return new Promise<void>((res, rej) => {
222 this.app = fork(join(root(), 'dist', 'server.js'), options.peertubeArgs || [], forkOptions)
224 const onExit = function () {
225 return rej(new Error('Process exited'))
228 this.app.on('exit', onExit)
230 this.app.stdout.on('data', function onStdout (data) {
231 let dontContinue = false
233 // Capture things if we want to
234 for (const key of Object.keys(regexps)) {
235 const regexp = regexps[key]
236 const matches = data.toString().match(regexp)
237 if (matches !== null) {
238 if (key === 'client_id') self.store.client.id = matches[1]
239 else if (key === 'client_secret') self.store.client.secret = matches[1]
240 else if (key === 'user_username') self.store.user.username = matches[1]
241 else if (key === 'user_password') self.store.user.password = matches[1]
245 // Check if all required sentences are here
246 for (const key of Object.keys(serverRunString)) {
247 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
248 if (serverRunString[key] === false) dontContinue = true
251 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
252 if (dontContinue === true) return
254 if (options.hideLogs === false) {
255 console.log(data.toString())
257 self.app.stdout.removeListener('data', onStdout)
258 self.app.removeListener('exit', onExit)
261 process.on('exit', () => {
263 process.kill(self.app.pid)
264 } catch { /* empty */ }
273 if (!this.app) return
275 await this.sql.cleanup()
277 process.kill(-this.app.pid)
282 private randomServer () {
286 return randomInt(low, high)
289 private randomRTMP () {
293 return randomInt(low, high)
296 private async assignCustomConfigFile () {
297 if (this.internalServerNumber === this.serverNumber) return
299 const basePath = join(root(), 'config')
301 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
302 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
304 this.customConfigFile = tmpConfigFile
307 private buildConfigOverride () {
308 if (!this.parallel) return {}
318 suffix: '_test' + this.internalServerNumber
321 tmp: `test${this.internalServerNumber}/tmp/`,
322 avatars: `test${this.internalServerNumber}/avatars/`,
323 videos: `test${this.internalServerNumber}/videos/`,
324 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
325 redundancy: `test${this.internalServerNumber}/redundancy/`,
326 logs: `test${this.internalServerNumber}/logs/`,
327 previews: `test${this.internalServerNumber}/previews/`,
328 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
329 torrents: `test${this.internalServerNumber}/torrents/`,
330 captions: `test${this.internalServerNumber}/captions/`,
331 cache: `test${this.internalServerNumber}/cache/`,
332 plugins: `test${this.internalServerNumber}/plugins/`
335 email: `admin${this.internalServerNumber}@example.com`
345 private assignCommands () {
346 this.bulk = new BulkCommand(this)
347 this.cli = new CLICommand(this)
348 this.customPage = new CustomPagesCommand(this)
349 this.feed = new FeedCommand(this)
350 this.logs = new LogsCommand(this)
351 this.abuses = new AbusesCommand(this)
352 this.overviews = new OverviewsCommand(this)
353 this.search = new SearchCommand(this)
354 this.contactForm = new ContactFormCommand(this)
355 this.debug = new DebugCommand(this)
356 this.follows = new FollowsCommand(this)
357 this.jobs = new JobsCommand(this)
358 this.plugins = new PluginsCommand(this)
359 this.redundancy = new RedundancyCommand(this)
360 this.stats = new StatsCommand(this)
361 this.config = new ConfigCommand(this)
362 this.socketIO = new SocketIOCommand(this)
363 this.accounts = new AccountsCommand(this)
364 this.blocklist = new BlocklistCommand(this)
365 this.subscriptions = new SubscriptionsCommand(this)
366 this.live = new LiveCommand(this)
367 this.services = new ServicesCommand(this)
368 this.blacklist = new BlacklistCommand(this)
369 this.captions = new CaptionsCommand(this)
370 this.changeOwnership = new ChangeOwnershipCommand(this)
371 this.playlists = new PlaylistsCommand(this)
372 this.history = new HistoryCommand(this)
373 this.imports = new ImportsCommand(this)
374 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
375 this.channels = new ChannelsCommand(this)
376 this.comments = new CommentsCommand(this)
377 this.sql = new SQLCommand(this)
378 this.notifications = new NotificationsCommand(this)
379 this.servers = new ServersCommand(this)
380 this.login = new LoginCommand(this)
381 this.users = new UsersCommand(this)
382 this.videos = new VideosCommand(this)
383 this.objectStorage = new ObjectStorageCommand(this)