Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/reports_mailer.py
blob: 8b61840903243a9a7cc6d2bc06898068bd2f8076 (plain)
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
#!/usr/bin/env python

# Copyright (C) 2011, Martin Abente
#
# 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, either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import os
import sys
import json
import time
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from ConfigParser import ConfigParser

REPORT_INFO = 'report'
EMAILED_MARK = 'emailed'
REPORTS_PATH = ''

REPORTER_ADDRESS = ''
LIST_ADDRESS = ''

SMTP_USER = ''
SMTP_PASSWORD = ''
SMTP_SERVER = ''
SMTP_PORT = 0

CUSTOM_SUBJECT = '[custom.feedback.report]'
UNKNOWN_SUBJECT = '???'

CUSTOM_BODY = '''
Reported: %s
Nickname: %s
Serial number: %s
Jabber server: %s
Message:

%s

'''

AUTOMATIC_BODY = '''
Reported: %s
Component: %s
Type: %s
Ocurrences: %s

'''

def send_email(message):
    mail_server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    mail_server.ehlo()
    mail_server.starttls()
    mail_server.ehlo()
    mail_server.login(SMTP_USER, SMTP_PASSWORD)
    mail_server.sendmail(REPORTER_ADDRESS, [LIST_ADDRESS], message.as_string())
    mail_server.quit()

def prepare_message(subject, body, report_path):
    message = MIMEMultipart()
    message['Subject'] = subject
    message['From'] = REPORTER_ADDRESS
    message['To'] = LIST_ADDRESS
    message.preamble = 'Feedback Report'

    body_attachment = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    message.attach(body_attachment)

    for log_path in os.listdir(report_path):
        abs_log_path = os.path.join(report_path, log_path)

        if not os.path.isfile(abs_log_path):
            continue

        log_file = open(abs_log_path, 'r')
        payload = log_file.read().encode('utf-8')
        attachment = MIMEText(payload, 'plain', 'utf-8')
        log_file.close()

        attachment.add_header('Content-Disposition',
                'attachment',
                filename=log_path)
        message.attach(attachment)

    return message

def generate_body(info, report_info_path):
    report_time = time.ctime(os.path.getctime(report_info_path))

    if 'serial_number' in info:
        body = CUSTOM_BODY % (
            report_time,
            info.get('nick', ''),
            info.get('serial_number', ''),
            info.get('jabber_server', ''),
            info.get('message', ''))
    else:
        body = ''
        for component in info:
            for bugtype in info[component]:
                ocurrences = info[component][bugtype]
                body += AUTOMATIC_BODY % (
                    report_time,
                    component,
                    bugtype,
                    ocurrences)

    return body

def generate_subject(info):
    if 'serial_number' in info:
        subject = CUSTOM_SUBJECT
    else:
        subject = '[%s]' % ','.join(info.keys())

    return subject

def check_reports():
    for report in os.listdir(REPORTS_PATH):
        report_path = os.path.join(REPORTS_PATH, report)
        
        if os.path.isdir(report_path):
            report_info_path = os.path.join(report_path, REPORT_INFO)
            emailed_mark_path = os.path.join(report_path, EMAILED_MARK)

            if not os.path.exists(report_info_path) or \
                os.path.exists(emailed_mark_path):
                    continue

            report_info_file = open(report_info_path, 'r')
            report_data = report_info_file.read()
            report_info_file.close()

            try:
                report_info =  json.loads(report_data)
            except Exception, e:
                logging.info('Error while parsing %s: %s' % (report_info_path, str(e)))
                continue

            if len(report_info.keys()) <= 0:
                logging.info('Empty report %s.' % report_info_path)
                continue

            body = generate_body(report_info, report_info_path)
            subject = generate_subject(report_info)
            message = prepare_message(subject, body, report_path)

            try:
                send_email(message)
            except Exception, e:
                logging.info('Error while sending %s: %s' % (report_info_path, str(e)))
                continue

            emailed_mark_file = open(emailed_mark_path, 'w')
            emailed_mark_file.close()
            logging.info('Marked %s.' % emailed_mark_path)

def load_configuration(config):
    global REPORTS_PATH, REPORTER_ADDRESS, LIST_ADDRESS, \
        SMTP_USER, SMTP_PASSWORD, SMTP_SERVER, SMTP_PORT

    format = "%(asctime)s %(message)s"
    log_path = config.get('mailer', 'log_path')
    logging.basicConfig(filename=log_path, level=logging.INFO, format=format)

    REPORTS_PATH =  config.get('feedback', 'reports_path')

    if not os.path.exists(REPORTS_PATH):
        logging.error('Reports directory (%s) does not exists.' % REPORTS_PATH)
        sys.exit(-1)

    REPORTER_ADDRESS = config.get('mailer', 'reporter_address')
    LIST_ADDRESS = config.get('mailer', 'list_address')
    SMTP_USER = config.get('mailer', 'smtp_user')
    SMTP_PASSWORD = config.get('mailer', 'smtp_password')
    SMTP_SERVER = config.get('mailer', 'smtp_server')
    SMTP_PORT = config.get('mailer', 'smtp_port')

def main():
    config = ConfigParser()
    script_path = os.path.abspath(__file__)
    config_path = os.path.join(os.path.dirname(script_path), 'config.ini')

    if len(config.read(config_path)) == 0:
        print 'Can\'t load configuration file.'
        sys.exit(-1)

    if not config.has_section('mailer'):
        print 'No mailer configuration found.'
        sys.exit(-1)

    enabled = config.getboolean('mailer', 'enabled')
    if not enabled:
        print 'Mailer agent is not enabled.'
        sys.exit(-1)

    load_configuration(config)
    check_reports()
    sys.exit(0)

if __name__ == "__main__":
    main()