Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/jarabe/model/feedback_collector.py
blob: e239c9aa91627fc5773cf301490f6492c574788b (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
# Copyright (C) 2011, Aleksey Lim
#
# 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 time
import httplib
import logging
import tarfile
import threading
from cStringIO import StringIO
from os.path import join, exists, basename
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.generator import Generator
from email.encoders import encode_noop
from gettext import gettext as _

import gconf
import gobject
import simplejson

from sugar import logger, feedback, util
from jarabe import frame


_reports = {}
_logs = set()
_host = None
_port = None


def start(host, port, auto_submit_delay):
    global _host
    global _port

    _host = host
    _port = port

    if auto_submit_delay > 0:
        gobject.timeout_add_seconds(auto_submit_delay, anonymous_submit, True)


def update(bundle_id, report, log_file):
    if bundle_id not in _reports:
        _reports[bundle_id] = {}
    stat = _reports[bundle_id]

    for key, count in report.items():
        if key not in stat:
            stat[key] = 0
        stat[key] += count

    if log_file:
        _logs.add(log_file)


def is_empty():
    report, shell_log = feedback.flush()
    if report:
        if shell_log:
            shell_log = join(logger.get_logs_dir(), 'shell.log')
        update('shell', report, shell_log)

    return not _reports


def submit(message):
    from jarabe.journal import misc

    client = gconf.client_get_default()
    jabber = client.get_string('/desktop/sugar/collaboration/jabber_server')
    nick = client.get_string("/desktop/sugar/user/nick")

    data = {'message': message,
            'serial_number': '',
            'nick': '',
            'jabber_server': jabber,
            }
    _submit(data, False)


def anonymous_submit(implicit=False):
    from jarabe.journal import misc

    data = {}
    client = gconf.client_get_default()
    if client.get_bool('/desktop/sugar/feedback/anonymous_with_sn'):
        data['serial_number'] = misc.get_xo_serial()
    _submit(data, implicit)

    return True


def _submit(data, implicit):
    if data:
        _reports.update(data)
    if is_empty():
        return

    logging.debug('Sending feedback report: %r', _reports)

    report = simplejson.dumps(_reports)
    _reports.clear()

    tar_file = util.TempFilePath()
    tar = tarfile.open(tar_file, 'w:gz')

    while _logs:
        log_file = _logs.pop()
        if exists(log_file):
            tar.add(log_file, arcname=basename(log_file))

    report_file = tarfile.TarInfo('report')
    report_file.mode = 0644
    report_file.mtime = int(time.time())
    report_file.size = len(report)
    tar.addfile(report_file, StringIO(report))

    tar.close()

    _SubmitThread(tar_file, implicit).run()


class _SubmitThread(threading.Thread):

    def __init__(self, tar_file, implicit):
        threading.Thread.__init__(self)
        self._tar_file = tar_file
        self._implicit = implicit

    def run(self):
        try:
            message = _FormData()
            attachment = MIMEApplication(file(self._tar_file).read(),
                    _encoder=encode_noop)
            message.attach_file(attachment,
                    name='report', filename='report.tar.gz')
            body, headers = message.get_request_data()

            conn = httplib.HTTPSConnection(_host, _port)
            conn.request('POST', '/', body, headers)
            response = conn.getresponse()

            if response.status != 200:
                raise Exception('Incorrect feedback submit: %s, %s',
                        response.status, response.read())

        except Exception:
            title = _('Cannot submit feedback')
            msg = _('Feedback was not sent to %s:%s.') % (_host, _port)
            if not self._implicit:
                gobject.idle_add(lambda:
                        frame.get_view().add_message(summary=title, body=msg))
            logging.exception('%s: %s', title, msg)
        finally:
            os.unlink(self._tar_file)
            self._tar_file = None


class _FormData(MIMEMultipart):
    '''A simple RFC2388 multipart/form-data implementation.

    A snippet from http://bugs.python.org/issue3244

    '''

    def __init__(self, boundary=None, _subparts=None, **kwargs):
        MIMEMultipart.__init__(self, _subtype='form-data',
                boundary=boundary, _subparts=_subparts, **kwargs)

    def attach(self, subpart):
        if 'MIME-Version' in subpart:
            if subpart['MIME-Version'] != self['MIME-Version']:
                raise ValueError('subpart has incompatible MIME-Version')
            # Note: This isn't strictly necessary, but there is no point in
            # including a MIME-Version header in each subpart.
            del subpart['MIME-Version']
        MIMEMultipart.attach(self, subpart)

    def attach_file(self, subpart, name, filename):
        '''
        Attach a subpart, setting it's Content-Disposition header to "file".
        '''
        name = name.replace('"', '\\"')
        filename = filename.replace('"', '\\"')
        subpart['Content-Disposition'] = \
                'form-data; name="%s"; filename="%s"' % (name, filename)
        self.attach(subpart)

    def get_request_data(self, trailing_newline=True):
        '''Return the encoded message body.'''
        f = StringIO()
        generator = Generator(f, mangle_from_=False)
        # pylint: disable-msg=W0212
        generator._dispatch(self)
        # HTTP needs a trailing newline.  Since our return value is likely to
        # be passed directly to an HTTP connection, we might as well add it
        # here.
        if trailing_newline:
            f.write('\n')
        body = f.getvalue()
        headers = dict(self)
        return body, headers