tasks.py 36 KB
Newer Older
1
2
3
4
5
from flask import render_template

import os
import subprocess
import shutil
6
import tempfile
7
from datetime import datetime
Robin Sonnabend's avatar
Robin Sonnabend committed
8
import traceback
9
from copy import copy
10
import xmlrpc.client
11

12
from models.database import Document, Protocol, Error, Todo, Decision, TOP, DefaultTOP, MeetingReminder, TodoMail, DecisionDocument, TodoState, OldTodo, DecisionCategory
Robin Sonnabend's avatar
Robin Sonnabend committed
13
from models.errors import DateNotMatchingException
14
from server import celery, app
15
from shared import db, escape_tex, unhyphen, date_filter, datetime_filter, date_filter_long, date_filter_short, time_filter, class_filter, KNOWN_KEYS, WikiType
16
from utils import mail_manager, encode_kwargs, decode_kwargs, add_line_numbers, set_etherpad_text, get_etherpad_text, footnote_hash, parse_datetime_from_string
Robin Sonnabend's avatar
Robin Sonnabend committed
17
from protoparser import parse, ParserException, Element, Content, Text, Tag, Remark, Fork, RenderType
Robin Sonnabend's avatar
Robin Sonnabend committed
18
from wiki import WikiClient, WikiException
Robin Sonnabend's avatar
Robin Sonnabend committed
19
from calendarpush import Client as CalendarClient, CalendarException
20
from legacy import lookup_todo_id, import_old_todos
21
22
23
24
25
26
27
28
29
30
31
32
33
34

import config

texenv = app.create_jinja_environment()
texenv.block_start_string = r"\ENV{"
texenv.block_end_string = r"}"
texenv.variable_start_string = r"\VAR{"
texenv.variable_end_string = r"}"
texenv.comment_start_string = r"\COMMENT{"
texenv.comment_end_string = r"}"
texenv.filters["escape_tex"] = escape_tex
texenv.filters["unhyphen"] = unhyphen
texenv.trim_blocks = True
texenv.lstrip_blocks = True
Robin Sonnabend's avatar
Robin Sonnabend committed
35
#texenv.filters["url_complete"] = url_manager.complete
36
37
texenv.filters["datify"] = date_filter
texenv.filters["datify_long"] = date_filter_long
38
texenv.filters["datify_short"] = date_filter_short
39
40
texenv.filters["datetimify"] = datetime_filter
texenv.filters["timify"] = time_filter
41
texenv.filters["class"] = class_filter
42
43
44
45
46
47
48
49
50
51
52
53
54
55
logo_template = getattr(config, "LATEX_LOGO_TEMPLATE", None)
if logo_template is not None:
    texenv.globals["logo_template"] = logo_template
latex_geometry = getattr(config, "LATEX_GEOMETRY", "vmargin=1.5cm,hmargin={1.5cm,1.2cm},bindingoffset=8mm")
texenv.globals["latex_geometry"] = latex_geometry
raw_additional_packages = getattr(config, "LATEX_ADDITIONAL_PACKAGES", None)
additional_packages = []
if raw_additional_packages is not None:
    for package in raw_additional_packages:
        if "{" not in package:
            package = "{{{}}}".format(package)
        additional_packages.append(package)
texenv.globals["additional_packages"] = additional_packages
latex_pagestyle = getattr(config, "LATEX_PAGESTYLE", None)
56
if latex_pagestyle is not None and latex_pagestyle:
57
58
59
    texenv.globals["latex_pagestyle"] = latex_pagestyle
latex_header_footer = getattr(config, "LATEX_HEADER_FOOTER", False)
texenv.globals["latex_header_footer"] = latex_header_footer
60
61
62
63

mailenv = app.create_jinja_environment()
mailenv.trim_blocks = True
mailenv.lstrip_blocks = True
Robin Sonnabend's avatar
Robin Sonnabend committed
64
#mailenv.filters["url_complete"] = url_manager.complete
65
66
67
mailenv.filters["datify"] = date_filter
mailenv.filters["datetimify"] = datetime_filter

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
wikienv = app.create_jinja_environment()
wikienv.trim_blocks = True
wikienv.lstrip_blocks = True
wikienv.block_start_string = "<env>"
wikienv.block_end_string = "</env>"
wikienv.variable_start_string = "<var>"
wikienv.variable_end_string = "</var>"
wikienv.comment_start_string = "<comment>"
wikienv.comment_end_string = "</comment>"
wikienv.filters["datify"] = date_filter
wikienv.filters["datify_long"] = date_filter_long
wikienv.filters["datify_short"] = date_filter_short
wikienv.filters["datetimify"] = datetime_filter
wikienv.filters["timify"] = time_filter
wikienv.filters["class"] = class_filter


85
86
87
88
89
90
91
92
93
94
ID_FIELD_BEGINNING = "id "

def parse_protocol(protocol, **kwargs):
    parse_protocol_async.delay(protocol.id, encode_kwargs(kwargs))

@celery.task
def parse_protocol_async(protocol_id, encoded_kwargs):
    with app.app_context():
        with app.test_request_context("/"):
            try:
95
96
97
98
99
100
                kwargs = decode_kwargs(encoded_kwargs)
                protocol = Protocol.query.filter_by(id=protocol_id).first()
                if protocol is None:
                    raise Exception("No protocol given. Aborting parsing.")
                parse_protocol_async_inner(protocol, encoded_kwargs)
            except Exception as exc:
Robin Sonnabend's avatar
Robin Sonnabend committed
101
102
103
                stacktrace = traceback.format_exc()
                error = protocol.create_error("Parsing", "Exception",
                    "{}\n\n{}".format(str(exc), stacktrace))
104
105
                db.session.add(error)
                db.session.commit()
106
107
108
109
110
111

def parse_protocol_async_inner(protocol, encoded_kwargs):
    old_errors = list(protocol.errors)
    for error in old_errors:
        protocol.errors.remove(error)
    db.session.commit()
112
113
    if protocol.source is None or len(protocol.source.strip()) == 0:
        error = protocol.create_error("Parsing", "Protocol source is empty", "")
114
115
116
        db.session.add(error)
        db.session.commit()
        return
117
118
119
120
121
    if protocol.source == config.EMPTY_ETHERPAD:
        error = protocol.create_error("Parsing", "The etherpad is unmodified and does not contain a protocol.", protocol.source)
        db.session.add(error)
        db.session.commit()
        return
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    tree = None
    try:
        tree = parse(protocol.source)
    except ParserException as exc:
        context = ""
        if exc.linenumber is not None:
            source_lines = protocol.source.splitlines()
            start_index = max(0, exc.linenumber - config.ERROR_CONTEXT_LINES)
            end_index = min(len(source_lines) - 1, exc.linenumber + config.ERROR_CONTEXT_LINES)
            context = "\n".join(source_lines[start_index:end_index])
        if exc.tree is not None:
            context += "\n\nParsed syntax tree was:\n" + str(exc.tree.dump())
        error = protocol.create_error("Parsing", str(exc), context)
        db.session.add(error)
        db.session.commit()
        return
    remarks = {element.name: element for element in tree.children if isinstance(element, Remark)}
139
    required_fields = copy(KNOWN_KEYS)
Robin Sonnabend's avatar
Robin Sonnabend committed
140
141
    for default_meta in protocol.protocoltype.metas:
        required_fields.append(default_meta.key)
142
143
144
    if not config.PARSER_LAZY:
        missing_fields = [field for field in required_fields if field not in remarks]
        if len(missing_fields) > 0:
145
            error = protocol.create_error("Parsing", "Du hast vergessen, Metadaten anzugeben.", ", ".join(missing_fields))
146
            db.session.add(error)
Robin Sonnabend's avatar
Robin Sonnabend committed
147
            db.session.commit()
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
            return
    try:
        protocol.fill_from_remarks(remarks)
    except ValueError:
        error = protocol.create_error(
            "Parsing", "Invalid fields",
            "Date or time fields are not '%d.%m.%Y' respectively '%H:%M', "
            "but rather {}".format(
            ", ".join([
                remarks["Datum"].value.strip(),
                remarks["Beginn"].value.strip(),
                remarks["Ende"].value.strip()
            ])))
        db.session.add(error)
        db.session.commit()
        return
    except DateNotMatchingException as exc:
        error = protocol.create_error("Parsing", "Date not matching",
            "This protocol's date should be {}, but the protocol source says {}.".format(date_filter(exc.original_date) if exc.original_date is not None else "not present", date_filter(exc.protocol_date) if exc.protocol_date is not None else "not present"))
        db.session.add(error)
        db.session.commit()
        return
170
171
    # tags 
    tags = tree.get_tags()
Robin Sonnabend's avatar
Robin Sonnabend committed
172
173
    elements = tree.get_visible_elements(show_private=True)
    public_elements = tree.get_visible_elements(show_private=False)
174
175
176
177
178
179
180
181
182
    for tag in tags:
        if tag.name not in Tag.KNOWN_TAGS:
            error = protocol.create_error("Parsing", "Invalid tag",
                "The tag in line {} has the kind '{}', which is "
                "not defined. This is probably an error mit a missing "
                "semicolon.".format(tag.linenumber, tag.name))
            db.session.add(error)
            db.session.commit()
            return
183
    # todos
184
185
186
    old_todo_number_map = {}
    for todo in protocol.todos:
        old_todo_number_map[todo.description] = todo.get_id()
187
188
189
190
    protocol.delete_orphan_todos()
    db.session.commit()
    old_todos = list(protocol.todos)
    todo_tags = [tag for tag in tags if tag.name == "todo"]
191
    raw_todos = []
192
193
194
195
196
    for todo_tag in todo_tags:
        if len(todo_tag.values) < 2:
            error = protocol.create_error("Parsing", "Invalid todo-tag",
                "The todo tag in line {} needs at least "
                "information on who and what, "
197
198
                "but has less than that. This is probably "
                "a missing semicolon.".format(todo_tag.linenumber))
199
            db.session.add(error)
200
            db.session.commit()
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
            return
        who = todo_tag.values[0]
        what = todo_tag.values[1]
        field_id = None
        field_state = None
        field_date = None
        for other_field in todo_tag.values[2:]:
            other_field = other_field.strip()
            if len(other_field) == 0:
                continue
            if other_field.startswith(ID_FIELD_BEGINNING):
                try:
                    field_id = int(other_field[len(ID_FIELD_BEGINNING):])
                except ValueError:
                    error = protocol.create_error("Parsing", "Non-numerical todo ID",
                    "The todo in line {} has a nonnumerical ID, but needs "
                    "something like \"id 1234\"".format(todo_tag.linenumber))
218
219
220
                    db.session.add(error)
                    db.session.commit()
                    return
221
222
223
224
225
226
227
            else:
                try:
                    field_state = TodoState.from_name(other_field)
                except ValueError:
                    try:
                        field_date = datetime.strptime(other_field, "%d.%m.%Y")
                    except ValueError:
228
                        try:
229
                            field_state, field_date = TodoState.from_name_with_date(other_field.strip(), protocol=protocol)
230
231
                        except ValueError:
                            try:
232
                                field_state = TodoState.from_name_lazy(other_field)
233
234
235
                            except ValueError:
                                error = protocol.create_error("Parsing",
                                "Invalid field",
236
237
                                "The todo in line {} has the field '{}', but "
                                "this does neither match a date (\"%d.%m.%Y\") "
238
239
240
241
242
                                "nor a state.".format(
                                    todo_tag.linenumber, other_field))
                                db.session.add(error)
                                db.session.commit()
                                return
243
244
245
246
247
248
249
250
251
        raw_todos.append((who, what, field_id, field_state, field_date, todo_tag))
    for (_, _, field_id, _, _, _) in raw_todos:
        if field_id is not None:
            old_todos = [todo for todo in old_todos
                if todo.id != field_id]
    for todo in old_todos:
        protocol.todos.remove(todo)
    db.session.commit()
    for (who, what, field_id, field_state, field_date, todo_tag) in raw_todos:
252
253
254
255
256
257
258
259
        if field_state is None:
            field_state = TodoState.open
        if field_state.needs_date() and field_date is None:
            error = protocol.create_error("Parsing",
                "Todo missing date",
                "The todo in line {} has a state that needs a date, "
                "but the todo does not have one.".format(todo_tag.linenumber))
            db.session.add(error)
260
            db.session.commit()
261
262
263
264
265
266
267
268
269
270
271
272
            return
        who = who.strip()
        what = what.strip()
        todo = None
        if field_id is not None:
            todo = Todo.query.filter_by(number=field_id).first()
            if todo is None and not config.PARSER_LAZY:
                error = protocol.create_error("Parsing",
                "Invalid Todo ID",
                "The todo in line {} has the ID {}, but there is no "
                "Todo with that ID.".format(todo_tag.linenumber, field_id))
                db.session.add(error)
273
                db.session.commit()
274
                return
275
        if todo is None and field_id is None and what in old_todo_number_map:
276
            todo = Todo(protocoltype_id=protocol.protocoltype.id,
277
278
279
280
                who=who, description=what, state=field_state,
                date=field_date, number=old_todo_number_map[what])
            db.session.add(todo)
            db.session.commit()
281
282
283
284
285
286
        if todo is None:
            protocol_key = protocol.get_identifier()
            old_candidates = OldTodo.query.filter(
                OldTodo.protocol_key == protocol_key).all()
            if len(old_candidates) == 0:
                # new protocol
287
                todo = Todo(protocoltype_id=protocol.protocoltype.id,
288
289
290
291
292
293
294
295
296
297
298
                    who=who, description=what, state=field_state,
                    date=field_date)
                db.session.add(todo)
                db.session.commit()
                todo.number = field_id or todo.id
                db.session.commit()
            else:
                # old protocol
                number = field_id or lookup_todo_id(old_candidates, who, what)
                todo = Todo.query.filter_by(number=number).first()
                if todo is None:
299
                    todo = Todo(protocoltype_id=protocol.protocoltype.id,
300
301
302
303
304
                        who=who, description=what, state=field_state,
                        date=field_date, number=number)
                    db.session.add(todo)
                    db.session.commit()
        todo.protocols.append(protocol)
305
306
307
308
309
310
311
312
313
314
        is_newest_protocol = True
        for other_protocol in todo.protocols:
            if other_protocol.date > protocol.date:
                is_newest_protocol = False
                break
        if is_newest_protocol:
            todo.state = field_state
            todo.date = field_date
            todo.who = who
            todo.description = what
315
316
317
        db.session.commit()
        todo_tag.todo = todo
    # Decisions
Robin Sonnabend's avatar
Robin Sonnabend committed
318
319
320
321
322
323
324
325
326
327
    decision_tags = [tag for tag in tags if tag.name == "beschluss"]
    for decision_tag in decision_tags:
        if decision_tag not in public_elements:
            error = protocol.create_error("Parsing", "Decision in private context.",
                "The decision in line {} is in a private context, but decisions are "
                "and have to be public. Please move it to a public spot.".format(
                decision_tag.linenumber))
            db.session.add(error)
            db.session.commit()
            return
328
329
330
331
    old_decisions = list(protocol.decisions)
    for decision in old_decisions:
        protocol.decisions.remove(decision)
    db.session.commit()
332
    decisions_to_render = []
333
334
335
336
337
    for decision_tag in decision_tags:
        if len(decision_tag.values) == 0:
            error = protocol.create_error("Parsing", "Empty decision found.",
                "The decision in line {} is empty.".format(decision_tag.linenumber))
            db.session.add(error)
Robin Sonnabend's avatar
Robin Sonnabend committed
338
            db.session.commit()
339
            return
340
        decision_content = decision_tag.values[0]
341
342
        decision_categories = []
        for decision_category_name in decision_tag.values[1:]:
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
            decision_category = DecisionCategory.query.filter_by(protocoltype_id=protocol.protocoltype.id, name=decision_category_name).first()
            if decision_category is None:
                category_candidates = DecisionCategory.query.filter_by(protocoltype_id=protocol.protocoltype.id).all()
                category_names = [
                    "'{}'".format(category.name)
                    for category in category_candidates
                ]
                error = protocol.create_error("Parsing",
                    "Unknown decision category",
                    "The decision in line {} has the category {}, "
                    "but there is no such category. "
                    "Known categories are {}".format(
                        decision_tag.linenumber,
                        decision_category_name,
                        ", ".join(category_names)))
                db.session.add(error)
                db.session.commit()
                return
            else:
362
                decision_categories.append(decision_category)
363
        decision = Decision(protocol_id=protocol.id,
364
            content=decision_content)
365
366
        db.session.add(decision)
        db.session.commit()
367
368
        for decision_category in decision_categories:
            decision.categories.append(decision_category)
369
370
371
        decision_tag.decision = decision
        decisions_to_render.append((decision, decision_tag))
    for decision, decision_tag in decisions_to_render:
372
373
374
        decision_top = decision_tag.fork.get_top()
        decision_content = texenv.get_template("decision.tex").render(
            render_type=RenderType.latex, decision=decision,
Robin Sonnabend's avatar
Robin Sonnabend committed
375
            protocol=protocol, top=decision_top, show_private=True)
376
377
        maxdepth = decision_top.get_maxdepth()
        compile_decision(decision_content, decision, maxdepth=maxdepth)
Robin Sonnabend's avatar
Robin Sonnabend committed
378
379
380
381
382

    # Footnotes
    footnote_tags = [tag for tag in tags if tag.name == "footnote"]
    public_footnote_tags = [tag for tag in footnote_tags if tag in public_elements]

383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    # new Protocols
    protocol_tags = [tag for tag in tags if tag.name == "sitzung"]
    for protocol_tag in protocol_tags:
        if len(protocol_tag.values) not in {1, 2}:
            error = protocol.create_error("Parsing",
                "Falsche Verwendung von [sitzung;…].",
                "Der Tag \"sitzung\" benötigt immer ein Datum "
                "und optional eine Uhrzeit, also ein bis zwei Argumente. "
                "Stattdessen wurden {} übergeben, nämlich {}".format(
                len(protocol_tag.values),
                protocol_tag.values))
            db.session.add(error)
            db.ession.commit()
            return
        else:
            try:
                protocol_date = parse_datetime_from_string(
                    protocol_tag.values[0])
            except ValueError as exc:
                error = protocol.create_error("Parsing", "Invalides Datum",
                    "'{}' ist kein valides Datum.".format(
                        protocol_tag.values[0]))
                db.session.add(error)
                db.session.commit()
                return
            if len(protocol_tag.values) > 1:
                try:
                    protocol_time = datetime.strptime(protocol_tag.values[1], "%H:%M")
                except ValueError:
                    error = protocol.create_error("Parsing", "Invalide Uhrzeit",
                        "'{}' ist keine valide Uhrzeit.".format(
                            protocol_tag.values[1]))
                    db.session.add(error)
                    db.session.commit()
                    return
    for protocol_tag in protocol_tags:
        new_protocol_date = parse_datetime_from_string(protocol_tag.values[0])
        new_protocol_time = None
        if len(protocol_tag.values) > 1:
            new_protocol_time = datetime.strptime(protocol_tag.values[1], "%H:%M")
        Protocol.create_new_protocol(protocol.protocoltype,
            new_protocol_date, new_protocol_time)

Robin Sonnabend's avatar
Robin Sonnabend committed
426
    # TOPs
427
428
429
430
431
    old_tops = list(protocol.tops)
    for top in old_tops:
        protocol.tops.remove(top)
    tops = []
    for index, fork in enumerate((child for child in tree.children if isinstance(child, Fork))):
432
433
        top = TOP(protocol_id=protocol.id, name=fork.name, number=index,
            planned=False)
434
435
        db.session.add(top)
    db.session.commit()
436

Robin Sonnabend's avatar
Robin Sonnabend committed
437
438
    # render
    private_render_kwargs = {
439
        "protocol": protocol,
Robin Sonnabend's avatar
Robin Sonnabend committed
440
441
        "tree": tree,
        "footnotes": footnote_tags,
442
    }
Robin Sonnabend's avatar
Robin Sonnabend committed
443
444
445
446
    public_render_kwargs = copy(private_render_kwargs)
    public_render_kwargs["footnotes"] = public_footnote_tags
    render_kwargs = {True: private_render_kwargs, False: public_render_kwargs}
    
447
448
    maxdepth = tree.get_maxdepth()
    privacy_states = [False]
Robin Sonnabend's avatar
Robin Sonnabend committed
449
450
    content_private = render_template("protocol.txt", render_type=RenderType.plaintext, show_private=True, **private_render_kwargs)
    content_public = render_template("protocol.txt", render_type=RenderType.plaintext, show_private=False, **public_render_kwargs)
451
452
453
454
    if content_private != content_public:
        privacy_states.append(True)
    protocol.content_private = content_private
    protocol.content_public = content_public
455
    protocol.content_html_private = render_template("protocol.html",
Robin Sonnabend's avatar
Robin Sonnabend committed
456
        render_type=RenderType.html, show_private=True, **private_render_kwargs)
457
    protocol.content_html_public = render_template("protocol.html",
Robin Sonnabend's avatar
Robin Sonnabend committed
458
        render_type=RenderType.html, show_private=False, **public_render_kwargs)
459

460
    for show_private in privacy_states:
Robin Sonnabend's avatar
Robin Sonnabend committed
461
462
463
464
        latex_source = texenv.get_template("protocol.tex").render(
            render_type=RenderType.latex,
            show_private=show_private,
            **render_kwargs[show_private])
465
        compile(latex_source, protocol, show_private=show_private, maxdepth=maxdepth)
Robin Sonnabend's avatar
Robin Sonnabend committed
466

467
    if protocol.protocoltype.use_wiki:
468
469
470
471
472
473
474
475
476
        wiki_type = WikiType[getattr(config, "WIKI_TYPE", "MEDIAWIKI")]
        wiki_template = {
            WikiType.MEDIAWIKI: "protocol.wiki",
            WikiType.DOKUWIKI: "protocol.dokuwiki",
        }
        wiki_render_type = {
            WikiType.MEDIAWIKI: RenderType.wikitext,
            WikiType.DOKUWIKI: RenderType.dokuwiki,
        }
Robin Sonnabend's avatar
Robin Sonnabend committed
477
        show_private = not protocol.protocoltype.wiki_only_public
478
479
        wiki_source = wikienv.get_template(wiki_template[wiki_type]).render(
            render_type=wiki_render_type[wiki_type],
Robin Sonnabend's avatar
Robin Sonnabend committed
480
481
482
            show_private=show_private,
            **render_kwargs[show_private]
        ).replace("\n\n\n", "\n\n")
483
484
485
486
487
488
489
490
        if wiki_type == WikiType.MEDIAWIKI:
            wiki_infobox_source = wikienv.get_template("infobox.wiki").render(
                protocoltype=protocol.protocoltype)
            push_to_wiki(protocol, wiki_source, wiki_infobox_source,
                "Automatisch generiert vom Protokollsystem 3.0")
        elif wiki_type == WikiType.DOKUWIKI:
            push_to_dokuwiki(protocol, wiki_source,
                "Automatisch generiert vom Protokollsystem 3.0")
491
492
    protocol.done = True
    db.session.commit()
493

494
495
def push_to_wiki(protocol, content, infobox_content, summary):
    push_to_wiki_async.delay(protocol.id, content, infobox_content, summary)
Robin Sonnabend's avatar
Robin Sonnabend committed
496
497

@celery.task
498
def push_to_wiki_async(protocol_id, content, infobox_content, summary):
Robin Sonnabend's avatar
Robin Sonnabend committed
499
500
501
    with WikiClient() as wiki_client, app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        try:
502
503
504
            wiki_client.edit_page(
                title=protocol.protocoltype.get_wiki_infobox_title(),
                content=infobox_content,
505
                summary=summary)
Robin Sonnabend's avatar
Robin Sonnabend committed
506
507
508
            wiki_client.edit_page(
                title=protocol.get_wiki_title(),
                content=content,
509
                summary=summary)
Robin Sonnabend's avatar
Robin Sonnabend committed
510
511
        except WikiException as exc:
            error = protocol.create_error("Pushing to Wiki", "Pushing to Wiki failed.", str(exc))
512
513
514
515
516
517
            db.session.add(error)
            db.session.commit()

def push_to_dokuwiki(protocol, content, summary):
    push_to_dokuwiki_async.delay(protocol.id, content, summary)

Robin Sonnabend's avatar
Robin Sonnabend committed
518
@celery.task
519
520
521
522
523
524
525
526
527
def push_to_dokuwiki_async(protocol_id, content, summary):
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    with xmlrpc.client.ServerProxy(config.WIKI_API_URL) as proxy:
        if not proxy.wiki.putPage(protocol.get_wiki_title(),
            content, {"sum": "Automatisch generiert vom Protokollsystem 3."}):
            error = protocol.create_error("Pushing to Wiki",
                "Pushing to Wiki failed." "")
            db.session.add(error)
            db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
528

529
530
def compile(content, protocol, show_private, maxdepth):
   compile_async.delay(content, protocol.id, show_private=show_private, maxdepth=maxdepth)
Robin Sonnabend's avatar
Robin Sonnabend committed
531

532
533
def compile_decision(content, decision, maxdepth):
    compile_async.delay(content, decision.id, use_decision=True, maxdepth=maxdepth)
534
535

@celery.task
536
def compile_async(content, protocol_id, show_private=False, use_decision=False, maxdepth=5):
537
    with tempfile.TemporaryDirectory() as compile_dir, app.app_context():
Robin Sonnabend's avatar
Robin Sonnabend committed
538
539
540
541
542
543
544
        decision = None
        protocol = None
        if use_decision:
            decision = Decision.query.filter_by(id=protocol_id).first()
            protocol = decision.protocol
        else:
            protocol = Protocol.query.filter_by(id=protocol_id).first()
545
546
547
        try:
            current = os.getcwd()
            protocol_source_filename = "protocol.tex"
548
            protocol_target_filename = "protocol.pdf"
549
            protocol_class_filename = "protokoll2.cls"
550
551
552
            log_filename = "protocol.log"
            with open(os.path.join(compile_dir, protocol_source_filename), "w") as source_file:
                source_file.write(content)
553
554
            protocol2_class_source = texenv.get_template(protocol_class_filename).render(fonts=config.FONTS, maxdepth=maxdepth, bulletpoints=config.LATEX_BULLETPOINTS)
            with open(os.path.join(compile_dir, protocol_class_filename), "w") as protocol2_class_file:
555
                protocol2_class_file.write(protocol2_class_source)
556
557
558
559
560
561
562
563
564
565
            os.chdir(compile_dir)
            command = [
                "/usr/bin/xelatex",
                "-halt-on-error",
                "-file-line-error",
                protocol_source_filename
            ]
            subprocess.check_call(command, universal_newlines=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            subprocess.check_call(command, universal_newlines=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            os.chdir(current)
Robin Sonnabend's avatar
Robin Sonnabend committed
566
567
568
569
570
            document = None
            if not use_decision:
                for old_document in [document for document in protocol.documents if document.is_compiled and document.is_private == show_private]:
                    protocol.documents.remove(old_document)
                db.session.commit()
571
572
573
574
575
576
577
578
                document = Document(protocol_id=protocol.id,
                    name="protokoll{}_{}_{}.pdf".format(
                        "_intern" if show_private else "",
                        protocol.protocoltype.short_name,
                        date_filter_short(protocol.date)),
                    filename="",
                    is_compiled=True,
                    is_private=show_private)
Robin Sonnabend's avatar
Robin Sonnabend committed
579
            else:
580
581
582
583
584
585
                document = DecisionDocument(decision_id=decision.id,
                    name="beschluss_{}_{}_{}.pdf".format(
                        protocol.protocoltype.short_name,
                        date_filter_short(protocol.date),
                        decision.id),
                    filename="")
586
587
            db.session.add(document)
            db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
588
            target_filename = "compiled-{}-{}.pdf".format(document.id, "internal" if show_private else "public")
Robin Sonnabend's avatar
Robin Sonnabend committed
589
590
            if use_decision:
                target_filename = "decision-{}-{}-{}.pdf".format(protocol.id, decision.id, document.id)
591
            document.filename = target_filename
592
            shutil.copy(os.path.join(compile_dir, protocol_target_filename), os.path.join(config.DOCUMENTS_PATH, target_filename))
593
            db.session.commit()
Administrator's avatar
Administrator committed
594
            shutil.copy(os.path.join(compile_dir, log_filename), "/tmp/proto-tex.log")
595
596
597
598
599
        except subprocess.SubprocessError:
            log = ""
            total_log_filename = os.path.join(compile_dir, log_filename)
            if os.path.isfile(total_log_filename):
                with open(total_log_filename, "r") as log_file:
600
                    log = "Log:\n\n" + add_line_numbers(log_file.read())
601
602
            else:
                log = "Logfile not found."
603
604
605
606
            total_source_filename = os.path.join(compile_dir, protocol_source_filename)
            if os.path.isfile(total_source_filename):
                with open(total_source_filename, "r") as source_file:
                    log += "\n\nSource:\n\n" + add_line_numbers(source_file.read())
607
608
609
610
            total_class_filename = os.path.join(compile_dir, protocol_class_filename)
            if os.path.isfile(total_class_filename):
                with open(total_class_filename, "r") as class_file:
                    log += "\n\nClass:\n\n" + add_line_numbers(class_file.read())
611
612
613
614
615
            error = protocol.create_error("Compiling", "Compiling LaTeX failed", log)
            db.session.add(error)
            db.session.commit()
        finally:
            os.chdir(current)
616

Robin Sonnabend's avatar
Robin Sonnabend committed
617
618
619
620
621
622
623
624
625
626
def print_file(filename, protocol):
    if config.PRINTING_ACTIVE:
        print_file_async.delay(filename, protocol.id)

@celery.task
def print_file_async(filename, protocol_id):
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        if protocol.protocoltype.printer is None:
            error = protocol.create_error("Printing", "No printer configured.", "You don't have any printer configured for the protocoltype {}. Please do so before printing a protocol.".format(protocol.protocoltype.name))
627
628
            db.session.add(error)
            db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
        try:
            command = [
                "/usr/bin/lpr",
                "-H", config.PRINTING_SERVER,
                "-P", protocol.protocoltype.printer,
                "-U", config.PRINTING_USER,
                "-T", protocol.get_identifier(),
            ]
            for option in config.PRINTING_PRINTERS[protocol.protocoltype.printer]:
                command.extend(["-o", '"{}"'.format(option) if " " in option else option])
            command.append(filename)
            subprocess.check_call(command, universal_newlines=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except subprocess.SubprocessError:
            error = protocol.create_error("Printing", "Printing {} failed.".format(protocol.get_identifier()), "")
            db.session.add(error)
            db.session.commit()

Robin Sonnabend's avatar
Robin Sonnabend committed
646
647
def send_reminder(reminder, protocol):
    send_reminder_async.delay(reminder.id, protocol.id)
648
649

@celery.task
Robin Sonnabend's avatar
Robin Sonnabend committed
650
def send_reminder_async(reminder_id, protocol_id):
651
    with app.app_context():
Robin Sonnabend's avatar
Robin Sonnabend committed
652
653
        reminder = MeetingReminder.query.filter_by(id=reminder_id).first()
        protocol = Protocol.query.filter_by(id=protocol_id).first()
654
        reminder_text = render_template("reminder-mail.txt", reminder=reminder, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
655
        if reminder.send_public:
656
            print("sending public reminder mail to {}".format(protocol.protocoltype.public_mail))
657
658
659
            send_mail(protocol, protocol.protocoltype.public_mail,
                "Tagesordnung der {}".format(protocol.protocoltype.name),
                reminder_text, reply_to=protocol.protocoltype.public_mail)
Robin Sonnabend's avatar
Robin Sonnabend committed
660
        if reminder.send_private:
661
            print("sending private reminder mail to {}".format(protocol.protocoltype.private_mail))
662
663
664
            send_mail(protocol, protocol.protocoltype.private_mail,
                "Tagesordnung der {}".format(protocol.protocoltype.name),
                reminder_text, reply_to=protocol.protocoltype.private_mail)
Robin Sonnabend's avatar
Robin Sonnabend committed
665

666
667
668
669
670
671
672
673
674
675
676
677
678
679
def remind_finishing(protocol, delay_days, min_delay_days):
    remind_finishing.delay(protocol.id, delay_days, min_delay_days)

@celery.task
def remind_finishing(protocol_id, delay_days, min_delay_days):
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        mail_text = render_template("remind-finishing-mail.txt",
            protocol=protocol, delay_days=delay_days,
            min_delay_days=min_delay_days)
        send_mail(protocol, protocol.protocoltype.private_mail,
            "Unfertiges Protokoll der {}".format(protocol.protocoltype.name),
            mail_text, reply_to=protocol.protocoltype.private_mail)

680
def send_protocol_private(protocol):
681
    send_protocol_async.delay(protocol.id, show_private=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
682
    send_todomails_async.delay(protocol.id)
683

684
685
686
def send_protocol_public(protocol):
    send_protocol_async.delay(protocol.id, show_private=False)

687
688
689
690
691
692
@celery.task
def send_protocol_async(protocol_id, show_private):
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        to_addr = protocol.protocoltype.private_mail if show_private else protocol.protocoltype.public_mail
        subject = "{}{}-Protokoll vom {}".format("Internes " if show_private else "", protocol.protocoltype.short_name, date_filter(protocol.date))
693
        mail_content = render_template("protocol-mail.txt", protocol=protocol, show_private=show_private)
694
695
696
697
698
699
        appendix = [(document.name, document.as_file_like())
            for document in protocol.documents
            if show_private or not document.is_private
        ]
        send_mail(protocol, to_addr, subject, mail_content, appendix)

Robin Sonnabend's avatar
Robin Sonnabend committed
700
701
702
703
@celery.task
def send_todomails_async(protocol_id):
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
704
        all_todos = [
Administrator's avatar
Administrator committed
705
            todo for todo in Todo.query.all()
706
            if not todo.is_done()
Administrator's avatar
Administrator committed
707
            and todo.protocoltype == protocol.protocoltype
708
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
709
710
711
712
713
714
        users = {user for todo in all_todos for user in todo.get_users()}
        grouped_todos = {
            user: [todo for todo in all_todos if user in todo.get_users()]
            for user in users
        }
        subject = "Du hast noch was zu tun!"
715
716
717
718
719
720
721
722
723
        todomail_providers = getattr(config, "ADDITIONAL_TODOMAIL_PROVIDERS", None)
        additional_todomails = {}
        if todomail_providers:
            for provider in todomail_providers:
                todomail_dict = provider()
                for key in todomail_dict:
                    if key not in additional_todomails:
                        name, mail = todomail_dict[key]
                        additional_todomails[key] = TodoMail(name, mail)
Robin Sonnabend's avatar
Robin Sonnabend committed
724
725
        for user in users:
            todomail = TodoMail.query.filter(TodoMail.name.ilike(user)).first()
726
727
728
            if todomail is None:
                if user in additional_todomails:
                    todomail = additional_todomails[user]
Robin Sonnabend's avatar
Robin Sonnabend committed
729
730
731
732
733
734
735
            if todomail is None:
                error = protocol.create_error("Sending Todomail", "Sending Todomail failed.", "User {} has no Todo-Mail-Assignment.".format(user))
                db.session.add(error)
                db.session.commit()
                continue
            to_addr = todomail.get_formatted_mail()
            mail_content = render_template("todo-mail.txt", protocol=protocol, todomail=todomail, todos=grouped_todos[user])
736
737
            send_mail(protocol, to_addr, subject, mail_content,
                reply_to=protocol.protocoltype.private_mail)
738

739
def send_mail(protocol, to_addr, subject, content, appendix=None, reply_to=None):
Robin Sonnabend's avatar
Robin Sonnabend committed
740
    if to_addr is not None and len(to_addr.strip()) > 0:
741
        send_mail_async.delay(protocol.id, to_addr, subject, content, appendix, reply_to)
742

Robin Sonnabend's avatar
Robin Sonnabend committed
743
@celery.task
744
def send_mail_async(protocol_id, to_addr, subject, content, appendix, reply_to):
Robin Sonnabend's avatar
Robin Sonnabend committed
745
746
747
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        try:
748
            mail_manager.send(to_addr, subject, content, appendix, reply_to)
Robin Sonnabend's avatar
Robin Sonnabend committed
749
750
751
752
        except Exception as exc:
            error = protocol.create_error("Sending Mail", "Sending mail failed", str(exc))
            db.session.add(error)
            db.session.commit()
753

Robin Sonnabend's avatar
Robin Sonnabend committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def push_tops_to_calendar(protocol):
    push_tops_to_calendar_async.delay(protocol.id)

@celery.task
def push_tops_to_calendar_async(protocol_id):
    if not config.CALENDAR_ACTIVE:
        return
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
        if protocol.protocoltype.calendar == "":
            return
        description = render_template("calendar-tops.txt", protocol=protocol)
        try:
            client = CalendarClient(protocol.protocoltype.calendar)
            client.set_event_at(begin=protocol.get_datetime(),
                name=protocol.protocoltype.short_name, description=description)
        except CalendarException as exc:
            error = Protocol.create_error("Calendar",
                "Pushing TOPs to Calendar failed", str(exc))
            db.session.add(error)
            db.session.commit()
775
776

def set_etherpad_content(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
777
    set_etherpad_content_async.delay(protocol.id)
778
779
780
781
782

@celery.task
def set_etherpad_content_async(protocol_id):
    with app.app_context():
        protocol = Protocol.query.filter_by(id=protocol_id).first()
Administrator's avatar
Administrator committed
783
784
        identifier = protocol.get_identifier()
        return set_etherpad_text(identifier, protocol.get_template())
785