]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/emailer.ts
chore(refactor): remove shared folder dependencies to the server
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
... / ...
CommitLineData
1import { readFileSync } from 'fs-extra'
2import { isArray, merge } from 'lodash'
3import { createTransport, Transporter } from 'nodemailer'
4import { join } from 'path'
5import { EmailPayload } from '@shared/models'
6import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
7import { isTestInstance } from '../helpers/core-utils'
8import { root } from '@shared/core-utils'
9import { bunyanLogger, logger } from '../helpers/logger'
10import { CONFIG, isEmailEnabled } from '../initializers/config'
11import { WEBSERVER } from '../initializers/constants'
12import { MUser } from '../types/models'
13import { JobQueue } from './job-queue'
14
15const Email = require('email-templates')
16
17class Emailer {
18
19 private static instance: Emailer
20 private initialized = false
21 private transporter: Transporter
22
23 private constructor () {
24 }
25
26 init () {
27 // Already initialized
28 if (this.initialized === true) return
29 this.initialized = true
30
31 if (!isEmailEnabled()) {
32 if (!isTestInstance()) {
33 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
34 }
35
36 return
37 }
38
39 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
40 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
41 }
42
43 async checkConnection () {
44 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
45
46 logger.info('Testing SMTP server...')
47
48 try {
49 const success = await this.transporter.verify()
50 if (success !== true) this.warnOnConnectionFailure()
51
52 logger.info('Successfully connected to SMTP server.')
53 } catch (err) {
54 this.warnOnConnectionFailure(err)
55 }
56 }
57
58 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
59 const emailPayload: EmailPayload = {
60 template: 'password-reset',
61 to: [ to ],
62 subject: 'Reset your account password',
63 locals: {
64 username,
65 resetPasswordUrl
66 }
67 }
68
69 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
70 }
71
72 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
73 const emailPayload: EmailPayload = {
74 template: 'password-create',
75 to: [ to ],
76 subject: 'Create your account password',
77 locals: {
78 username,
79 createPasswordUrl
80 }
81 }
82
83 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
84 }
85
86 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
87 const emailPayload: EmailPayload = {
88 template: 'verify-email',
89 to: [ to ],
90 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
91 locals: {
92 username,
93 verifyEmailUrl
94 }
95 }
96
97 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
98 }
99
100 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
101 const reasonString = reason ? ` for the following reason: ${reason}` : ''
102 const blockedWord = blocked ? 'blocked' : 'unblocked'
103
104 const to = user.email
105 const emailPayload: EmailPayload = {
106 to: [ to ],
107 subject: 'Account ' + blockedWord,
108 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
109 }
110
111 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
112 }
113
114 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
115 const emailPayload: EmailPayload = {
116 template: 'contact-form',
117 to: [ CONFIG.ADMIN.EMAIL ],
118 replyTo: `"${fromName}" <${fromEmail}>`,
119 subject: `(contact form) ${subject}`,
120 locals: {
121 fromName,
122 fromEmail,
123 body,
124
125 // There are not notification preferences for the contact form
126 hideNotificationPreferences: true
127 }
128 }
129
130 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
131 }
132
133 async sendMail (options: EmailPayload) {
134 if (!isEmailEnabled()) {
135 throw new Error('Cannot send mail because SMTP is not configured.')
136 }
137
138 const fromDisplayName = options.from
139 ? options.from
140 : CONFIG.INSTANCE.NAME
141
142 const email = new Email({
143 send: true,
144 message: {
145 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
146 },
147 transport: this.transporter,
148 views: {
149 root: join(root(), 'dist', 'server', 'lib', 'emails')
150 },
151 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
152 })
153
154 const toEmails = isArray(options.to)
155 ? options.to
156 : [ options.to ]
157
158 for (const to of toEmails) {
159 const baseOptions: SendEmailDefaultOptions = {
160 template: 'common',
161 message: {
162 to,
163 from: options.from,
164 subject: options.subject,
165 replyTo: options.replyTo
166 },
167 locals: { // default variables available in all templates
168 WEBSERVER,
169 EMAIL: CONFIG.EMAIL,
170 instanceName: CONFIG.INSTANCE.NAME,
171 text: options.text,
172 subject: options.subject
173 }
174 }
175
176 // overriden/new variables given for a specific template in the payload
177 const sendOptions = merge(baseOptions, options)
178
179 await email.send(sendOptions)
180 .then(res => logger.debug('Sent email.', { res }))
181 .catch(err => logger.error('Error in email sender.', { err }))
182 }
183 }
184
185 private warnOnConnectionFailure (err?: Error) {
186 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
187 }
188
189 private initSMTPTransport () {
190 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
191
192 let tls
193 if (CONFIG.SMTP.CA_FILE) {
194 tls = {
195 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
196 }
197 }
198
199 let auth
200 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
201 auth = {
202 user: CONFIG.SMTP.USERNAME,
203 pass: CONFIG.SMTP.PASSWORD
204 }
205 }
206
207 this.transporter = createTransport({
208 host: CONFIG.SMTP.HOSTNAME,
209 port: CONFIG.SMTP.PORT,
210 secure: CONFIG.SMTP.TLS,
211 debug: CONFIG.LOG.LEVEL === 'debug',
212 logger: bunyanLogger as any,
213 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
214 tls,
215 auth
216 })
217 }
218
219 private initSendmailTransport () {
220 logger.info('Using sendmail to send emails')
221
222 this.transporter = createTransport({
223 sendmail: true,
224 newline: 'unix',
225 path: CONFIG.SMTP.SENDMAIL,
226 logger: bunyanLogger
227 })
228 }
229
230 static get Instance () {
231 return this.instance || (this.instance = new this())
232 }
233}
234
235// ---------------------------------------------------------------------------
236
237export {
238 Emailer
239}