]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
replace fs by fs-extra to prevent EMFILE error
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
CommitLineData
ecb4e35f 1import { createTransport, Transporter } from 'nodemailer'
ba75d268 2import { UserRight } from '../../shared/models/users'
ecb4e35f 3import { isTestInstance } from '../helpers/core-utils'
05e67d62 4import { bunyanLogger, logger } from '../helpers/logger'
ecb4e35f 5import { CONFIG } from '../initializers'
ba75d268
C
6import { UserModel } from '../models/account/user'
7import { VideoModel } from '../models/video/video'
ecb4e35f
C
8import { JobQueue } from './job-queue'
9import { EmailPayload } from './job-queue/handlers/email'
c9d5c64f 10import { readFileSync } from 'fs-extra'
ecb4e35f
C
11
12class Emailer {
13
14 private static instance: Emailer
15 private initialized = false
16 private transporter: Transporter
17
18 private constructor () {}
19
20 init () {
21 // Already initialized
22 if (this.initialized === true) return
23 this.initialized = true
24
25 if (CONFIG.SMTP.HOSTNAME && CONFIG.SMTP.PORT) {
26 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
27
28 let tls
29 if (CONFIG.SMTP.CA_FILE) {
30 tls = {
31 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
32 }
33 }
34
f076daa7
C
35 let auth
36 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
37 auth = {
38 user: CONFIG.SMTP.USERNAME,
39 pass: CONFIG.SMTP.PASSWORD
40 }
41 }
42
ecb4e35f
C
43 this.transporter = createTransport({
44 host: CONFIG.SMTP.HOSTNAME,
45 port: CONFIG.SMTP.PORT,
46 secure: CONFIG.SMTP.TLS,
05e67d62
C
47 debug: CONFIG.LOG.LEVEL === 'debug',
48 logger: bunyanLogger as any,
bebf2d89 49 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
ecb4e35f 50 tls,
f076daa7 51 auth
ecb4e35f
C
52 })
53 } else {
54 if (!isTestInstance()) {
55 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
56 }
57 }
58 }
59
60 async checkConnectionOrDie () {
61 if (!this.transporter) return
62
3d3441d6
C
63 logger.info('Testing SMTP server...')
64
ecb4e35f
C
65 try {
66 const success = await this.transporter.verify()
67 if (success !== true) this.dieOnConnectionFailure()
68
69 logger.info('Successfully connected to SMTP server.')
70 } catch (err) {
71 this.dieOnConnectionFailure(err)
72 }
73 }
74
75 addForgetPasswordEmailJob (to: string, resetPasswordUrl: string) {
76 const text = `Hi dear user,\n\n` +
77 `It seems you forgot your password on ${CONFIG.WEBSERVER.HOST}! ` +
37ddeba5 78 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
ecb4e35f
C
79 `If you are not the person who initiated this request, please ignore this email.\n\n` +
80 `Cheers,\n` +
81 `PeerTube.`
82
83 const emailPayload: EmailPayload = {
84 to: [ to ],
85 subject: 'Reset your PeerTube password',
86 text
87 }
88
89 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
90 }
91
eacb25c4 92 async addVideoAbuseReportJob (videoId: number) {
ba75d268 93 const video = await VideoModel.load(videoId)
c1e791ba 94 if (!video) throw new Error('Unknown Video id during Abuse report.')
ba75d268
C
95
96 const text = `Hi,\n\n` +
c1e791ba 97 `Your instance received an abuse for the following video ${video.url}\n\n` +
ba75d268
C
98 `Cheers,\n` +
99 `PeerTube.`
100
101 const to = await UserModel.listEmailsWithRight(UserRight.MANAGE_VIDEO_ABUSES)
102 const emailPayload: EmailPayload = {
103 to,
104 subject: '[PeerTube] Received a video abuse',
105 text
106 }
107
108 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
109 }
110
26b7305a
C
111 async addVideoBlacklistReportJob (videoId: number, reason?: string) {
112 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
113 if (!video) throw new Error('Unknown Video id during Blacklist report.')
114 // It's not our user
115 if (video.remote === true) return
116
117 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
118
119 const reasonString = reason ? ` for the following reason: ${reason}` : ''
120 const blockedString = `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
121
122 const text = 'Hi,\n\n' +
123 blockedString +
124 '\n\n' +
125 'Cheers,\n' +
126 `PeerTube.`
127
128 const to = user.email
129 const emailPayload: EmailPayload = {
130 to: [ to ],
131 subject: `[PeerTube] Video ${video.name} blacklisted`,
132 text
133 }
134
135 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
136 }
137
138 async addVideoUnblacklistReportJob (videoId: number) {
139 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
140 if (!video) throw new Error('Unknown Video id during Blacklist report.')
e5e7f7fe
C
141 // It's not our user
142 if (video.remote === true) return
26b7305a
C
143
144 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
145
146 const text = 'Hi,\n\n' +
147 `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
148 '\n\n' +
149 'Cheers,\n' +
150 `PeerTube.`
151
152 const to = user.email
153 const emailPayload: EmailPayload = {
154 to: [ to ],
155 subject: `[PeerTube] Video ${video.name} unblacklisted`,
156 text
157 }
158
159 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
160 }
161
eacb25c4
C
162 addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
163 const reasonString = reason ? ` for the following reason: ${reason}` : ''
164 const blockedWord = blocked ? 'blocked' : 'unblocked'
165 const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
166
167 const text = 'Hi,\n\n' +
168 blockedString +
169 '\n\n' +
170 'Cheers,\n' +
171 `PeerTube.`
172
173 const to = user.email
174 const emailPayload: EmailPayload = {
175 to: [ to ],
176 subject: '[PeerTube] Account ' + blockedWord,
177 text
178 }
179
180 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
181 }
182
ecb4e35f
C
183 sendMail (to: string[], subject: string, text: string) {
184 if (!this.transporter) {
185 throw new Error('Cannot send mail because SMTP is not configured.')
186 }
187
188 return this.transporter.sendMail({
189 from: CONFIG.SMTP.FROM_ADDRESS,
190 to: to.join(','),
191 subject,
192 text
193 })
194 }
195
196 private dieOnConnectionFailure (err?: Error) {
d5b7d911 197 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
198 process.exit(-1)
199 }
200
201 static get Instance () {
202 return this.instance || (this.instance = new this())
203 }
204}
205
206// ---------------------------------------------------------------------------
207
208export {
209 Emailer
210}