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