File: mail.py

package info (click to toggle)
ubuntu-dev-tools 0.208
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,172 kB
  • sloc: python: 9,118; sh: 1,330; perl: 135; makefile: 11
file content (292 lines) | stat: -rw-r--r-- 8,861 bytes parent folder | download
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
# -*- coding: utf-8 -*-
#
#   mail.py - methods used by requestsync when used in "mail" mode
#
#   Copyright © 2009 Michael Bienia <geser@ubuntu.com>,
#               2011 Stefano Rivera <stefanor@ubuntu.com>
#
#   This module may contain code written by other authors/contributors to
#   the main requestsync script. See there for their names.
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; version 2
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   Please see the /usr/share/common-licenses/GPL-2 file for the full text
#   of the GNU General Public License license.

import logging
import os
import re
import smtplib
import socket
import subprocess
import sys
import tempfile

from debian.changelog import Changelog
from distro_info import DebianDistroInfo, DistroDataOutdated

from ubuntutools.archive import DebianSourcePackage, UbuntuSourcePackage
from ubuntutools.lp.udtexceptions import PackageNotFoundException
from ubuntutools.question import YesNoQuestion, confirmation_prompt

Logger = logging.getLogger(__name__)


__all__ = [
    "get_debian_srcpkg",
    "get_ubuntu_srcpkg",
    "need_sponsorship",
    "check_existing_reports",
    "get_ubuntu_delta_changelog",
    "mail_bug",
]


def get_debian_srcpkg(name, release):
    # Canonicalise release:
    debian_info = DebianDistroInfo()
    try:
        codename = debian_info.codename(release, default=release)
        return DebianSourcePackage(package=name, series=codename).lp_spph
    except DistroDataOutdated as e:
        Logger.warning(e)
    except PackageNotFoundException:
        pass
    return DebianSourcePackage(package=name, series=release).lp_spph


def get_ubuntu_srcpkg(name, release, pocket="Proposed"):
    srcpkg = UbuntuSourcePackage(package=name, series=release, pocket=pocket)
    try:
        return srcpkg.lp_spph
    except PackageNotFoundException:
        if pocket != "Release":
            parent_pocket = "Release"
            if pocket == "Updates":
                parent_pocket = "Proposed"
            return get_ubuntu_srcpkg(name, release, parent_pocket)
        raise


def need_sponsorship(name, component, release):
    """
    Ask the user if he has upload permissions for the package or the
    component.
    """

    val = YesNoQuestion().ask(
        f"Do you have upload permissions for the '{component}' component or "
        f"the package '{name}' in Ubuntu {release}?\nIf in doubt answer 'n'.",
        "no",
    )
    return val == "no"


def check_existing_reports(srcpkg):
    """
    Point the user to the URL to manually check for duplicate bug reports.
    """
    print(
        f"Please check on https://bugs.launchpad.net/ubuntu/+source/{srcpkg}/+bugs\n"
        f"for duplicate sync requests before continuing."
    )
    confirmation_prompt()


def get_ubuntu_delta_changelog(srcpkg):
    """
    Download the Ubuntu changelog and extract the entries since the last sync
    from Debian.
    """
    changelog = Changelog(srcpkg.getChangelog())
    if changelog is None:
        return ""
    delta = []
    debian_info = DebianDistroInfo()
    for block in changelog:
        distribution = block.distributions.split()[0].split("-")[0]
        if debian_info.valid(distribution):
            break
        delta += [str(change) for change in block.changes() if change.strip()]

    return "\n".join(delta)


def mail_bug(
    srcpkg,
    subscribe,
    status,
    bugtitle,
    bugtext,
    bug_mail_domain,
    keyid,
    myemailaddr,
    mailserver_host,
    mailserver_port,
    mailserver_user,
    mailserver_pass,
):
    """
    Submit the sync request per email.
    """

    to = f"new@{bug_mail_domain}"

    # generate mailbody
    if srcpkg:
        mailbody = f" affects ubuntu/{srcpkg}\n"
    else:
        mailbody = " affects ubuntu\n"
    mailbody += f"""\
 status {status}
 importance wishlist
 subscribe {subscribe}
 done

{bugtext}"""

    # prepare sign command
    gpg_command = None
    for cmd in ("gnome-gpg", "gpg2", "gpg"):
        if os.access(f"/usr/bin/{cmd}", os.X_OK):
            gpg_command = [cmd]
            break

    if not gpg_command:
        Logger.error("Cannot locate gpg, please install the 'gnupg' package!")
        sys.exit(1)

    gpg_command.append("--clearsign")
    if keyid:
        gpg_command.extend(("-u", keyid))

    # sign the mail body
    gpg = subprocess.Popen(
        gpg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8"
    )
    signed_report = gpg.communicate(mailbody)[0]
    if gpg.returncode != 0:
        Logger.error("%s failed.", gpg_command[0])
        sys.exit(1)

    # generate email
    mail = f"""\
From: {myemailaddr}
To: {to}
Subject: {bugtitle}
Content-Type: text/plain; charset=UTF-8

{signed_report}"""

    print(f"The final report is:\n{mail}")
    confirmation_prompt()

    # save mail in temporary file
    backup = tempfile.NamedTemporaryFile(
        mode="w",
        delete=False,
        prefix=f"requestsync-{re.sub('[^a-zA-Z0-9_-]', '', bugtitle.replace(' ', '_'))}",
    )
    with backup:
        backup.write(mail)

    Logger.info(
        "The e-mail has been saved in %s and will be deleted after succesful transmission",
        backup.name,
    )

    # connect to the server
    while True:
        try:
            Logger.info("Connecting to %s:%s ...", mailserver_host, mailserver_port)
            smtp = smtplib.SMTP(mailserver_host, mailserver_port)
            break
        except smtplib.SMTPConnectError as error:
            try:
                # py2 path
                # pylint: disable=unsubscriptable-object
                Logger.error(
                    "Could not connect to %s:%s: %s (%i)",
                    mailserver_host,
                    mailserver_port,
                    error[1],
                    error[0],
                )
            except TypeError:
                # pylint: disable=no-member
                Logger.error(
                    "Could not connect to %s:%s: %s (%i)",
                    mailserver_host,
                    mailserver_port,
                    error.strerror,
                    error.errno,
                )
            if error.smtp_code == 421:
                confirmation_prompt(
                    message="This is a temporary error, press [Enter] "
                    "to retry. Press [Ctrl-C] to abort now."
                )
        except socket.error as error:
            try:
                # py2 path
                # pylint: disable=unsubscriptable-object
                Logger.error(
                    "Could not connect to %s:%s: %s (%i)",
                    mailserver_host,
                    mailserver_port,
                    error[1],
                    error[0],
                )
            except TypeError:
                # pylint: disable=no-member
                Logger.error(
                    "Could not connect to %s:%s: %s (%i)",
                    mailserver_host,
                    mailserver_port,
                    error.strerror,
                    error.errno,
                )
            return

    if mailserver_user and mailserver_pass:
        try:
            smtp.login(mailserver_user, mailserver_pass)
        except smtplib.SMTPAuthenticationError:
            Logger.error("Error authenticating to the server: invalid username and password.")
            smtp.quit()
            return
        except smtplib.SMTPException:
            Logger.error("Unknown SMTP error.")
            smtp.quit()
            return

    while True:
        try:
            smtp.sendmail(myemailaddr, to, mail.encode("utf-8"))
            smtp.quit()
            os.remove(backup.name)
            Logger.info("Sync request mailed.")
            break
        except smtplib.SMTPRecipientsRefused as smtperror:
            smtp_code, smtp_message = smtperror.recipients[to]
            Logger.error("Error while sending: %i, %s", smtp_code, smtp_message)
            if smtp_code == 450:
                confirmation_prompt(
                    message="This is a temporary error, press [Enter] "
                    "to retry. Press [Ctrl-C] to abort now."
                )
            else:
                return
        except smtplib.SMTPResponseException as error:
            Logger.error("Error while sending: %i, %s", error.smtp_code, error.smtp_error)
            return
        except smtplib.SMTPServerDisconnected:
            Logger.error("Server disconnected while sending the mail.")
            return