aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/emailer.ts
blob: 9c49aa2f6549e76c4b22db95baed6ca2782f90e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import { readFileSync } from 'fs-extra'
import { merge } from 'lodash'
import { createTransport, Transporter } from 'nodemailer'
import { join } from 'path'
import { VideoChannelModel } from '@server/models/video/video-channel'
import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
import { MVideoImport, MVideoImportVideo } from '@server/types/models/video/video-import'
import { AbuseState, EmailPayload, UserAbuse } from '@shared/models'
import { SendEmailOptions } from '../../shared/models/server/emailer.model'
import { isTestInstance, root } from '../helpers/core-utils'
import { bunyanLogger, logger } from '../helpers/logger'
import { CONFIG, isEmailEnabled } from '../initializers/config'
import { WEBSERVER } from '../initializers/constants'
import { MAbuseFull, MAbuseMessage, MActorFollowActors, MActorFollowFull, MUser } from '../types/models'
import { MCommentOwnerVideo, MVideo, MVideoAccountLight } from '../types/models/video'
import { JobQueue } from './job-queue'

const Email = require('email-templates')

class Emailer {

  private static instance: Emailer
  private initialized = false
  private transporter: Transporter

  private constructor () {
  }

  init () {
    // Already initialized
    if (this.initialized === true) return
    this.initialized = true

    if (isEmailEnabled()) {
      if (CONFIG.SMTP.TRANSPORT === 'smtp') {
        logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)

        let tls
        if (CONFIG.SMTP.CA_FILE) {
          tls = {
            ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
          }
        }

        let auth
        if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
          auth = {
            user: CONFIG.SMTP.USERNAME,
            pass: CONFIG.SMTP.PASSWORD
          }
        }

        this.transporter = createTransport({
          host: CONFIG.SMTP.HOSTNAME,
          port: CONFIG.SMTP.PORT,
          secure: CONFIG.SMTP.TLS,
          debug: CONFIG.LOG.LEVEL === 'debug',
          logger: bunyanLogger as any,
          ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
          tls,
          auth
        })
      } else { // sendmail
        logger.info('Using sendmail to send emails')

        this.transporter = createTransport({
          sendmail: true,
          newline: 'unix',
          path: CONFIG.SMTP.SENDMAIL
        })
      }
    } else {
      if (!isTestInstance()) {
        logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
      }
    }
  }

  static isEnabled () {
    if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
      return !!CONFIG.SMTP.SENDMAIL
    } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
      return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
    } else {
      return false
    }
  }

  async checkConnectionOrDie () {
    if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return

    logger.info('Testing SMTP server...')

    try {
      const success = await this.transporter.verify()
      if (success !== true) this.dieOnConnectionFailure()

      logger.info('Successfully connected to SMTP server.')
    } catch (err) {
      this.dieOnConnectionFailure(err)
    }
  }

  addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
    const channelName = video.VideoChannel.getDisplayName()
    const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()

    const emailPayload: EmailPayload = {
      to,
      subject: channelName + ' just published a new video',
      text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
      locals: {
        title: 'New content ',
        action: {
          text: 'View video',
          url: videoUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
    const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()

    const emailPayload: EmailPayload = {
      template: 'follower-on-channel',
      to,
      subject: `New follower on your channel ${followingName}`,
      locals: {
        followerName: actorFollow.ActorFollower.Account.getDisplayName(),
        followerUrl: actorFollow.ActorFollower.url,
        followingName,
        followingUrl: actorFollow.ActorFollowing.url,
        followType
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
    const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''

    const emailPayload: EmailPayload = {
      to,
      subject: 'New instance follower',
      text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
      locals: {
        title: 'New instance follower',
        action: {
          text: 'Review followers',
          url: WEBSERVER.URL + '/admin/follows/followers-list'
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
    const instanceUrl = actorFollow.ActorFollowing.url
    const emailPayload: EmailPayload = {
      to,
      subject: 'Auto instance following',
      text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  myVideoPublishedNotification (to: string[], video: MVideo) {
    const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()

    const emailPayload: EmailPayload = {
      to,
      subject: `Your video ${video.name} has been published`,
      text: `Your video "${video.name}" has been published.`,
      locals: {
        title: 'You video is live',
        action: {
          text: 'View video',
          url: videoUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
    const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()

    const emailPayload: EmailPayload = {
      to,
      subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
      text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
      locals: {
        title: 'Import complete',
        action: {
          text: 'View video',
          url: videoUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
    const importUrl = WEBSERVER.URL + '/my-account/video-imports'

    const text =
      `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
      '\n\n' +
      `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`

    const emailPayload: EmailPayload = {
      to,
      subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
      text,
      locals: {
        title: 'Import failed',
        action: {
          text: 'Review imports',
          url: importUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
    const video = comment.Video
    const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
    const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()

    const emailPayload: EmailPayload = {
      template: 'video-comment-new',
      to,
      subject: 'New comment on your video ' + video.name,
      locals: {
        accountName: comment.Account.getDisplayName(),
        accountUrl: comment.Account.Actor.url,
        comment,
        video,
        videoUrl,
        action: {
          text: 'View comment',
          url: commentUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
    const accountName = comment.Account.getDisplayName()
    const video = comment.Video
    const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
    const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()

    const emailPayload: EmailPayload = {
      template: 'video-comment-mention',
      to,
      subject: 'Mention on video ' + video.name,
      locals: {
        comment,
        video,
        videoUrl,
        accountName,
        action: {
          text: 'View comment',
          url: commentUrl
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addAbuseModeratorsNotification (to: string[], parameters: {
    abuse: UserAbuse
    abuseInstance: MAbuseFull
    reporter: string
  }) {
    const { abuse, abuseInstance, reporter } = parameters

    const action = {
      text: 'View report #' + abuse.id,
      url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
    }

    let emailPayload: EmailPayload

    if (abuseInstance.VideoAbuse) {
      const video = abuseInstance.VideoAbuse.Video
      const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()

      emailPayload = {
        template: 'video-abuse-new',
        to,
        subject: `New video abuse report from ${reporter}`,
        locals: {
          videoUrl,
          isLocal: video.remote === false,
          videoCreatedAt: new Date(video.createdAt).toLocaleString(),
          videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
          videoName: video.name,
          reason: abuse.reason,
          videoChannel: abuse.video.channel,
          reporter,
          action
        }
      }
    } else if (abuseInstance.VideoCommentAbuse) {
      const comment = abuseInstance.VideoCommentAbuse.VideoComment
      const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()

      emailPayload = {
        template: 'video-comment-abuse-new',
        to,
        subject: `New comment abuse report from ${reporter}`,
        locals: {
          commentUrl,
          videoName: comment.Video.name,
          isLocal: comment.isOwned(),
          commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
          reason: abuse.reason,
          flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
          reporter,
          action
        }
      }
    } else {
      const account = abuseInstance.FlaggedAccount
      const accountUrl = account.getClientUrl()

      emailPayload = {
        template: 'account-abuse-new',
        to,
        subject: `New account abuse report from ${reporter}`,
        locals: {
          accountUrl,
          accountDisplayName: account.getDisplayName(),
          isLocal: account.isOwned(),
          reason: abuse.reason,
          reporter,
          action
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addAbuseStateChangeNotification (to: string[], abuse: MAbuseFull) {
    const text = abuse.state === AbuseState.ACCEPTED
      ? 'Report #' + abuse.id + ' has been accepted'
      : 'Report #' + abuse.id + ' has been rejected'

    const action = {
      text,
      url: WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
    }

    const emailPayload: EmailPayload = {
      template: 'abuse-state-change',
      to,
      subject: text,
      locals: {
        action,
        abuseId: abuse.id,
        isAccepted: abuse.state === AbuseState.ACCEPTED
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addAbuseNewMessageNotification (to: string[], options: { target: 'moderator' | 'reporter', abuse: MAbuseFull, message: MAbuseMessage }) {
    const { abuse, target, message } = options

    const text = 'New message on abuse #' + abuse.id
    const action = {
      text,
      url: target === 'moderator'
        ? WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
        : WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
    }

    const emailPayload: EmailPayload = {
      template: 'abuse-new-message',
      to,
      subject: text,
      locals: {
        abuseUrl: action.url,
        messageText: message.message,
        action
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
    const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
    const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
    const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()

    const emailPayload: EmailPayload = {
      template: 'video-auto-blacklist-new',
      to,
      subject: 'A new video is pending moderation',
      locals: {
        channel,
        videoUrl,
        videoName: videoBlacklist.Video.name,
        action: {
          text: 'Review autoblacklist',
          url: VIDEO_AUTO_BLACKLIST_URL
        }
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addNewUserRegistrationNotification (to: string[], user: MUser) {
    const emailPayload: EmailPayload = {
      template: 'user-registered',
      to,
      subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
      locals: {
        user
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
    const videoName = videoBlacklist.Video.name
    const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()

    const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
    const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`

    const emailPayload: EmailPayload = {
      to,
      subject: `Video ${videoName} blacklisted`,
      text: blockedString,
      locals: {
        title: 'Your video was blacklisted'
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addVideoUnblacklistNotification (to: string[], video: MVideo) {
    const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()

    const emailPayload: EmailPayload = {
      to,
      subject: `Video ${video.name} unblacklisted`,
      text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
      locals: {
        title: 'Your video was unblacklisted'
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
    const emailPayload: EmailPayload = {
      template: 'password-reset',
      to: [ to ],
      subject: 'Reset your account password',
      locals: {
        username,
        resetPasswordUrl
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
    const emailPayload: EmailPayload = {
      template: 'password-create',
      to: [ to ],
      subject: 'Create your account password',
      locals: {
        username,
        createPasswordUrl
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
    const emailPayload: EmailPayload = {
      template: 'verify-email',
      to: [ to ],
      subject: `Verify your email on ${WEBSERVER.HOST}`,
      locals: {
        username,
        verifyEmailUrl
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
    const reasonString = reason ? ` for the following reason: ${reason}` : ''
    const blockedWord = blocked ? 'blocked' : 'unblocked'

    const to = user.email
    const emailPayload: EmailPayload = {
      to: [ to ],
      subject: 'Account ' + blockedWord,
      text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
    const emailPayload: EmailPayload = {
      template: 'contact-form',
      to: [ CONFIG.ADMIN.EMAIL ],
      replyTo: `"${fromName}" <${fromEmail}>`,
      subject: `(contact form) ${subject}`,
      locals: {
        fromName,
        fromEmail,
        body
      }
    }

    return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
  }

  async sendMail (options: EmailPayload) {
    if (!isEmailEnabled()) {
      throw new Error('Cannot send mail because SMTP is not configured.')
    }

    const fromDisplayName = options.from
      ? options.from
      : WEBSERVER.HOST

    const email = new Email({
      send: true,
      message: {
        from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
      },
      transport: this.transporter,
      views: {
        root: join(root(), 'dist', 'server', 'lib', 'emails')
      },
      subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
    })

    for (const to of options.to) {
      await email
        .send(merge(
          {
            template: 'common',
            message: {
              to,
              from: options.from,
              subject: options.subject,
              replyTo: options.replyTo
            },
            locals: { // default variables available in all templates
              WEBSERVER,
              EMAIL: CONFIG.EMAIL,
              text: options.text,
              subject: options.subject
            }
          },
          options // overriden/new variables given for a specific template in the payload
        ) as SendEmailOptions)
        .then(res => logger.debug('Sent email.', { res }))
        .catch(err => logger.error('Error in email sender.', { err }))
    }
  }

  private dieOnConnectionFailure (err?: Error) {
    logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
    process.exit(-1)
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

// ---------------------------------------------------------------------------

export {
  Emailer
}