Fix redundancy totalVideos stats
[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-extra'
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   addVerifyEmailJob (to: string, verifyEmailUrl: string) {
93     const text = `Welcome to PeerTube,\n\n` +
94       `To start using PeerTube on ${CONFIG.WEBSERVER.HOST} you must  verify your email! ` +
95       `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
96       `If you are not the person who initiated this request, please ignore this email.\n\n` +
97       `Cheers,\n` +
98       `PeerTube.`
99
100     const emailPayload: EmailPayload = {
101       to: [ to ],
102       subject: 'Verify your PeerTube email',
103       text
104     }
105
106     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
107   }
108
109   async addVideoAbuseReportJob (videoId: number) {
110     const video = await VideoModel.load(videoId)
111     if (!video) throw new Error('Unknown Video id during Abuse report.')
112
113     const text = `Hi,\n\n` +
114       `Your instance received an abuse for the following video ${video.url}\n\n` +
115       `Cheers,\n` +
116       `PeerTube.`
117
118     const to = await UserModel.listEmailsWithRight(UserRight.MANAGE_VIDEO_ABUSES)
119     const emailPayload: EmailPayload = {
120       to,
121       subject: '[PeerTube] Received a video abuse',
122       text
123     }
124
125     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
126   }
127
128   async addVideoBlacklistReportJob (videoId: number, reason?: string) {
129     const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
130     if (!video) throw new Error('Unknown Video id during Blacklist report.')
131     // It's not our user
132     if (video.remote === true) return
133
134     const user = await UserModel.loadById(video.VideoChannel.Account.userId)
135
136     const reasonString = reason ? ` for the following reason: ${reason}` : ''
137     const blockedString = `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
138
139     const text = 'Hi,\n\n' +
140       blockedString +
141       '\n\n' +
142       'Cheers,\n' +
143       `PeerTube.`
144
145     const to = user.email
146     const emailPayload: EmailPayload = {
147       to: [ to ],
148       subject: `[PeerTube] Video ${video.name} blacklisted`,
149       text
150     }
151
152     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
153   }
154
155   async addVideoUnblacklistReportJob (videoId: number) {
156     const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
157     if (!video) throw new Error('Unknown Video id during Blacklist report.')
158     // It's not our user
159     if (video.remote === true) return
160
161     const user = await UserModel.loadById(video.VideoChannel.Account.userId)
162
163     const text = 'Hi,\n\n' +
164       `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
165       '\n\n' +
166       'Cheers,\n' +
167       `PeerTube.`
168
169     const to = user.email
170     const emailPayload: EmailPayload = {
171       to: [ to ],
172       subject: `[PeerTube] Video ${video.name} unblacklisted`,
173       text
174     }
175
176     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
177   }
178
179   addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
180     const reasonString = reason ? ` for the following reason: ${reason}` : ''
181     const blockedWord = blocked ? 'blocked' : 'unblocked'
182     const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
183
184     const text = 'Hi,\n\n' +
185       blockedString +
186       '\n\n' +
187       'Cheers,\n' +
188       `PeerTube.`
189
190     const to = user.email
191     const emailPayload: EmailPayload = {
192       to: [ to ],
193       subject: '[PeerTube] Account ' + blockedWord,
194       text
195     }
196
197     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
198   }
199
200   sendMail (to: string[], subject: string, text: string) {
201     if (!this.transporter) {
202       throw new Error('Cannot send mail because SMTP is not configured.')
203     }
204
205     return this.transporter.sendMail({
206       from: CONFIG.SMTP.FROM_ADDRESS,
207       to: to.join(','),
208       subject,
209       text
210     })
211   }
212
213   private dieOnConnectionFailure (err?: Error) {
214     logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
215     process.exit(-1)
216   }
217
218   static get Instance () {
219     return this.instance || (this.instance = new this())
220   }
221 }
222
223 // ---------------------------------------------------------------------------
224
225 export {
226   Emailer
227 }