]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
Fix embed url
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
CommitLineData
ecb4e35f 1import { createTransport, Transporter } from 'nodemailer'
df4c603d 2import { isTestInstance, root } from '../helpers/core-utils'
05e67d62 3import { bunyanLogger, logger } from '../helpers/logger'
4c1c1709 4import { CONFIG, isEmailEnabled } from '../initializers/config'
ecb4e35f 5import { JobQueue } from './job-queue'
c9d5c64f 6import { readFileSync } from 'fs-extra'
6dd9de95 7import { WEBSERVER } from '../initializers/constants'
8424c402
C
8import {
9 MCommentOwnerVideo,
10 MVideo,
11 MVideoAbuseVideo,
12 MVideoAccountLight,
13 MVideoBlacklistLightVideo,
14 MVideoBlacklistVideo
26d6bf65
C
15} from '../types/models/video'
16import { MActorFollowActors, MActorFollowFull, MUser } from '../types/models'
17import { MVideoImport, MVideoImportVideo } from '@server/types/models/video/video-import'
8dc8a34e 18import { EmailPayload } from '@shared/models'
df4c603d
RK
19import { join } from 'path'
20import { VideoAbuse } from '../../shared/models/videos'
21import { SendEmailOptions } from '../../shared/models/server/emailer.model'
22import { merge } from 'lodash'
23import { VideoChannelModel } from '@server/models/video/video-channel'
24const Email = require('email-templates')
dee77e76 25
ecb4e35f
C
26class Emailer {
27
28 private static instance: Emailer
29 private initialized = false
30 private transporter: Transporter
31
a1587156
C
32 private constructor () {
33 }
ecb4e35f
C
34
35 init () {
36 // Already initialized
37 if (this.initialized === true) return
38 this.initialized = true
39
887e1a03 40 if (isEmailEnabled()) {
ed3f089c
IB
41 if (CONFIG.SMTP.TRANSPORT === 'smtp') {
42 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
43
44 let tls
45 if (CONFIG.SMTP.CA_FILE) {
46 tls = {
47 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
48 }
ecb4e35f 49 }
ecb4e35f 50
ed3f089c
IB
51 let auth
52 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
53 auth = {
54 user: CONFIG.SMTP.USERNAME,
55 pass: CONFIG.SMTP.PASSWORD
56 }
f076daa7 57 }
f076daa7 58
ed3f089c
IB
59 this.transporter = createTransport({
60 host: CONFIG.SMTP.HOSTNAME,
61 port: CONFIG.SMTP.PORT,
62 secure: CONFIG.SMTP.TLS,
63 debug: CONFIG.LOG.LEVEL === 'debug',
64 logger: bunyanLogger as any,
65 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
66 tls,
67 auth
68 })
69 } else { // sendmail
70 logger.info('Using sendmail to send emails')
71
72 this.transporter = createTransport({
73 sendmail: true,
74 newline: 'unix',
9afa0901 75 path: CONFIG.SMTP.SENDMAIL
ed3f089c
IB
76 })
77 }
ecb4e35f
C
78 } else {
79 if (!isTestInstance()) {
80 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
81 }
82 }
83 }
84
d3e56c0c 85 static isEnabled () {
ed3f089c
IB
86 if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
87 return !!CONFIG.SMTP.SENDMAIL
88 } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
89 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
90 } else {
91 return false
92 }
3b3b1820
C
93 }
94
ecb4e35f 95 async checkConnectionOrDie () {
ed3f089c 96 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
ecb4e35f 97
3d3441d6
C
98 logger.info('Testing SMTP server...')
99
ecb4e35f
C
100 try {
101 const success = await this.transporter.verify()
102 if (success !== true) this.dieOnConnectionFailure()
103
104 logger.info('Successfully connected to SMTP server.')
105 } catch (err) {
106 this.dieOnConnectionFailure(err)
107 }
108 }
109
453e83ea 110 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
cef534ed 111 const channelName = video.VideoChannel.getDisplayName()
6dd9de95 112 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
cef534ed 113
ecb4e35f 114 const emailPayload: EmailPayload = {
cef534ed 115 to,
df4c603d
RK
116 subject: channelName + ' just published a new video',
117 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
118 locals: {
119 title: 'New content ',
120 action: {
121 text: 'View video',
122 url: videoUrl
123 }
124 }
ecb4e35f
C
125 }
126
127 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
128 }
129
8424c402 130 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
f7cc67b4
C
131 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
132
f7cc67b4 133 const emailPayload: EmailPayload = {
df4c603d 134 template: 'follower-on-channel',
f7cc67b4 135 to,
df4c603d
RK
136 subject: `New follower on your channel ${followingName}`,
137 locals: {
138 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
139 followerUrl: actorFollow.ActorFollower.url,
140 followingName,
141 followingUrl: actorFollow.ActorFollowing.url,
142 followType
143 }
f7cc67b4
C
144 }
145
146 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
147 }
148
453e83ea 149 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
883993c8
C
150 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
151
883993c8
C
152 const emailPayload: EmailPayload = {
153 to,
df4c603d
RK
154 subject: 'New instance follower',
155 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
156 locals: {
157 title: 'New instance follower',
158 action: {
159 text: 'Review followers',
160 url: WEBSERVER.URL + '/admin/follows/followers-list'
161 }
162 }
883993c8
C
163 }
164
165 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
166 }
167
8424c402 168 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
df4c603d 169 const instanceUrl = actorFollow.ActorFollowing.url
8424c402
C
170 const emailPayload: EmailPayload = {
171 to,
df4c603d
RK
172 subject: 'Auto instance following',
173 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
8424c402
C
174 }
175
176 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
177 }
178
453e83ea 179 myVideoPublishedNotification (to: string[], video: MVideo) {
6dd9de95 180 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
dc133480 181
dc133480
C
182 const emailPayload: EmailPayload = {
183 to,
df4c603d
RK
184 subject: `Your video ${video.name} has been published`,
185 text: `Your video "${video.name}" has been published.`,
186 locals: {
187 title: 'You video is live',
188 action: {
189 text: 'View video',
190 url: videoUrl
191 }
192 }
dc133480
C
193 }
194
195 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
196 }
197
453e83ea 198 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
6dd9de95 199 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
dc133480 200
dc133480
C
201 const emailPayload: EmailPayload = {
202 to,
df4c603d
RK
203 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
204 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
205 locals: {
206 title: 'Import complete',
207 action: {
208 text: 'View video',
209 url: videoUrl
210 }
211 }
dc133480
C
212 }
213
214 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
215 }
216
453e83ea 217 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
6dd9de95 218 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
dc133480 219
df4c603d
RK
220 const text =
221 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
a1587156 222 '\n\n' +
df4c603d 223 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
dc133480
C
224
225 const emailPayload: EmailPayload = {
226 to,
df4c603d
RK
227 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
228 text,
229 locals: {
230 title: 'Import failed',
231 action: {
232 text: 'Review imports',
233 url: importUrl
234 }
235 }
dc133480
C
236 }
237
238 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
239 }
240
453e83ea 241 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
cef534ed 242 const video = comment.Video
df4c603d 243 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
6dd9de95 244 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
cef534ed 245
d9eaee39 246 const emailPayload: EmailPayload = {
df4c603d 247 template: 'video-comment-new',
cef534ed 248 to,
df4c603d
RK
249 subject: 'New comment on your video ' + video.name,
250 locals: {
251 accountName: comment.Account.getDisplayName(),
252 accountUrl: comment.Account.Actor.url,
253 comment,
254 video,
255 videoUrl,
256 action: {
257 text: 'View comment',
258 url: commentUrl
259 }
260 }
d9eaee39
JM
261 }
262
263 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
264 }
265
453e83ea 266 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
f7cc67b4
C
267 const accountName = comment.Account.getDisplayName()
268 const video = comment.Video
df4c603d 269 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
6dd9de95 270 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
f7cc67b4 271
f7cc67b4 272 const emailPayload: EmailPayload = {
df4c603d 273 template: 'video-comment-mention',
f7cc67b4 274 to,
df4c603d
RK
275 subject: 'Mention on video ' + video.name,
276 locals: {
277 comment,
278 video,
279 videoUrl,
280 accountName,
281 action: {
282 text: 'View comment',
283 url: commentUrl
284 }
285 }
f7cc67b4
C
286 }
287
288 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
289 }
290
df4c603d
RK
291 addVideoAbuseModeratorsNotification (to: string[], parameters: {
292 videoAbuse: VideoAbuse
293 videoAbuseInstance: MVideoAbuseVideo
294 reporter: string
295 }) {
296 const videoAbuseUrl = WEBSERVER.URL + '/admin/moderation/video-abuses/list?search=%23' + parameters.videoAbuse.id
297 const videoUrl = WEBSERVER.URL + parameters.videoAbuseInstance.Video.getWatchStaticPath()
ba75d268 298
ba75d268 299 const emailPayload: EmailPayload = {
df4c603d 300 template: 'video-abuse-new',
ba75d268 301 to,
df4c603d
RK
302 subject: `New video abuse report from ${parameters.reporter}`,
303 locals: {
304 videoUrl,
305 videoAbuseUrl,
306 videoCreatedAt: new Date(parameters.videoAbuseInstance.Video.createdAt).toLocaleString(),
307 videoPublishedAt: new Date(parameters.videoAbuseInstance.Video.publishedAt).toLocaleString(),
308 videoAbuse: parameters.videoAbuse,
309 reporter: parameters.reporter,
310 action: {
311 text: 'View report #' + parameters.videoAbuse.id,
312 url: videoAbuseUrl
313 }
314 }
ba75d268
C
315 }
316
317 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
318 }
319
df4c603d 320 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
6dd9de95 321 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
8424c402 322 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
df4c603d 323 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
7ccddd7b
JM
324
325 const emailPayload: EmailPayload = {
df4c603d 326 template: 'video-auto-blacklist-new',
7ccddd7b 327 to,
df4c603d
RK
328 subject: 'A new video is pending moderation',
329 locals: {
330 channel,
331 videoUrl,
332 videoName: videoBlacklist.Video.name,
333 action: {
334 text: 'Review autoblacklist',
335 url: VIDEO_AUTO_BLACKLIST_URL
336 }
337 }
7ccddd7b
JM
338 }
339
340 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
341 }
342
453e83ea 343 addNewUserRegistrationNotification (to: string[], user: MUser) {
f7cc67b4 344 const emailPayload: EmailPayload = {
df4c603d 345 template: 'user-registered',
f7cc67b4 346 to,
df4c603d
RK
347 subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
348 locals: {
349 user
350 }
f7cc67b4
C
351 }
352
353 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
354 }
355
453e83ea 356 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
cef534ed 357 const videoName = videoBlacklist.Video.name
6dd9de95 358 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
26b7305a 359
cef534ed 360 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
6dd9de95 361 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
26b7305a 362
26b7305a 363 const emailPayload: EmailPayload = {
cef534ed 364 to,
df4c603d
RK
365 subject: `Video ${videoName} blacklisted`,
366 text: blockedString,
367 locals: {
368 title: 'Your video was blacklisted'
369 }
26b7305a
C
370 }
371
372 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
373 }
374
453e83ea 375 addVideoUnblacklistNotification (to: string[], video: MVideo) {
6dd9de95 376 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
26b7305a 377
26b7305a 378 const emailPayload: EmailPayload = {
cef534ed 379 to,
df4c603d
RK
380 subject: `Video ${video.name} unblacklisted`,
381 text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
382 locals: {
383 title: 'Your video was unblacklisted'
384 }
26b7305a
C
385 }
386
387 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
388 }
389
b426edd4 390 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
cef534ed 391 const emailPayload: EmailPayload = {
df4c603d 392 template: 'password-reset',
cef534ed 393 to: [ to ],
df4c603d
RK
394 subject: 'Reset your account password',
395 locals: {
396 resetPasswordUrl
397 }
cef534ed
C
398 }
399
400 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
401 }
402
df4c603d 403 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
45f1bd72 404 const emailPayload: EmailPayload = {
df4c603d 405 template: 'password-create',
45f1bd72 406 to: [ to ],
df4c603d
RK
407 subject: 'Create your account password',
408 locals: {
409 username,
410 createPasswordUrl
411 }
45f1bd72
JL
412 }
413
414 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
415 }
416
cef534ed 417 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
cef534ed 418 const emailPayload: EmailPayload = {
df4c603d 419 template: 'verify-email',
cef534ed 420 to: [ to ],
df4c603d
RK
421 subject: `Verify your email on ${WEBSERVER.HOST}`,
422 locals: {
423 verifyEmailUrl
424 }
cef534ed
C
425 }
426
427 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
428 }
429
453e83ea 430 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
eacb25c4
C
431 const reasonString = reason ? ` for the following reason: ${reason}` : ''
432 const blockedWord = blocked ? 'blocked' : 'unblocked'
eacb25c4
C
433
434 const to = user.email
435 const emailPayload: EmailPayload = {
436 to: [ to ],
df4c603d
RK
437 subject: 'Account ' + blockedWord,
438 text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
eacb25c4
C
439 }
440
441 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
442 }
443
4e9fa5b7 444 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
a4101923 445 const emailPayload: EmailPayload = {
df4c603d 446 template: 'contact-form',
a4101923 447 to: [ CONFIG.ADMIN.EMAIL ],
df4c603d
RK
448 replyTo: `"${fromName}" <${fromEmail}>`,
449 subject: `(contact form) ${subject}`,
450 locals: {
451 fromName,
452 fromEmail,
453 body
454 }
a4101923
C
455 }
456
457 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
458 }
459
47f6cb31 460 async sendMail (options: EmailPayload) {
4c1c1709 461 if (!isEmailEnabled()) {
ecb4e35f
C
462 throw new Error('Cannot send mail because SMTP is not configured.')
463 }
464
df4c603d
RK
465 const fromDisplayName = options.from
466 ? options.from
6dd9de95 467 : WEBSERVER.HOST
4759fedc 468
df4c603d
RK
469 const email = new Email({
470 send: true,
471 message: {
472 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
473 },
474 transport: this.transporter,
475 views: {
03fc1928 476 root: join(root(), 'dist', 'server', 'lib', 'emails')
df4c603d
RK
477 },
478 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
479 })
480
47f6cb31 481 for (const to of options.to) {
df4c603d
RK
482 await email
483 .send(merge(
484 {
485 template: 'common',
486 message: {
487 to,
488 from: options.from,
489 subject: options.subject,
490 replyTo: options.replyTo
491 },
492 locals: { // default variables available in all templates
493 WEBSERVER,
494 EMAIL: CONFIG.EMAIL,
495 text: options.text,
496 subject: options.subject
497 }
498 },
499 options // overriden/new variables given for a specific template in the payload
500 ) as SendEmailOptions)
03fc1928
C
501 .then(res => logger.debug('Sent email.', { res }))
502 .catch(err => logger.error('Error in email sender.', { err }))
47f6cb31 503 }
ecb4e35f
C
504 }
505
506 private dieOnConnectionFailure (err?: Error) {
d5b7d911 507 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
508 process.exit(-1)
509 }
510
511 static get Instance () {
512 return this.instance || (this.instance = new this())
513 }
514}
515
516// ---------------------------------------------------------------------------
517
518export {
8dc8a34e 519 Emailer
ecb4e35f 520}