summaryrefslogtreecommitdiff
path: root/service/pixelated/maintenance.py
blob: 3b216304a6fd32094254da03074fbc3bc0217cb1 (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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pixelated. If not, see <http://www.gnu.org/licenses/>.

from os.path import isfile
from mailbox import Maildir, mbox, MaildirMessage
import random

from leap.mail.adaptors.soledad import MetaMsgDocWrapper
from twisted.internet import reactor, defer
from twisted.internet.threads import deferToThread
from pixelated.adapter.mailstore.maintenance import SoledadMaintenance
from pixelated.config.leap import initialize_leap_single_user
from pixelated.config import logger, arguments
import logging

from leap.mail.constants import MessageFlags
from pixelated.support.mail_generator import MailGenerator

REPAIR_COMMAND = 'repair'
INTEGRITY_CHECK_COMMAND = 'integrity-check'


log = logging.getLogger(__name__)


def initialize():
    args = arguments.parse_maintenance_args()

    logger.init(debug=args.debug)

    @defer.inlineCallbacks
    def _run():
        leap_session = yield initialize_leap_single_user(
            args.leap_provider_cert,
            args.leap_provider_cert_fingerprint,
            args.credentials_file,
            leap_home=args.leap_home)

        execute_command(args, leap_session)

    reactor.callWhenRunning(_run)
    reactor.run()


def _is_repair_command(args):
    return args.command == REPAIR_COMMAND


def _is_integrity_check_command(args):
    return args.command == INTEGRITY_CHECK_COMMAND


def execute_command(args, leap_session):

    def init_soledad():
        return leap_session

    def get_soledad_handle(leap_session):
        soledad = leap_session.soledad

        return leap_session, soledad

    @defer.inlineCallbacks
    def soledad_sync(args):
        leap_session, soledad = args

        log.warn('Before sync')

        yield soledad.sync()

        log.warn('after sync')

        defer.returnValue(args)

    tearDown = defer.Deferred()

    prepare = deferToThread(init_soledad)
    prepare.addCallback(get_soledad_handle)
    prepare.addCallback(soledad_sync)
    add_command_callback(args, prepare, tearDown)
    tearDown.addCallback(soledad_sync)
    tearDown.addCallback(shutdown)
    tearDown.addErrback(shutdown_on_error)


def add_command_callback(args, prepareDeferred, finalizeDeferred):
    if args.command == 'reset':
        prepareDeferred.addCallback(delete_all_mails)
        prepareDeferred.addCallback(flush_to_soledad, finalizeDeferred)
    elif args.command == 'load-mails':
        prepareDeferred.addCallback(load_mails, args.file)
        prepareDeferred.addCallback(flush_to_soledad, finalizeDeferred)
    elif args.command == 'markov-generate':
        prepareDeferred.addCallback(markov_generate, args.file, int(args.limit), args.seed)
        prepareDeferred.addCallback(flush_to_soledad, finalizeDeferred)
    elif args.command == 'dump-soledad':
        prepareDeferred.addCallback(dump_soledad)
        prepareDeferred.chainDeferred(finalizeDeferred)
    elif args.command == 'sync':
        # nothing to do here, sync is already part of the chain
        prepareDeferred.chainDeferred(finalizeDeferred)
    elif args.command == INTEGRITY_CHECK_COMMAND:
        prepareDeferred.addCallback(integrity_check)
        prepareDeferred.chainDeferred(finalizeDeferred)
    elif args.command == REPAIR_COMMAND:
        prepareDeferred.addCallback(repair)
        prepareDeferred.chainDeferred(finalizeDeferred)
    else:
        print 'Unsupported command: %s' % args.command
        prepareDeferred.chainDeferred(finalizeDeferred)

    return finalizeDeferred


@defer.inlineCallbacks
def delete_all_mails(args):
    leap_session, soledad = args
    generation, docs = yield soledad.get_all_docs()

    for doc in docs:
        if doc.content.get('type', None) in ['head', 'cnt', 'flags']:
            soledad.delete_doc(doc)

    defer.returnValue(args)


def is_keep_file(mail):
    return mail['subject'] is None


def _is_new_mail(mail):
    return _is_maildir_msg(mail) and mail.get_subdir() == 'new'


def _is_maildir_msg(mail):
    return isinstance(mail, MaildirMessage)


@defer.inlineCallbacks
def _add_mail(store, folder_name, mail, flags, tags):
    created_mail = yield store.add_mail(folder_name, mail.as_string())
    leap_mail = yield store.get_mail(created_mail.mail_id)
    leap_mail.tags |= set(tags)
    for flag in flags:
        leap_mail.flags.add(flag)

    yield store.update_mail(leap_mail)


@defer.inlineCallbacks
def add_mail_folder(store, mailbox, folder_name, deferreds):
    yield store.add_mailbox(folder_name)

    for mail in mailbox:
        if is_keep_file(mail):
            continue

        if _is_maildir_msg(mail):
            flags = {MessageFlags.RECENT_FLAG} if _is_new_mail(mail) else set()

            if 'S' in mail.get_flags():
                flags = flags.add(MessageFlags.SEEN_FLAG)
            if 'R' in mail.get_flags():
                flags = flags.add(MessageFlags.ANSWERED_FLAG)
        else:
            flags = {MessageFlags.RECENT_FLAG}

        tags = mail['X-Tags'].split() if mail['X-Tags'] else []

        deferreds.append(_add_mail(store, folder_name, mail, flags, tags))


@defer.inlineCallbacks
def load_mails(args, mail_paths):
    leap_session, soledad = args
    store = leap_session.mail_store

    yield _load_mails_as_is(mail_paths, store)

    defer.returnValue(args)


@defer.inlineCallbacks
def _load_mails_as_is(mail_paths, store):
    deferreds = []

    for path in mail_paths:
        if isfile(path):
            mbox_mails = mbox(path, factory=None)
            yield add_mail_folder(store, mbox_mails, 'INBOX', deferreds)
        else:
            maildir = Maildir(path, factory=None)
            yield add_mail_folder(store, maildir, 'INBOX', deferreds)
            for mail_folder_name in maildir.list_folders():
                mail_folder = maildir.get_folder(mail_folder_name)
                yield add_mail_folder(store, mail_folder, mail_folder_name, deferreds)

    yield defer.gatherResults(deferreds, consumeErrors=True)


@defer.inlineCallbacks
def markov_generate(args, mail_paths, limit, seed):
    leap_session, soledad = args
    store = leap_session.mail_store

    username = leap_session.user_auth.username
    server_name = leap_session.provider.server_name

    markov_mails = _generate_mails(limit, mail_paths, seed, server_name, username)
    deferreds = []
    yield add_mail_folder(store, markov_mails, 'INBOX', deferreds)
    yield defer.gatherResults(deferreds, consumeErrors=True)

    defer.returnValue(args)


def _generate_mails(limit, mail_paths, seed, server_name, username):
    mails = []
    for path in mail_paths:
        mbox_mails = mbox(path, factory=None)
        mails.extend(mbox_mails)
    gen = MailGenerator(username, server_name, mails, random=random.Random(seed))
    markov_mails = [gen.generate_mail() for _ in range(limit)]
    return markov_mails


def flush_to_soledad(args, finalize):
    leap_session, soledad = args

    def after_sync(_):
        finalize.callback((leap_session, soledad))

    d = soledad.sync()
    d.addCallback(after_sync)

    return args


@defer.inlineCallbacks
def dump_soledad(args):
    leap_session, soledad = args

    generation, docs = yield soledad.get_all_docs()

    for doc in docs:
        print doc
        print '\n'

    defer.returnValue(args)


@defer.inlineCallbacks
def integrity_check(args):
    leap_session, soledad = args

    generation, docs = yield soledad.get_all_docs()

    known_docs = {}

    print 'Analysing %d docs\n' % len(docs)

    # learn about all docs
    for doc in docs:
        known_docs[doc.doc_id] = doc

    for doc in docs:
        if doc.doc_id.startswith('M-'):
            meta = MetaMsgDocWrapper(doc_id=doc.doc_id, **doc.content)

            # validate header doc
            if meta.hdoc not in known_docs:
                print 'Error: Could not find header doc %s for meta %s' % (meta.hdoc, doc.doc_id)

            if meta.fdoc not in known_docs:
                print 'Error: Could not find flags doc %s for meta %s' % (meta.fdoc, doc.doc_id)

            for cdoc in meta.cdocs:
                if cdoc not in known_docs:
                    print 'Error: Could not find content doc %s for meta %s' % (cdoc, meta.doc_id)

    defer.returnValue(args)


@defer.inlineCallbacks
def repair(args):
    leap_session, soledad = args

    yield SoledadMaintenance(soledad).repair()

    defer.returnValue(args)


def shutdown(args):
    # time.sleep(30)
    reactor.stop()


def shutdown_on_error(error):
    print error
    shutdown(None)

if __name__ == '__main__':
    initialize()