sendmail.py 6.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
#
# This file is part of GetTor, a Tor Browser distribution system.
#
# :authors: isra <ilv@torproject.org>
#           see also AUTHORS file
#
# :copyright:   (c) 2008-2014, The Tor Project, Inc.
#               (c) 2014-2018, Israel Leiva
#
# :license: This is Free Software. See LICENSE for license information.

from __future__ import absolute_import

import gettext
import hashlib

import configparser
from email import encoders
from email import mime
21
22
from email.mime.text import MIMEText

23
24
25
from twisted.internet import defer
from twisted.mail.smtp import sendmail

Hiro's avatar
Hiro committed
26
from ...utils.db import SQLite3 as DB
27
from ...utils.commons import log
28
from ...utils import strings
29
30
31
32
33
34
35
36


class SMTPError(Exception):
    """
    Error if we can't send emails.
    """
    pass

37
from email.mime.text import MIMEText
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
class Sendmail(object):
    """
    Class for sending email replies to `help` and `links` requests.
    """
    def __init__(self, settings):
        """
        Constructor. It opens and stores a connection to the database.
        :dbname: reads from configs
        """
        self.settings = settings
        dbname = self.settings.get("dbname")
        self.conn = DB(dbname)


    def get_interval(self):
        """
        Get time interval for service periodicity.

        :return: time interval (float) in seconds.
        """
        return self.settings.get("sendmail_interval")


    def sendmail_callback(self, message):
        """
        Callback invoked after an email has been sent.

        :param message (string): Success details from the server.
        """
        log.info("Email sent successfully.")

    def sendmail_errback(self, error):
        """
        Errback if we don't/can't send the message.
        """
        log.debug("Could not send email.")
        raise SMTPError("{}".format(error))

    def sendmail(self, email_addr, subject, body):
        """
        Send an email message. It creates a plain text message, set headers
        and content and finally send it.

        :param email_addr (str): email address of the recipient.
        :param subject (str): subject of the message.
        :param content (str): content of the message.

        :return: deferred whose callback/errback will handle the SMTP
        execution details.
        """
        log.debug("Creating plain text email")
        message = MIMEText(body)

        message['Subject'] = subject
92
        message['From'] = self.settings.get("sendmail_addr")
93
94
95
96
97
        message['To'] = email_addr

        log.debug("Calling asynchronous sendmail.")

        return sendmail(
98
99
            self.settings.get("sendmail_host"), self.settings.get("sendmail_addr"), email_addr, message,
            requireTransportSecurity=True
100
101
102
103
104
105
        ).addCallback(self.sendmail_callback).addErrback(self.sendmail_errback)



    @defer.inlineCallbacks
    def get_new(self):
Hiro's avatar
Hiro committed
106
        """
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        Get new requests to process. This will define the `main loop` of
        the Sendmail service.
        """

        # Manage help and links messages separately
        help_requests = yield self.conn.get_requests(
            status="ONHOLD", command="help", service="email"
        )

        link_requests = yield self.conn.get_requests(
            status="ONHOLD", command="links", service="email"
        )

        if help_requests:
Hiro's avatar
Hiro committed
121
            strings.load_strings("en")
122
123
124
125
126
            try:
                log.info("Got new help request.")

                for request in help_requests:
                    id = request[0]
127
                    date = request[5]
128

129
                    hid = hashlib.sha256(id.encode('utf-8'))
130
131
132
133
134
135
136
137
                    log.info(
                        "Sending help message to {}.".format(
                            hid.hexdigest()
                        )
                    )

                    yield self.sendmail(
                        email_addr=id,
Hiro's avatar
Hiro committed
138
139
                        subject=strings._("help_subject"),
                        body=strings._("help_body")
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
                    )

                    yield self.conn.update_stats(
                        command="help", service="email"
                    )

                    yield self.conn.update_request(
                        id=id, hid=hid.hexdigest(), status="SENT",
                        service="email", date=date
                    )

            except SMTPError as e:
                log.info("Error sending email: {}.".format(e))

        elif link_requests:
            try:
                log.info("Got new links request.")

                for request in link_requests:
                    id = request[0]
160
                    date = request[5]
161
                    platform = request[2]
Hiro's avatar
Hiro committed
162
                    language = request[3]
Hiro's avatar
Hiro committed
163
164
165
166

                    if not language:
                        language = 'en'

167
168
                    locales = strings.get_locales()

Hiro's avatar
Hiro committed
169
                    strings.load_strings(language)
170
                    locale = locales[language]['locale']
171
172
173

                    log.info("Getting links for {}.".format(platform))
                    links = yield self.conn.get_links(
174
                        platform=platform, language=locale, status="ACTIVE"
175
176
177
178
179
                    )

                    # build message
                    link_msg = None
                    for link in links:
180
181
182
                        provider = link[5]
                        version = link[4]
                        arch = link[3]
183
184
                        url = link[0]

185
186
                        link_str = "Tor Browser {} for {}-{}-{} ({}): {}".format(
                            version, platform, locale, arch, provider, url
187
188
189
190
191
192
193
                        )

                        if link_msg:
                            link_msg = "{}\n{}".format(link_msg, link_str)
                        else:
                            link_msg = link_str

Hiro's avatar
Hiro committed
194
                    body_msg = strings._("links_body").format(platform, link_msg)
195
                    subject_msg = strings._("links_subject")
196

197
                    hid = hashlib.sha256(id.encode('utf-8'))
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
                    log.info(
                        "Sending links to {}.".format(
                            hid.hexdigest()
                        )
                    )

                    yield self.sendmail(
                        email_addr=id,
                        subject=subject_msg,
                        body=body_msg
                    )

                    yield self.conn.update_stats(
                        command="links", platform=platform, service="email"
                    )

                    yield self.conn.update_request(
                        id=id, hid=hid.hexdigest(), status="SENT",
                        service="email", date=date
                    )

            except SMTPError as e:
                log.info("Error sending email: {}.".format(e))
        else:
            log.debug("No pending email requests. Keep waiting.")