Remove tmp file on image processing error
[oweals/peertube.git] / shared / utils / miscs / email.ts
1 import { fork, ChildProcess } from 'child_process'
2
3 class MockSmtpServer {
4
5   private static instance: MockSmtpServer
6   private started = false
7   private emailChildProcess: ChildProcess
8   private emails: object[]
9
10   private constructor () {
11     this.emailChildProcess = fork(`${__dirname}/email-child-process`, [])
12
13     this.emailChildProcess.on('message', (msg) => {
14       if (msg.email) {
15         return this.emails.push(msg.email)
16       }
17     })
18
19     process.on('exit', () => this.kill())
20   }
21
22   collectEmails (emailsCollection: object[]) {
23     return new Promise((res, rej) => {
24       if (this.started) {
25         this.emails = emailsCollection
26         return res()
27       }
28
29       // ensure maildev isn't started until
30       // unexpected exit can be reported to test runner
31       this.emailChildProcess.send({ start: true })
32       this.emailChildProcess.on('exit', () => {
33         return rej(new Error('maildev exited unexpectedly, confirm port not in use'))
34       })
35       this.emailChildProcess.on('message', (msg) => {
36         if (msg.err) {
37           return rej(new Error(msg.err))
38         }
39         this.started = true
40         this.emails = emailsCollection
41         return res()
42       })
43     })
44   }
45
46   kill () {
47     if (!this.emailChildProcess) return
48
49     process.kill(this.emailChildProcess.pid)
50
51     this.emailChildProcess = null
52     MockSmtpServer.instance = null
53   }
54
55   static get Instance () {
56     return this.instance || (this.instance = new this())
57   }
58 }
59
60 // ---------------------------------------------------------------------------
61
62 export {
63   MockSmtpServer
64 }