]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/server/server.ts
Translated using Weblate (Ukrainian)
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / server / server.ts
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'
18 import {
19 BlacklistCommand,
20 CaptionsCommand,
21 ChangeOwnershipCommand,
22 ChannelsCommand,
23 HistoryCommand,
24 ImportsCommand,
25 LiveCommand,
26 PlaylistsCommand,
27 ServicesCommand,
28 StreamingPlaylistsCommand,
29 VideosCommand
30 } from '../videos'
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'
42
43 export type RunServerOptions = {
44 hideLogs?: boolean
45 nodeArgs?: string[]
46 peertubeArgs?: string[]
47 env?: { [ id: string ]: string }
48 }
49
50 export class PeerTubeServer {
51 app?: ChildProcess
52
53 url: string
54 host?: string
55 hostname?: string
56 port?: number
57
58 rtmpPort?: number
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
80 video?: Video
81 videoCreated?: VideoCreateResult
82 videoDetails?: VideoDetails
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
126 objectStorage?: ObjectStorageCommand
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
157 this.port = 9000 + this.internalServerNumber
158
159 this.url = `http://localhost:${this.port}`
160 this.host = `localhost:${this.port}`
161 this.hostname = 'localhost'
162 }
163
164 setUrl (url: string) {
165 const parsed = new URL(url)
166
167 this.url = url
168 this.host = parsed.host
169 this.hostname = parsed.hostname
170 this.port = parseInt(parsed.port)
171 }
172
173 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
174 await ServersCommand.flushTests(this.internalServerNumber)
175
176 return this.run(configOverride, options)
177 }
178
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
183 }
184 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
185 serverRunString[key] = false
186
187 const regexps = {
188 client_id: 'Client id: (.+)',
189 client_secret: 'Client secret: (.+)',
190 user_username: 'Username: (.+)',
191 user_password: 'User password: (.+)'
192 }
193
194 await this.assignCustomConfigFile()
195
196 const configOverride = this.buildConfigOverride()
197
198 if (configOverrideArg !== undefined) {
199 Object.assign(configOverride, configOverrideArg)
200 }
201
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)
207
208 if (options.env) {
209 Object.assign(env, options.env)
210 }
211
212 const forkOptions = {
213 silent: true,
214 env,
215 detached: true,
216 execArgv: options.nodeArgs || []
217 }
218
219 return new Promise<void>((res, rej) => {
220 const self = this
221
222 this.app = fork(join(root(), 'dist', 'server.js'), options.peertubeArgs || [], forkOptions)
223
224 const onPeerTubeExit = () => rej(new Error('Process exited'))
225 const onParentExit = () => {
226 if (!this.app || !this.app.pid) return
227
228 try {
229 process.kill(self.app.pid)
230 } catch { /* empty */ }
231 }
232
233 this.app.on('exit', onPeerTubeExit)
234 process.on('exit', onParentExit)
235
236 this.app.stdout.on('data', function onStdout (data) {
237 let dontContinue = false
238
239 // Capture things if we want to
240 for (const key of Object.keys(regexps)) {
241 const regexp = regexps[key]
242 const matches = data.toString().match(regexp)
243 if (matches !== null) {
244 if (key === 'client_id') self.store.client.id = matches[1]
245 else if (key === 'client_secret') self.store.client.secret = matches[1]
246 else if (key === 'user_username') self.store.user.username = matches[1]
247 else if (key === 'user_password') self.store.user.password = matches[1]
248 }
249 }
250
251 // Check if all required sentences are here
252 for (const key of Object.keys(serverRunString)) {
253 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
254 if (serverRunString[key] === false) dontContinue = true
255 }
256
257 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
258 if (dontContinue === true) return
259
260 if (options.hideLogs === false) {
261 console.log(data.toString())
262 } else {
263 process.removeListener('exit', onParentExit)
264 self.app.stdout.removeListener('data', onStdout)
265 self.app.removeListener('exit', onPeerTubeExit)
266 }
267
268 res()
269 })
270 })
271 }
272
273 async kill () {
274 if (!this.app) return
275
276 await this.sql.cleanup()
277
278 process.kill(-this.app.pid)
279
280 this.app = null
281 }
282
283 private randomServer () {
284 const low = 10
285 const high = 10000
286
287 return randomInt(low, high)
288 }
289
290 private randomRTMP () {
291 const low = 1900
292 const high = 2100
293
294 return randomInt(low, high)
295 }
296
297 private async assignCustomConfigFile () {
298 if (this.internalServerNumber === this.serverNumber) return
299
300 const basePath = join(root(), 'config')
301
302 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
303 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
304
305 this.customConfigFile = tmpConfigFile
306 }
307
308 private buildConfigOverride () {
309 if (!this.parallel) return {}
310
311 return {
312 listen: {
313 port: this.port
314 },
315 webserver: {
316 port: this.port
317 },
318 database: {
319 suffix: '_test' + this.internalServerNumber
320 },
321 storage: {
322 tmp: `test${this.internalServerNumber}/tmp/`,
323 avatars: `test${this.internalServerNumber}/avatars/`,
324 videos: `test${this.internalServerNumber}/videos/`,
325 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
326 redundancy: `test${this.internalServerNumber}/redundancy/`,
327 logs: `test${this.internalServerNumber}/logs/`,
328 previews: `test${this.internalServerNumber}/previews/`,
329 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
330 torrents: `test${this.internalServerNumber}/torrents/`,
331 captions: `test${this.internalServerNumber}/captions/`,
332 cache: `test${this.internalServerNumber}/cache/`,
333 plugins: `test${this.internalServerNumber}/plugins/`
334 },
335 admin: {
336 email: `admin${this.internalServerNumber}@example.com`
337 },
338 live: {
339 rtmp: {
340 port: this.rtmpPort
341 }
342 }
343 }
344 }
345
346 private assignCommands () {
347 this.bulk = new BulkCommand(this)
348 this.cli = new CLICommand(this)
349 this.customPage = new CustomPagesCommand(this)
350 this.feed = new FeedCommand(this)
351 this.logs = new LogsCommand(this)
352 this.abuses = new AbusesCommand(this)
353 this.overviews = new OverviewsCommand(this)
354 this.search = new SearchCommand(this)
355 this.contactForm = new ContactFormCommand(this)
356 this.debug = new DebugCommand(this)
357 this.follows = new FollowsCommand(this)
358 this.jobs = new JobsCommand(this)
359 this.plugins = new PluginsCommand(this)
360 this.redundancy = new RedundancyCommand(this)
361 this.stats = new StatsCommand(this)
362 this.config = new ConfigCommand(this)
363 this.socketIO = new SocketIOCommand(this)
364 this.accounts = new AccountsCommand(this)
365 this.blocklist = new BlocklistCommand(this)
366 this.subscriptions = new SubscriptionsCommand(this)
367 this.live = new LiveCommand(this)
368 this.services = new ServicesCommand(this)
369 this.blacklist = new BlacklistCommand(this)
370 this.captions = new CaptionsCommand(this)
371 this.changeOwnership = new ChangeOwnershipCommand(this)
372 this.playlists = new PlaylistsCommand(this)
373 this.history = new HistoryCommand(this)
374 this.imports = new ImportsCommand(this)
375 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
376 this.channels = new ChannelsCommand(this)
377 this.comments = new CommentsCommand(this)
378 this.sql = new SQLCommand(this)
379 this.notifications = new NotificationsCommand(this)
380 this.servers = new ServersCommand(this)
381 this.login = new LoginCommand(this)
382 this.users = new UsersCommand(this)
383 this.videos = new VideosCommand(this)
384 this.objectStorage = new ObjectStorageCommand(this)
385 }
386 }