server.py 35.7 KB
Newer Older
1
2
3
4
#!/usr/bin/env python3
import locale
locale.setlocale(locale.LC_TIME, "de_DE.utf8")

Robin Sonnabend's avatar
Robin Sonnabend committed
5
from flask import Flask, g, current_app, request, session, flash, redirect, url_for, abort, render_template, Response, send_file
6
from werkzeug.utils import secure_filename
7
8
9
10
from flask_script import Manager, prompt
from flask_migrate import Migrate, MigrateCommand
#from flask_socketio import SocketIO
from celery import Celery
Robin Sonnabend's avatar
Robin Sonnabend committed
11
from io import StringIO, BytesIO
12
import os
Robin Sonnabend's avatar
Robin Sonnabend committed
13
from datetime import datetime
Robin Sonnabend's avatar
Robin Sonnabend committed
14
import math
15
16

import config
17
from shared import db, date_filter, datetime_filter, date_filter_long, time_filter, ldap_manager, security_manager, current_user, check_login, login_required, group_required, class_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
18
from utils import is_past, mail_manager, url_manager, get_first_unused_int, set_etherpad_text, get_etherpad_text, split_terms
19
from models.database import ProtocolType, Protocol, DefaultTOP, TOP, Document, Todo, Decision, MeetingReminder, Error
Robin Sonnabend's avatar
Robin Sonnabend committed
20
from views.forms import LoginForm, ProtocolTypeForm, DefaultTopForm, MeetingReminderForm, NewProtocolForm, DocumentUploadForm, KnownProtocolSourceUploadForm, NewProtocolSourceUploadForm, ProtocolForm, TopForm, SearchForm
Robin Sonnabend's avatar
Robin Sonnabend committed
21
from views.tables import ProtocolsTable, ProtocolTypesTable, ProtocolTypeTable, DefaultTOPsTable, MeetingRemindersTable, ErrorsTable, TodosTable, DocumentsTable, DecisionsTable
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)

def make_celery(app, config):
    celery = Celery(app.import_name, broker=config.CELERY_BROKER_URL)
    celery.conf.update(app.config)
    return celery
celery = make_celery(app, config)

#def make_socketio(app, config):
#    socketio = SocketIO(app)
#    return socketio
#socketio = make_socketio(app, config)

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.jinja_env.filters["datify"] = date_filter
app.jinja_env.filters["datetimify"] = datetime_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
45
46
app.jinja_env.filters["timify"] = time_filter
app.jinja_env.filters["datify_long"] = date_filter_long
47
app.jinja_env.filters["url_complete"] = url_manager.complete
48
app.jinja_env.filters["class"] = class_filter
49
app.jinja_env.tests["auth_valid"] = security_manager.check_user
50
51
52

import tasks

53
54
app.jinja_env.globals.update(check_login=check_login)
app.jinja_env.globals.update(current_user=current_user)
Robin Sonnabend's avatar
Robin Sonnabend committed
55
app.jinja_env.globals.update(zip=zip)
Robin Sonnabend's avatar
Robin Sonnabend committed
56
57
58
app.jinja_env.globals.update(min=min)
app.jinja_env.globals.update(max=max)
app.jinja_env.globals.update(dir=dir)
59

60
61
62
63
64
65
# blueprints here

@app.route("/")
def index():
    return render_template("index.html")

Robin Sonnabend's avatar
Robin Sonnabend committed
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
@login_required
@app.route("/types/list")
def list_types():
    is_logged_in = check_login()
    user = current_user()
    types = [
        protocoltype for protocoltype in ProtocolType.query.all()
        if (protocoltype.public_group in user.groups
        or protocoltype.private_group in user.groups
        or protocoltype.is_public)]
    types_table = ProtocolTypesTable(types)
    return render_template("types-list.html", types=types, types_table=types_table)

@app.route("/type/new", methods=["GET", "POST"])
@login_required
def new_type():
    form = ProtocolTypeForm()
    if form.validate_on_submit():
        user = current_user()
        if form.private_group.data not in user.groups:
            flash("Du kannst keinen internen Protokolltypen anlegen, zu dem du selbst keinen Zugang hast.", "alert-error")
        else:
            protocoltype = ProtocolType(form.name.data, form.short_name.data,
                form.organization.data, form.is_public.data,
                form.private_group.data, form.public_group.data,
Robin Sonnabend's avatar
Robin Sonnabend committed
91
92
                form.private_mail.data, form.public_mail.data,
                form.use_wiki.data, form.wiki_category.data,
Robin Sonnabend's avatar
Robin Sonnabend committed
93
                form.wiki_only_public.data, form.printer.data)
Robin Sonnabend's avatar
Robin Sonnabend committed
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
            db.session.add(protocoltype)
            db.session.commit()
            flash("Der Protokolltyp {} wurde angelegt.".format(protocoltype.name), "alert-success")
        return redirect(request.args.get("next") or url_for("list_types"))
    return render_template("type-new.html", form=form)

@app.route("/type/edit/<int:type_id>", methods=["GET", "POST"])
@login_required
def edit_type(type_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_private_view_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = ProtocolTypeForm(obj=protocoltype)
    if form.validate_on_submit():
        if form.private_group.data not in user.groups:
            flash("Du kannst keinen internen Protokolltypen anlegen, zu dem du selbst keinen Zugang hast.", "alert-error")
        else:
            form.populate_obj(protocoltype)
            db.session.commit()
            return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))
    return render_template("type-edit.html", form=form, protocoltype=protocoltype)

@app.route("/type/show/<int:type_id>")
@login_required
def show_type(type_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_private_view_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    protocoltype_table = ProtocolTypeTable(protocoltype)
    default_tops_table = DefaultTOPsTable(protocoltype.default_tops, protocoltype)
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
    reminders_table = MeetingRemindersTable(protocoltype.reminders, protocoltype)
    return render_template("type-show.html", protocoltype=protocoltype, protocoltype_table=protocoltype_table, default_tops_table=default_tops_table, reminders_table=reminders_table)

@app.route("/type/reminders/new/<int:type_id>", methods=["GET", "POST"])
@login_required
def new_reminder(type_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = MeetingReminderForm()
    if form.validate_on_submit():
        reminder = MeetingReminder(protocoltype.id, form.days_before.data, form.send_public.data, form.send_private.data)
        db.session.add(reminder)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))
    return render_template("reminder-new.html", form=form, protocoltype=protocoltype)

@app.route("/type/reminder/edit/<int:type_id>/<int:reminder_id>", methods=["GET", "POST"])
@login_required
def edit_reminder(type_id, reminder_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    reminder = MeetingReminder.query.filter_by(id=reminder_id).first()
    if reminder is None or reminder.protocoltype != protocoltype:
        flash("Invalide Erinnerung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = MeetingReminderForm(obj=reminder)
    if form.validate_on_submit():
        form.populate_obj(reminder)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))
    return render_template("reminder-edit.html", form=form, protocoltype=protocoltype, reminder=reminder)

@app.route("/type/reminder/delete/<int:type_id>/<int:reminder_id>")
@login_required
def delete_reminder(type_id, reminder_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    reminder = MeetingReminder.query.filter_by(id=reminder_id).first()
    if reminder is None or reminder.protocoltype != protocoltype:
        flash("Invalide Erinnerung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    db.session.delete(reminder)
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
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
@app.route("/type/tops/new/<int:type_id>", methods=["GET", "POST"])
@login_required
def new_default_top(type_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = DefaultTopForm()
    if form.validate_on_submit():
        default_top = DefaultTOP(protocoltype.id, form.name.data, form.number.data)
        db.session.add(default_top)
        db.session.commit()
        flash("Der Standard-TOP {} wurde für dem Protokolltyp {} hinzugefügt.".format(default_top.name, protocoltype.name), "alert-success")
        return redirect(request.args.get("next") or url_for("index"))
    return render_template("default-top-new.html", form=form, protocoltype=protocoltype)

@app.route("/type/tops/edit/<int:type_id>/<int:top_id>", methods=["GET", "POST"])
@login_required
def edit_default_top(type_id, top_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    default_top = DefaultTOP.query.filter_by(id=top_id).first()
    if default_top is None or default_top.protocoltype != protocoltype:
        flash("Invalider Standard-TOP.", "alert-error")
231
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
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
    form = DefaultTopForm(obj=default_top)
    if form.validate_on_submit():
        form.populate_obj(default_top)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))
    return render_template("default-top-edit.html", form=form, protocoltype=protocoltype, default_top=default_top)

@app.route("/type/tops/delete/<int:type_id>/<int:top_id>")
@login_required
def delete_default_top(type_id, top_id):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    default_top = DefaultTOP.query.filter_by(id=top_id).first()
    if default_top is None or default_top.protocoltype != protocoltype:
        flash("Invalider Standard-TOP.", "alert-error")
        return redirect(request.args.get("nexT") or url_for("index"))
    db.session.delete(default_top)
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))

@app.route("/type/tops/move/<int:type_id>/<int:top_id>/<diff>/")
@login_required
def move_default_top(type_id, top_id, diff):
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None:
        flash("Dieser Protokolltyp existiert nicht.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    user = current_user()
    if not protocoltype.has_modify_right(user):
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    default_top = DefaultTOP.query.filter_by(id=top_id).first()
    if default_top is None or default_top.protocoltype != protocoltype:
        flash("Invalider Standard-TOP.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
273
274
275
276
277
    try:
        default_top.number += int(diff)
        db.session.commit()
    except ValueError:
        flash("Die angegebene Differenz ist keine Zahl.", "alert-error")
Robin Sonnabend's avatar
Robin Sonnabend committed
278
279
    return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
280
281

@app.route("/protocols/list")
282
283
284
def list_protocols():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    protocoltype = None
    protocoltype_id = None
    try:
        protocoltype_id = int(request.args.get("protocoltype"))
    except (ValueError, TypeError):
        pass
    search_term = request.args.get("search")
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
    search_form = SearchForm(protocoltypes)
    if protocoltype_id is not None:
        search_form.protocoltype.data = protocoltype_id
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
    if search_term is not None:
        search_form.search.data = search_term
    protocol_query = Protocol.query
    if search_term is not None:
        match_target = Protocol.content_public
        if protocoltype is not None and protocoltype.has_private_view_right(user):
            match_target = Protocol.content_private
        for term in split_terms(search_term):
            protocol_query = protocol_query.filter(match_target.match("%{}%".format(term)))
306
    protocols = [
Robin Sonnabend's avatar
Robin Sonnabend committed
307
        protocol for protocol in protocol_query.all()
308
309
310
311
        if (not is_logged_in and protocol.protocoltype.is_public)
        or (is_logged_in and (
            protocol.protocoltype.public_group in user.groups
            or protocol.protocoltype.private_group in user.groups))]
Robin Sonnabend's avatar
Robin Sonnabend committed
312
313
314
315
316
317
318
319
320
321
322
323
324
    if protocoltype_id is not None and protocoltype_id != -1:
        protocols = [
            protocol for protocol in protocols
            if protocol.protocoltype.id == protocoltype_id
        ]
    protocols = sorted(protocols, key=lambda protocol: protocol.date, reverse=True)
    page = _get_page()
    page_count = int(math.ceil(len(protocols)) / config.PAGE_LENGTH)
    if page >= page_count:
        page = 0
    begin_index = page * config.PAGE_LENGTH
    end_index = (page + 1) * config.PAGE_LENGTH
    protocols = protocols[begin_index:end_index]
325
    protocols_table = ProtocolsTable(protocols)
Robin Sonnabend's avatar
Robin Sonnabend committed
326
    return render_template("protocols-list.html", protocols=protocols, protocols_table=protocols_table, search_form=search_form, page=page, page_count=page_count, page_diff=config.PAGE_DIFF, protocoltype_id=protocoltype_id, search_term=search_term)
Robin Sonnabend's avatar
Robin Sonnabend committed
327
328
329
330
331

@app.route("/protocol/new", methods=["GET", "POST"])
@login_required
def new_protocol():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
332
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
333
    form = NewProtocolForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
334
    upload_form = NewProtocolSourceUploadForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
335
336
337
338
339
340
341
342
    if form.validate_on_submit():
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype.data).first()
        if protocoltype is None or not protocoltype.has_modify_right(user):
            flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
            return redirect(request.args.get("next") or url_for("index"))
        protocol = Protocol(protocoltype.id, form.date.data)
        db.session.add(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
343
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
344
345
346
    type_id = request.args.get("type_id")
    if type_id is not None:
        form.protocoltype.data = type_id
Robin Sonnabend's avatar
Robin Sonnabend committed
347
    return render_template("protocol-new.html", form=form, upload_form=upload_form, protocoltypes=protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
348
349
350
351
352
353
354
355
356

@app.route("/protocol/show/<int:protocol_id>")
def show_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_public_view_right(user):
        flash("Invalides Protokoll.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    errors_table = ErrorsTable(protocol.errors)
Robin Sonnabend's avatar
Robin Sonnabend committed
357
358
359
360
361
362
    visible_documents = [
        document for document in protocol.documents
        if (not document.is_private and document.protocol.protocoltype.has_public_view_right(user))
        or (document.is_private and document.protocol.protocoltype.has_private_view_right(user))
    ]
    documents_table = DocumentsTable(visible_documents)
363
    document_upload_form = DocumentUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
364
365
    source_upload_form = KnownProtocolSourceUploadForm()
    return render_template("protocol-show.html", protocol=protocol, errors_table=errors_table, documents_table=documents_table, document_upload_form=document_upload_form, source_upload_form=source_upload_form)
Robin Sonnabend's avatar
Robin Sonnabend committed
366

Robin Sonnabend's avatar
Robin Sonnabend committed
367
368
369
370
371
372
373
374
375
@app.route("/protocol/delete/<int:protocol_id>")
@login_required
def delete_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = protocol.get_identifier()
Robin Sonnabend's avatar
Robin Sonnabend committed
376
    protocol.delete_orphan_todos()
Robin Sonnabend's avatar
Robin Sonnabend committed
377
378
379
380
381
    db.session.delete(protocol)
    db.session.commit()
    flash("Protokoll {} ist gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_protocols"))

Robin Sonnabend's avatar
Robin Sonnabend committed
382
@app.route("/protocol/etherpull/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
383
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
384
385
386
387
388
389
def etherpull_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
390
    protocol.source = get_etherpad_text(protocol.get_identifier())
Robin Sonnabend's avatar
Robin Sonnabend committed
391
392
393
394
395
    db.session.commit()
    tasks.parse_protocol(protocol)
    flash("Das Protokoll wird kompiliert.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
@app.route("/protocol/upload/known/<int:protocol_id>", methods=["POST"])
@login_required
def upload_source_to_known_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = KnownProtocolSourceUploadForm()
    if form.validate_on_submit():
        if form.source.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
        else:
            file = form.source.data
            if file.filename == "":
                flash("Es wurde keine Datei ausgewählt.", "alert-error")
            else:
                # todo: Prüfen, ob es Text ist?
                source = file.stream.read().decode("utf-8")
                protocol.source = source
                db.session.commit()
                tasks.parse_protocol(protocol)
                flash("Das Protokoll wird kompiliert.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

@app.route("/protocol/upload/new/", methods=["POST"])
@login_required
def upload_new_protocol():
    user = current_user()
    available_types = [
        protocoltype for protocoltype in ProtocolType.query.all()
        if protocoltype.has_modify_right(user)
    ]
    form = NewProtocolSourceUploadForm(protocoltypes=available_types)
    if form.validate_on_submit():
        if form.source.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
        else:
            file = form.source.data
            if file.filename == "":
                flash("Es wurde keine Datei ausgewählt.", "alert-error")
            else:
                source = file.stream.read().decode("utf-8")
                protocoltype = ProtocolType.query.filter_by(id=form.protocoltype.data).first()
                if protocoltype is None or not protocoltype.has_modify_right(user):
                    flash("Invalider Protokolltyp oder keine Rechte.", "alert-error")
                else:
                    protocol = Protocol(protocoltype.id, None, source)
                    db.session.add(protocol)
                    db.session.commit()
                    tasks.parse_protocol(protocol)
                    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    return redirect(request.args.get("fail") or url_for("new_protocol"))

Robin Sonnabend's avatar
Robin Sonnabend committed
450
451
452
453
454
455
456
457
458
459
460
@app.route("/protocol/source/<int:protocol_id>")
@login_required
def get_protocol_source(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    file_like = BytesIO(protocol.source.encode("utf-8"))
    return send_file(file_like, cache_timeout=1, as_attachment=True, attachment_filename="{}.txt".format(protocol.get_identifier()))

Robin Sonnabend's avatar
Robin Sonnabend committed
461
462
463
464
465
466
467
468
469
470
471
@app.route("/protocol/template/<int:protocol_id>")
@login_required
def get_protocol_template(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    file_like = BytesIO(protocol.get_template().encode("utf-8"))
    return send_file(file_like, cache_timeout=1, as_attachment=True, attachment_filename="{}-template.txt".format(protocol.get_identifier()))

Robin Sonnabend's avatar
Robin Sonnabend committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
@app.route("/protocol/etherpush/<int:protocol_id>")
@login_required
def etherpush_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    if set_etherpad_text(protocol.get_identifier(), protocol.get_template()):
        flash("Vorlage von {} in Etherpad hochgeladen.".format(protocol.get_identifier()), "alert-success")
    else:
        flash("Das Etherpad wurde bereits bearbeitet.", "alert-error")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
486
@app.route("/protocol/update/<int:protocol_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
487
488
489
490
491
492
493
@login_required
def update_protocol(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
494
    upload_form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
495
    edit_form = ProtocolForm(obj=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
496
497
498
499
    if edit_form.validate_on_submit():
        edit_form.populate_obj(protocol)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
500
    return render_template("protocol-update.html", upload_form=upload_form, edit_form=edit_form, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
501

Robin Sonnabend's avatar
Robin Sonnabend committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
@app.route("/protocol/tops/new/<int:protocol_id>", methods=["GET", "POST"])
@login_required
def new_top(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = TopForm()
    if form.validate_on_submit():
        top = TOP(protocol_id=protocol.id, name=form.name.data, number=form.number.data, planned=True)
        db.session.add(top)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    else:
        print(form.number.data)
        current_numbers = list(map(lambda t: t.number, protocol.tops))
        suggested_number = get_first_unused_int(current_numbers)
        form.number.data = suggested_number
    return render_template("top-new.html", form=form, protocol=protocol)

@app.route("/protocol/top/edit/<int:top_id>", methods=["GET", "POST"])
@login_required
def edit_top(top_id):
    user = current_user()
    top = TOP.query.filter_by(id=top_id).first()
    if top is None or not top.protocol.protocoltype.has_modify_right(user):
        flash("Invalider TOP oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = TopForm(obj=top)
    if form.validate_on_submit():
        form.populate_obj(top)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=top.protocol.id))
    return render_template("top-edit.html", form=form, top=top)

@app.route("/protocol/top/delete/<int:top_id>")
@login_required
def delete_top(top_id):
    user = current_user()
    top = TOP.query.filter_by(id=top_id).first()
    if top is None or not top.protocol.protocoltype.has_modify_right(user):
        flash("Invalider TOP oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = top.name
    protocol_id = top.protocol.id
    db.session.delete(top)
    db.session.commit()
    flash("Der TOP {} wurde gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))

@app.route("/protocol/top/move/<int:top_id>/<diff>")
@login_required
def move_top(top_id, diff):
    user = current_user()
    top = TOP.query.filter_by(id=top_id).first()
    if top is None or not top.protocol.protocoltype.has_modify_right(user):
        flash("Invalider TOP oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    try:
        top.number += int(diff)
        db.session.commit()
    except ValueError:
        flash("Die angegebene Differenz ist keine Zahl.", "alert-error")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=top.protocol.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
568
569
570
571
572
573
574
575
576
def _get_page():
    try:
        page = request.args.get("page")
        if page is None:
            return 0
        return int(page)
    except ValueError:
        return 0

577
@app.route("/todos/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
578
579
580
def list_todos():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
581
582
583
    protocoltype = None
    protocoltype_id = None
    try:
584
        protocoltype_id = int(request.args.get("protocoltype"))
Robin Sonnabend's avatar
Robin Sonnabend committed
585
586
587
    except (ValueError, TypeError):
        pass
    search_term = request.args.get("search")
Robin Sonnabend's avatar
Robin Sonnabend committed
588
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
589
590
    search_form = SearchForm(protocoltypes)
    if protocoltype_id is not None:
591
        search_form.protocoltype.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
592
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
593
594
    if search_term is not None:
        search_form.search.data = search_term
Robin Sonnabend's avatar
Robin Sonnabend committed
595
596
597
598
    todos = [
        todo for todo in Todo.query.all()
        if todo.protocoltype.has_public_view_right(user)
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
599
    if protocoltype_id is not None and protocoltype_id != -1:
Robin Sonnabend's avatar
Robin Sonnabend committed
600
601
602
603
        todos = [
            todo for todo in todos
            if todo.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
604
    if search_term is not None and len(search_term.strip()) > 0:
Robin Sonnabend's avatar
Robin Sonnabend committed
605
606
607
608
        todos = [
            todo for todo in todos
            if search_term.lower() in todo.description.lower()
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
609
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
610
    page_count = int(math.ceil(len(todos) / config.PAGE_LENGTH))
Robin Sonnabend's avatar
Robin Sonnabend committed
611
612
613
614
    if page >= page_count:
        page = 0
    begin_index = page * config.PAGE_LENGTH
    end_index = (page + 1) * config.PAGE_LENGTH
Robin Sonnabend's avatar
Robin Sonnabend committed
615
    todos = todos[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
616
    todos_table = TodosTable(todos)
Robin Sonnabend's avatar
Robin Sonnabend committed
617
    return render_template("todos-list.html", todos=todos, todos_table=todos_table, search_form=search_form, page=page, page_count=page_count, page_diff=config.PAGE_DIFF, protocoltype_id=protocoltype_id, search_term=search_term)
Robin Sonnabend's avatar
Robin Sonnabend committed
618

Robin Sonnabend's avatar
Robin Sonnabend committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
@app.route("/decisions/list")
def list_decisions():
    is_logged_In = check_login()
    user = current_user()
    protocoltype = None
    protocoltype_id = None
    try:
        protocoltype_id = int(request.args.get("protocoltype"))
    except (ValueError, TypeError):
        pass
    search_term = request.args.get("search")
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
    search_form = SearchForm(protocoltypes)
    if protocoltype_id is not None:
        search_form.protocoltype.data = protocoltype_id
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
    if search_term is not None:
        search_form.search.data = search_term
    decisions = [
        decision for decision in Decision.query.all()
        if decision.protocol.protocoltype.has_public_view_right(user)
    ]
    if protocoltype_id is not None and protocoltype_id != -1:
        decisions = [
            decision for decision in decisions 
            if decision.protocol.protocoltype.id == protocoltype_id
        ]
    if search_term is not None and len(search_term.strip()) > 0:
        decisions = [
            decision for decision in decisions
            if search_term.lower() in decision.content.lower()
        ]
    page = _get_page()
    page_count = int(math.ceil(len(decisions) / config.PAGE_LENGTH))
    if page >= page_count:
        page = 0
    begin_index = page * config.PAGE_LENGTH
    end_index = (page + 1) * config.PAGE_LENGTH
    decisions = decisions[begin_index:end_index]
    decisions_table = DecisionsTable(decisions)
    return render_template("decisions-list.html", decisions=decisions, decisions_table=decisions_table, search_form=search_form, page=page, page_count=page_count, page_diff=config.PAGE_DIFF, protocoltype_id=protocoltype_id, search_term=search_term)


662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
@app.route("/document/download/<int:document_id>")
def download_document(document_id):
    user = current_user()
    document = Document.query.filter_by(id=document_id).first()
    if document is None:
        flash("Invalides Dokument.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    if ((document.is_private
            and not document.protocol.protocoltype.has_private_view_right(user))
        or (not document.is_private
            and not document.protocol.protocoltype.has_public_view_right(user))):
        flash("Keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    with open(document.get_filename(), "rb") as file:
        file_like = BytesIO(file.read())
        return send_file(file_like, cache_timeout=1, as_attachment=True, attachment_filename=document.name)

@app.route("/document/upload/<int:protocol_id>", methods=["POST"])
@login_required
def upload_document(protocol_id):
    user = current_user()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocol is None or not protocol.protocoltype.has_modify_right(user):
Robin Sonnabend's avatar
Robin Sonnabend committed
685
        flash("Unzureichende Berechtigung.", "alert-error")
686
687
688
        return redirect(request.args.get("next") or url_for("index"))
    form = DocumentUploadForm()
    if form.document.data is None:
Robin Sonnabend's avatar
Robin Sonnabend committed
689
        flash("Es wurde keine Datei ausgewählt.", "alert-error")
690
691
692
        return redirect(request.args.get("next") or url_for("index"))
    file = form.document.data
    if file.filename == "":
Robin Sonnabend's avatar
Robin Sonnabend committed
693
        flash("Es wurde keine Datei ausgewählt.", "alert-error")
694
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
695
    # todo: Dateitypen einschränken?
696
697
    if file:
        filename = secure_filename(file.filename)
Robin Sonnabend's avatar
Robin Sonnabend committed
698
        document = Document(protocol.id, filename, "", False, form.private.data)
699
700
        db.session.add(document)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
        internal_filename = "{}-{}-{}".format(protocol.id, document.id, filename)
        document.filename = internal_filename
        file.save(os.path.join(config.DOCUMENTS_PATH, internal_filename))
        if datetime.now().date() >= protocol.date:
            protocol.done = True
        db.session.commit()
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

@app.route("/document/delete/<int:document_id>")
@login_required
def delete_document(document_id):
    user = current_user()
    document = Document.query.filter_by(id=document_id).first()
    if document is None or not document.protocol.protocoltype.has_modify_right(user):
        flash("Unzureichende Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = document.name
    protocol = document.protocol
    db.session.delete(document)
    db.session.commit()
    flash("Das Dokument {} wurde gelöscht.".format(name), "alert-success")
722
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
723

Robin Sonnabend's avatar
Robin Sonnabend committed
724
725
726
727
728
729
730
731
732
733
734
@app.route("/document/print/<int:document_id>")
@login_required
def print_document(document_id):
    user = current_user()
    document = Document.query.filter_by(id=document_id).first()
    if document is None or not document.protocol.protocoltype.has_modify_right(user):
        flash("Invalides Protokoll oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    tasks.print_file(document.get_filename(), document.protocol)
    flash("Das Dokument {} wird gedruckt.".format(document.name), "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=document.protocol.id))
735

736
737
738
739
@app.route("/login", methods=["GET", "POST"])
def login():
    if "auth" in session:
        flash("You are already logged in.", "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
740
        return redirect(request.args.get("next") or url_for("index"))
741
742
743
744
745
746
747
748
749
750
    form = LoginForm()
    if form.validate_on_submit():
        user = ldap_manager.login(form.username.data, form.password.data)
        if user is not None:
            session["auth"] = security_manager.hash_user(user)
            flash("Login successful, {}!".format(user.username), "alert-success")
            return redirect(request.args.get("next") or url_for("index"))
        else:
            flash("Wrong login data. Try again.", "alert-error")
    return render_template("login.html", form=form)
751

752
753
754
755
756
757
758
759
@app.route("/logout")
@login_required
def logout():
    if "auth" in session:
        session.pop("auth")
    else:
        flash("You are not logged in.", "alert-error")
    return redirect(url_for(".index"))
760
761
762
763


if __name__ == "__main__":
    manager.run()