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