Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/reports_mailer.py
blob: 68774e2d047888a6f4242ab64e5077a2b9b0d17b (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
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
#!/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 fcntl
import smtplib
import logging
import zipfile
import tempfile
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
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 = '''
Report: %s
Received: %s
Nickname: %s
Serial number: %s
Jabber server: %s
Message:

%s

'''

AUTOMATIC_BODY = '''
Report: %s
Received: %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)
    mail_server.quit()

def compress_directory(report_path, report_name):
    temp_file = tempfile.TemporaryFile()
    zip_file = zipfile.ZipFile(temp_file, 'w')

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

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

        zip_log_path = os.path.join(report_name, log_file)
        zip_file.write(log_path, zip_log_path, zipfile.ZIP_DEFLATED)

    zip_file.close()
    temp_file.seek(0)
    return temp_file.read()

def prepare_message(subject, body, report_path, report_name):
    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)

    attachment_content =  compress_directory(report_path, report_name)

    attachment = MIMEBase('application', 'zip')
    attachment.set_payload(attachment_content)
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition', 'attachment', 
                   filename=report_name + '.zip')

    message.attach(attachment)
    return message.as_string()

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

    if 'serial_number' in info:
        body = CUSTOM_BODY % (
            report_name,
            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_name,
                    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, report)
            subject = generate_subject(report_info)
            message = prepare_message(subject, body, report_path, report)

            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 already_running(lockfile):
    descriptor = os.open(lockfile, os.O_CREAT|os.O_TRUNC|os.O_WRONLY)

    try:
        fcntl.lockf(descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
    except IOError:
        return True

    return False

def main():
    script_path = os.path.abspath(__file__)
    script_directory_path = os.path.dirname(script_path)

    lockfile = os.path.join(script_directory_path, '.lock')
    if already_running(lockfile):
        print 'Can\'t run script, because it is already running.'
        sys.exit(-1)

    config = ConfigParser()
    config_path = os.path.join(script_directory_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()