Add blacklist reason field
[oweals/peertube.git] / server / lib / emailer.ts
1 import { createTransport, Transporter } from 'nodemailer'
2 import { UserRight } from '../../shared/models/users'
3 import { isTestInstance } from '../helpers/core-utils'
4 import { bunyanLogger, logger } from '../helpers/logger'
5 import { CONFIG } from '../initializers'
6 import { UserModel } from '../models/account/user'
7 import { VideoModel } from '../models/video/video'
8 import { JobQueue } from './job-queue'
9 import { EmailPayload } from './job-queue/handlers/email'
10 import { readFileSync } from 'fs'
11
12 class 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
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
43       this.transporter = createTransport({
44         host: CONFIG.SMTP.HOSTNAME,
45         port: CONFIG.SMTP.PORT,
46         secure: CONFIG.SMTP.TLS,
47         debug: CONFIG.LOG.LEVEL === 'debug',
48         logger: bunyanLogger as any,
49         ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
50         tls,
51         auth
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
63     logger.info('Testing SMTP server...')
64
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}! ` +
78       `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
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
92   async addVideoAbuseReportJob (videoId: number) {
93     const video = await VideoModel.load(videoId)
94     if (!video) throw new Error('Unknown Video id during Abuse report.')
95
96     const text = `Hi,\n\n` +
97       `Your instance received an abuse for the following video ${video.url}\n\n` +
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
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.')
141
142     const user = await UserModel.loadById(video.VideoChannel.Account.userId)
143
144     const text = 'Hi,\n\n' +
145       `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
146       '\n\n' +
147       'Cheers,\n' +
148       `PeerTube.`
149
150     const to = user.email
151     const emailPayload: EmailPayload = {
152       to: [ to ],
153       subject: `[PeerTube] Video ${video.name} unblacklisted`,
154       text
155     }
156
157     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
158   }
159
160   addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
161     const reasonString = reason ? ` for the following reason: ${reason}` : ''
162     const blockedWord = blocked ? 'blocked' : 'unblocked'
163     const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
164
165     const text = 'Hi,\n\n' +
166       blockedString +
167       '\n\n' +
168       'Cheers,\n' +
169       `PeerTube.`
170
171     const to = user.email
172     const emailPayload: EmailPayload = {
173       to: [ to ],
174       subject: '[PeerTube] Account ' + blockedWord,
175       text
176     }
177
178     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
179   }
180
181   sendMail (to: string[], subject: string, text: string) {
182     if (!this.transporter) {
183       throw new Error('Cannot send mail because SMTP is not configured.')
184     }
185
186     return this.transporter.sendMail({
187       from: CONFIG.SMTP.FROM_ADDRESS,
188       to: to.join(','),
189       subject,
190       text
191     })
192   }
193
194   private dieOnConnectionFailure (err?: Error) {
195     logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
196     process.exit(-1)
197   }
198
199   static get Instance () {
200     return this.instance || (this.instance = new this())
201   }
202 }
203
204 // ---------------------------------------------------------------------------
205
206 export {
207   Emailer
208 }