]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/miscs/email.ts
Add ability for plugins to specify scale filter
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / miscs / email.ts
1 import { ChildProcess, fork } from 'child_process'
2 import { join } from 'path'
3 import { randomInt } from '../../core-utils/miscs/miscs'
4 import { parallelTests } from '../server/servers'
5
6 class MockSmtpServer {
7
8 private static instance: MockSmtpServer
9 private started = false
10 private emailChildProcess: ChildProcess
11 private emails: object[]
12
13 private constructor () {
14 this.emailChildProcess = fork(join(__dirname, 'email-child-process'), [])
15
16 this.emailChildProcess.on('message', (msg: any) => {
17 if (msg.email) {
18 return this.emails.push(msg.email)
19 }
20 })
21
22 process.on('exit', () => this.kill())
23 }
24
25 collectEmails (emailsCollection: object[]) {
26 return new Promise<number>((res, rej) => {
27 const port = parallelTests() ? randomInt(1000, 2000) : 1025
28
29 if (this.started) {
30 this.emails = emailsCollection
31 return res(undefined)
32 }
33
34 // ensure maildev isn't started until
35 // unexpected exit can be reported to test runner
36 this.emailChildProcess.send({ start: true, port })
37 this.emailChildProcess.on('exit', () => {
38 return rej(new Error('maildev exited unexpectedly, confirm port not in use'))
39 })
40 this.emailChildProcess.on('message', (msg: any) => {
41 if (msg.err) return rej(new Error(msg.err))
42
43 this.started = true
44 this.emails = emailsCollection
45
46 return res(port)
47 })
48 })
49 }
50
51 kill () {
52 if (!this.emailChildProcess) return
53
54 process.kill(this.emailChildProcess.pid)
55
56 this.emailChildProcess = null
57 MockSmtpServer.instance = null
58 }
59
60 static get Instance () {
61 return this.instance || (this.instance = new this())
62 }
63 }
64
65 // ---------------------------------------------------------------------------
66
67 export {
68 MockSmtpServer
69 }