]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
fe57a3e4caf5108e3a45a03e21df766a694d1da9
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { createTransport, Transporter } from 'nodemailer'
2 import { isTestInstance } from '../helpers/core-utils'
3 import { bunyanLogger, logger } from '../helpers/logger'
4 import { CONFIG } from '../initializers/config'
5 import { UserModel } from '../models/account/user'
6 import { JobQueue } from './job-queue'
7 import { EmailPayload } from './job-queue/handlers/email'
8 import { readFileSync } from 'fs-extra'
9 import { VideoBlacklistModel } from '../models/video/video-blacklist'
10 import { WEBSERVER } from '../initializers/constants'
11 import { MCommentOwnerVideo, MVideo, MVideoAbuseVideo, MVideoAccountLight, MVideoBlacklistVideo } from '../typings/models/video'
12 import { MActorFollowActors, MActorFollowFull, MUser } from '../typings/models'
13 import { MVideoImport, MVideoImportVideo } from '@server/typings/models/video/video-import'
14
15 type SendEmailOptions = {
16 to: string[]
17 subject: string
18 text: string
19
20 fromDisplayName?: string
21 replyTo?: string
22 }
23
24 class Emailer {
25
26 private static instance: Emailer
27 private initialized = false
28 private transporter: Transporter
29
30 private constructor () {}
31
32 init () {
33 // Already initialized
34 if (this.initialized === true) return
35 this.initialized = true
36
37 if (Emailer.isEnabled()) {
38 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
39
40 let tls
41 if (CONFIG.SMTP.CA_FILE) {
42 tls = {
43 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
44 }
45 }
46
47 let auth
48 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
49 auth = {
50 user: CONFIG.SMTP.USERNAME,
51 pass: CONFIG.SMTP.PASSWORD
52 }
53 }
54
55 this.transporter = createTransport({
56 host: CONFIG.SMTP.HOSTNAME,
57 port: CONFIG.SMTP.PORT,
58 secure: CONFIG.SMTP.TLS,
59 debug: CONFIG.LOG.LEVEL === 'debug',
60 logger: bunyanLogger as any,
61 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
62 tls,
63 auth
64 })
65 } else {
66 if (!isTestInstance()) {
67 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
68 }
69 }
70 }
71
72 static isEnabled () {
73 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
74 }
75
76 async checkConnectionOrDie () {
77 if (!this.transporter) return
78
79 logger.info('Testing SMTP server...')
80
81 try {
82 const success = await this.transporter.verify()
83 if (success !== true) this.dieOnConnectionFailure()
84
85 logger.info('Successfully connected to SMTP server.')
86 } catch (err) {
87 this.dieOnConnectionFailure(err)
88 }
89 }
90
91 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
92 const channelName = video.VideoChannel.getDisplayName()
93 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
94
95 const text = `Hi dear user,\n\n` +
96 `Your subscription ${channelName} just published a new video: ${video.name}` +
97 `\n\n` +
98 `You can view it on ${videoUrl} ` +
99 `\n\n` +
100 `Cheers,\n` +
101 `${CONFIG.EMAIL.BODY.SIGNATURE}`
102
103 const emailPayload: EmailPayload = {
104 to,
105 subject: CONFIG.EMAIL.OBJECT.PREFIX + channelName + ' just published a new video',
106 text
107 }
108
109 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
110 }
111
112 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
113 const followerName = actorFollow.ActorFollower.Account.getDisplayName()
114 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
115
116 const text = `Hi dear user,\n\n` +
117 `Your ${followType} ${followingName} has a new subscriber: ${followerName}` +
118 `\n\n` +
119 `Cheers,\n` +
120 `${CONFIG.EMAIL.BODY.SIGNATURE}`
121
122 const emailPayload: EmailPayload = {
123 to,
124 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'New follower on your channel ' + followingName,
125 text
126 }
127
128 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
129 }
130
131 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
132 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
133
134 const text = `Hi dear admin,\n\n` +
135 `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
136 `\n\n` +
137 `Cheers,\n` +
138 `${CONFIG.EMAIL.BODY.SIGNATURE}`
139
140 const emailPayload: EmailPayload = {
141 to,
142 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'New instance follower',
143 text
144 }
145
146 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
147 }
148
149 myVideoPublishedNotification (to: string[], video: MVideo) {
150 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
151
152 const text = `Hi dear user,\n\n` +
153 `Your video ${video.name} has been published.` +
154 `\n\n` +
155 `You can view it on ${videoUrl} ` +
156 `\n\n` +
157 `Cheers,\n` +
158 `${CONFIG.EMAIL.BODY.SIGNATURE}`
159
160 const emailPayload: EmailPayload = {
161 to,
162 subject: CONFIG.EMAIL.OBJECT.PREFIX + `Your video ${video.name} is published`,
163 text
164 }
165
166 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
167 }
168
169 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
170 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
171
172 const text = `Hi dear user,\n\n` +
173 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
174 `\n\n` +
175 `You can view the imported video on ${videoUrl} ` +
176 `\n\n` +
177 `Cheers,\n` +
178 `${CONFIG.EMAIL.BODY.SIGNATURE}`
179
180 const emailPayload: EmailPayload = {
181 to,
182 subject: CONFIG.EMAIL.OBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} is finished`,
183 text
184 }
185
186 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
187 }
188
189 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
190 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
191
192 const text = `Hi dear user,\n\n` +
193 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
194 `\n\n` +
195 `See your videos import dashboard for more information: ${importUrl}` +
196 `\n\n` +
197 `Cheers,\n` +
198 `${CONFIG.EMAIL.BODY.SIGNATURE}`
199
200 const emailPayload: EmailPayload = {
201 to,
202 subject: CONFIG.EMAIL.OBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
203 text
204 }
205
206 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
207 }
208
209 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
210 const accountName = comment.Account.getDisplayName()
211 const video = comment.Video
212 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
213
214 const text = `Hi dear user,\n\n` +
215 `A new comment has been posted by ${accountName} on your video ${video.name}` +
216 `\n\n` +
217 `You can view it on ${commentUrl} ` +
218 `\n\n` +
219 `Cheers,\n` +
220 `${CONFIG.EMAIL.BODY.SIGNATURE}`
221
222 const emailPayload: EmailPayload = {
223 to,
224 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'New comment on your video ' + video.name,
225 text
226 }
227
228 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
229 }
230
231 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
232 const accountName = comment.Account.getDisplayName()
233 const video = comment.Video
234 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
235
236 const text = `Hi dear user,\n\n` +
237 `${accountName} mentioned you on video ${video.name}` +
238 `\n\n` +
239 `You can view the comment on ${commentUrl} ` +
240 `\n\n` +
241 `Cheers,\n` +
242 `${CONFIG.EMAIL.BODY.SIGNATURE}`
243
244 const emailPayload: EmailPayload = {
245 to,
246 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'Mention on video ' + video.name,
247 text
248 }
249
250 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
251 }
252
253 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: MVideoAbuseVideo) {
254 const videoUrl = WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
255
256 const text = `Hi,\n\n` +
257 `${WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` +
258 `Cheers,\n` +
259 `${CONFIG.EMAIL.BODY.SIGNATURE}`
260
261 const emailPayload: EmailPayload = {
262 to,
263 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'Received a video abuse',
264 text
265 }
266
267 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
268 }
269
270 addVideoAutoBlacklistModeratorsNotification (to: string[], video: MVideo) {
271 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
272 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
273
274 const text = `Hi,\n\n` +
275 `A recently added video was auto-blacklisted and requires moderator review before publishing.` +
276 `\n\n` +
277 `You can view it and take appropriate action on ${videoUrl}` +
278 `\n\n` +
279 `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` +
280 `\n\n` +
281 `Cheers,\n` +
282 `${CONFIG.EMAIL.BODY.SIGNATURE}`
283
284 const emailPayload: EmailPayload = {
285 to,
286 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'An auto-blacklisted video is awaiting review',
287 text
288 }
289
290 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
291 }
292
293 addNewUserRegistrationNotification (to: string[], user: MUser) {
294 const text = `Hi,\n\n` +
295 `User ${user.username} just registered on ${WEBSERVER.HOST} PeerTube instance.\n\n` +
296 `Cheers,\n` +
297 `${CONFIG.EMAIL.BODY.SIGNATURE}`
298
299 const emailPayload: EmailPayload = {
300 to,
301 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'New user registration on ' + WEBSERVER.HOST,
302 text
303 }
304
305 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
306 }
307
308 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
309 const videoName = videoBlacklist.Video.name
310 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
311
312 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
313 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
314
315 const text = 'Hi,\n\n' +
316 blockedString +
317 '\n\n' +
318 'Cheers,\n' +
319 `${CONFIG.EMAIL.BODY.SIGNATURE}`
320
321 const emailPayload: EmailPayload = {
322 to,
323 subject: CONFIG.EMAIL.OBJECT.PREFIX + `Video ${videoName} blacklisted`,
324 text
325 }
326
327 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
328 }
329
330 addVideoUnblacklistNotification (to: string[], video: MVideo) {
331 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
332
333 const text = 'Hi,\n\n' +
334 `Your video ${video.name} (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.` +
335 '\n\n' +
336 'Cheers,\n' +
337 `${CONFIG.EMAIL.BODY.SIGNATURE}`
338
339 const emailPayload: EmailPayload = {
340 to,
341 subject: CONFIG.EMAIL.OBJECT.PREFIX + `Video ${video.name} unblacklisted`,
342 text
343 }
344
345 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
346 }
347
348 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
349 const text = `Hi dear user,\n\n` +
350 `A reset password procedure for your account ${to} has been requested on ${WEBSERVER.HOST} ` +
351 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
352 `If you are not the person who initiated this request, please ignore this email.\n\n` +
353 `Cheers,\n` +
354 `${CONFIG.EMAIL.BODY.SIGNATURE}`
355
356 const emailPayload: EmailPayload = {
357 to: [ to ],
358 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'Reset your password',
359 text
360 }
361
362 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
363 }
364
365 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
366 const text = `Welcome to PeerTube,\n\n` +
367 `To start using PeerTube on ${WEBSERVER.HOST} you must verify your email! ` +
368 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
369 `If you are not the person who initiated this request, please ignore this email.\n\n` +
370 `Cheers,\n` +
371 `${CONFIG.EMAIL.BODY.SIGNATURE}`
372
373 const emailPayload: EmailPayload = {
374 to: [ to ],
375 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'Verify your email',
376 text
377 }
378
379 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
380 }
381
382 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
383 const reasonString = reason ? ` for the following reason: ${reason}` : ''
384 const blockedWord = blocked ? 'blocked' : 'unblocked'
385 const blockedString = `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
386
387 const text = 'Hi,\n\n' +
388 blockedString +
389 '\n\n' +
390 'Cheers,\n' +
391 `${CONFIG.EMAIL.BODY.SIGNATURE}`
392
393 const to = user.email
394 const emailPayload: EmailPayload = {
395 to: [ to ],
396 subject: CONFIG.EMAIL.OBJECT.PREFIX + 'Account ' + blockedWord,
397 text
398 }
399
400 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
401 }
402
403 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
404 const text = 'Hello dear admin,\n\n' +
405 fromName + ' sent you a message' +
406 '\n\n---------------------------------------\n\n' +
407 body +
408 '\n\n---------------------------------------\n\n' +
409 'Cheers,\n' +
410 'PeerTube.'
411
412 const emailPayload: EmailPayload = {
413 fromDisplayName: fromEmail,
414 replyTo: fromEmail,
415 to: [ CONFIG.ADMIN.EMAIL ],
416 subject: CONFIG.EMAIL.OBJECT.PREFIX + subject,
417 text
418 }
419
420 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
421 }
422
423 sendMail (options: EmailPayload) {
424 if (!Emailer.isEnabled()) {
425 throw new Error('Cannot send mail because SMTP is not configured.')
426 }
427
428 const fromDisplayName = options.fromDisplayName
429 ? options.fromDisplayName
430 : WEBSERVER.HOST
431
432 return this.transporter.sendMail({
433 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
434 replyTo: options.replyTo,
435 to: options.to.join(','),
436 subject: options.subject,
437 text: options.text
438 })
439 }
440
441 private dieOnConnectionFailure (err?: Error) {
442 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
443 process.exit(-1)
444 }
445
446 static get Instance () {
447 return this.instance || (this.instance = new this())
448 }
449 }
450
451 // ---------------------------------------------------------------------------
452
453 export {
454 Emailer,
455 SendEmailOptions
456 }