]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/server-commands/mock-servers/mock-email.ts
shared/ typescript types dir server-commands
[github/Chocobozzz/PeerTube.git] / shared / server-commands / mock-servers / mock-email.ts
1 import { ChildProcess } from 'child_process'
2 import MailDev from '@peertube/maildev'
3 import { randomInt } from '@shared/core-utils'
4 import { parallelTests } from '../miscs'
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
15 collectEmails (emailsCollection: object[]) {
16 return new Promise<number>((res, rej) => {
17 const port = parallelTests() ? randomInt(1000, 2000) : 1025
18 this.emails = emailsCollection
19
20 if (this.started) {
21 return res(undefined)
22 }
23
24 const maildev = new MailDev({
25 ip: '127.0.0.1',
26 smtp: port,
27 disableWeb: true,
28 silent: true
29 })
30
31 maildev.on('new', email => {
32 this.emails.push(email)
33 })
34
35 maildev.listen(err => {
36 if (err) return rej(err)
37
38 this.started = true
39
40 return res(port)
41 })
42 })
43 }
44
45 kill () {
46 if (!this.emailChildProcess) return
47
48 process.kill(this.emailChildProcess.pid)
49
50 this.emailChildProcess = null
51 MockSmtpServer.instance = null
52 }
53
54 static get Instance () {
55 return this.instance || (this.instance = new this())
56 }
57 }
58
59 // ---------------------------------------------------------------------------
60
61 export {
62 MockSmtpServer
63 }