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

5
from flask import Flask, g, current_app, request, session, flash, redirect, url_for, abort, render_template, Response, send_file as flask_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 sqlalchemy import or_, and_
Robin Sonnabend's avatar
Robin Sonnabend committed
12
13
14
15
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
import atexit
Robin Sonnabend's avatar
Robin Sonnabend committed
16
from io import StringIO, BytesIO
17
import os
Robin Sonnabend's avatar
Robin Sonnabend committed
18
from datetime import datetime
Robin Sonnabend's avatar
Robin Sonnabend committed
19
import math
20
import mimetypes
21
22

import config
Robin Sonnabend's avatar
Robin Sonnabend committed
23
from shared import db, date_filter, datetime_filter, date_filter_long, date_filter_short, time_filter, ldap_manager, security_manager, current_user, check_login, login_required, group_required, class_filter, needs_date_test, todostate_name_filter, code_filter, indent_tab_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
24
from utils import is_past, mail_manager, url_manager, get_first_unused_int, set_etherpad_text, get_etherpad_text, split_terms, optional_int_arg
Robin Sonnabend's avatar
Robin Sonnabend committed
25
26
27
from models.database import ProtocolType, Protocol, DefaultTOP, TOP, Document, Todo, Decision, MeetingReminder, Error, TodoMail, DecisionDocument, TodoState, Meta, DefaultMeta
from views.forms import LoginForm, ProtocolTypeForm, DefaultTopForm, MeetingReminderForm, NewProtocolForm, DocumentUploadForm, KnownProtocolSourceUploadForm, NewProtocolSourceUploadForm, ProtocolForm, TopForm, SearchForm, NewProtocolFileUploadForm, NewTodoForm, TodoForm, TodoMailForm, DefaultMetaForm, MetaForm
from views.tables import ProtocolsTable, ProtocolTypesTable, ProtocolTypeTable, DefaultTOPsTable, MeetingRemindersTable, ErrorsTable, TodosTable, DocumentsTable, DecisionsTable, TodoTable, ErrorTable, TodoMailsTable, DefaultMetasTable
28
from legacy import import_old_todos, import_old_protocols, import_old_todomails
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

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)

Robin Sonnabend's avatar
Robin Sonnabend committed
48
49
50
51
52
def make_scheduler(app, config, function):
    scheduler = BackgroundScheduler()
    scheduler.start()
    scheduler.add_job(
        func=function,
Robin Sonnabend's avatar
Robin Sonnabend committed
53
        trigger=CronTrigger(hour='*', minute=30),
Robin Sonnabend's avatar
Robin Sonnabend committed
54
55
56
57
58
        id="scheduler",
        name="Do an action regularly",
        replace_existing=True)
    atexit.register(scheduler.shutdown)

59
60
61
62
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
63
app.jinja_env.filters["timify"] = time_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
64
app.jinja_env.filters["datify_short"] = date_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
65
app.jinja_env.filters["datify_long"] = date_filter_long
66
app.jinja_env.filters["url_complete"] = url_manager.complete
67
app.jinja_env.filters["class"] = class_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
68
69
app.jinja_env.filters["todo_get_name"] = todostate_name_filter
app.jinja_env.filters["code"] = code_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
70
app.jinja_env.filters["indent_tab"] = indent_tab_filter
71
app.jinja_env.tests["auth_valid"] = security_manager.check_user
Robin Sonnabend's avatar
Robin Sonnabend committed
72
app.jinja_env.tests["needs_date"] = needs_date_test
73
74
75

import tasks

76
77
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
78
app.jinja_env.globals.update(zip=zip)
Robin Sonnabend's avatar
Robin Sonnabend committed
79
80
81
app.jinja_env.globals.update(min=min)
app.jinja_env.globals.update(max=max)
app.jinja_env.globals.update(dir=dir)
82

83
84
# blueprints here

85
86
@manager.command
def import_legacy():
87
    """Import the old todos and protocols from an sql dump"""
88
    filename = prompt("SQL-file")
89
    #filename = "legacy.sql"
90
91
    with open(filename, "rb") as sqlfile:
        content = sqlfile.read().decode("utf-8")
92
93
        import_old_todos(content)
        import_old_protocols(content)
94
        import_old_todomails(content)
95
    
96
97
98
99
# cause uwsgi currently has a bug
def send_file(file_like, cache_timeout, as_attachment, attachment_filename):
    mimetype, _ = mimetypes.guess_type(attachment_filename)
    response = Response(file_like.read(), mimetype)
100
101
102
103
104
105
106
107
    if as_attachment:
        response.headers["Content-Disposition"] = 'attachment; filename="{}"'.format(attachment_filename)
    content_type = mimetype
    if mimetype.startswith("text/"):
        content_type = "{}; charset=utf-8".format(content_type)
    response.headers["Content-Type"] = content_type
    response.headers["Cache-Control"] = "public, max-age={}".format(cache_timeout)
    response.headers["Connection"] = "close"
108
    return response
109

110
111
@app.route("/")
def index():
Robin Sonnabend's avatar
Robin Sonnabend committed
112
113
114
115
116
    user = current_user()
    protocols = [
        protocol for protocol in Protocol.query.all()
        if protocol.protocoltype.has_public_view_right(user)
    ]
117
    def _protocol_sort_key(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
118
119
120
        if protocol.date is not None:
            return protocol.date
        return datetime.now().date()
Robin Sonnabend's avatar
Robin Sonnabend committed
121
    current_day = datetime.now().date()
Robin Sonnabend's avatar
Robin Sonnabend committed
122
    open_protocols = sorted(
Robin Sonnabend's avatar
Robin Sonnabend committed
123
124
125
126
127
        [
            protocol for protocol in protocols
            if not protocol.done
            and (protocol.date - current_day).days < config.MAX_INDEX_DAYS
        ],
128
        key=_protocol_sort_key
Robin Sonnabend's avatar
Robin Sonnabend committed
129
130
    )
    finished_protocols = sorted(
131
132
133
134
135
136
        [
            protocol for protocol in protocols
            if protocol.done
            and (protocol.has_public_view_right(user)
                or protocol.has_private_view_right(user))
        ],
137
138
        key=_protocol_sort_key,
        reverse=True
Robin Sonnabend's avatar
Robin Sonnabend committed
139
140
141
142
143
    )
    protocol = finished_protocols[0] if len(finished_protocols) > 0 else None
    todos = None
    if check_login():
        todos = [
144
            todo for todo in Todo.query.all()
145
            if todo.protocoltype.has_private_view_right(user)
146
            and not todo.is_done()
Robin Sonnabend's avatar
Robin Sonnabend committed
147
        ]
148
149
150
151
        def _todo_sort_key(todo):
            protocol = todo.get_first_protocol()
            return protocol.date if protocol.date is not None else datetime.now().date()
        todos = sorted(todos, key=_todo_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
152
153
    todos_table = TodosTable(todos) if todos is not None else None
    return render_template("index.html", open_protocols=open_protocols, protocol=protocol, todos=todos, todos_table=todos_table)
154

Robin Sonnabend's avatar
Robin Sonnabend committed
155
@app.route("/documentation")
Robin Sonnabend's avatar
Robin Sonnabend committed
156
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
157
def documentation():
Robin Sonnabend's avatar
Robin Sonnabend committed
158
159
160
    todostates = list(TodoState)
    name_to_state = TodoState.get_name_to_state()
    return render_template("documentation.html", todostates=todostates, name_to_state=name_to_state)
Robin Sonnabend's avatar
Robin Sonnabend committed
161

Robin Sonnabend's avatar
Robin Sonnabend committed
162
@app.route("/types/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
163
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
164
165
166
167
168
169
170
171
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)]
172
    types = sorted(types, key=lambda t: t.short_name)
Robin Sonnabend's avatar
Robin Sonnabend committed
173
174
175
176
177
178
179
180
181
182
183
184
185
    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,
Robin Sonnabend's avatar
Robin Sonnabend committed
186
                form.organization.data, form.usual_time.data, form.is_public.data,
187
                form.modify_group.data, form.private_group.data, form.public_group.data,
Robin Sonnabend's avatar
Robin Sonnabend committed
188
189
                form.private_mail.data, form.public_mail.data,
                form.use_wiki.data, form.wiki_category.data,
190
191
                form.wiki_only_public.data, form.printer.data,
                form.calendar.data)
Robin Sonnabend's avatar
Robin Sonnabend committed
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
            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)
232
    reminders_table = MeetingRemindersTable(protocoltype.reminders, protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
233
234
    metas_table = DefaultMetasTable(protocoltype.metas, protocoltype)
    return render_template("type-show.html", protocoltype=protocoltype, protocoltype_table=protocoltype_table, default_tops_table=default_tops_table, metas_table=metas_table, reminders_table=reminders_table, mail_active=config.MAIL_ACTIVE)
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
@app.route("/type/delete/<int:type_id>")
@login_required
def delete_type(type_id):
    user = current_user()
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None or not protocoltype.has_modify_right(user):
        flash("Invalider Protokolltyp oder fehlende Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = protocoltype.name
    db.session.delete(protocoltype) 
    db.session.commit()
    flash("Der Protokolltype {} wurde gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_types"))

250
251
252
253
254
255
256
257
258
259
260
261
262
@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():
Robin Sonnabend's avatar
Robin Sonnabend committed
263
        reminder = MeetingReminder(protocoltype.id, form.days_before.data, form.send_public.data, form.send_private.data, form.additional_text.data)
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
        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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
@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")
344
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    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
386
387
388
389
390
    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
391
392
    return redirect(request.args.get("next") or url_for("show_type", type_id=protocoltype.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
393
394

@app.route("/protocols/list")
395
396
397
def list_protocols():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    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
Robin Sonnabend's avatar
Robin Sonnabend committed
413
414
415
416
417
418
419
420
421
    shall_search = search_term is not None and len(search_term.strip()) > 0
    search_terms = []
    if shall_search:
        search_terms = list(map(str.lower, split_terms(search_term)))
        for term in search_terms:
            protocol_query = protocol_query.filter(or_(
                Protocol.content_public.ilike("%{}%".format(term)),
                Protocol.content_private.ilike("%{}%".format(term))
            ))
422
    protocols = [
Robin Sonnabend's avatar
Robin Sonnabend committed
423
        protocol for protocol in protocol_query.all()
424
425
426
427
        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
428
429
430
431
432
433
434
435
436
437
438
439
440
    def _matches_search(content):
        content = content.lower()
        for search_term in search_terms:
            if search_term.lower() not in content:
                return False
        return True
    def _matches_search_lazy(content):
        content = content.lower()
        for search_term in search_terms:
            if search_term.lower() in content:
                return True
        return False
    search_results = {} if shall_search else None
Robin Sonnabend's avatar
Robin Sonnabend committed
441
442
443
444
445
    if protocoltype_id is not None and protocoltype_id != -1:
        protocols = [
            protocol for protocol in protocols
            if protocol.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
446
447
448
449
450
    if shall_search:
        protocols = [
            protocol for protocol in protocols
            if (protocol.protocoltype.has_private_view_right(user)
                and _matches_search(protocol.content_private))
451
            or (protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
                and _matches_search(protocol.content_public))
        ]
        for protocol in protocols:
            content = protocol.content_private if protocol.protocoltype.has_private_view_right(user) else protocol.content_public
            lines = content.splitlines()
            matches = [line for line in lines if _matches_search_lazy(line)]
            formatted_lines = []
            for line in matches:
                parts = []
                lower_line = line.lower()
                last_index = 0
                while last_index < len(line):
                    index_candidates = list(filter(lambda t: t[0] != -1, 
                        [(lower_line.find(term, last_index), term) for term in search_terms]))
                    if len(index_candidates) == 0:
                        parts.append((line[last_index:], False))
                        break
                    else:
                        new_index, term = min(index_candidates, key=lambda t: t[0])
                        new_end_index = new_index + len(term)
                        parts.append((line[last_index:new_index], False))
                        parts.append((line[new_index:new_end_index], True))
                        last_index = new_end_index
                formatted_lines.append("".join([
                    "<b>{}</b>".format(text) if matched else text
                    for text, matched in parts
                ]))
            search_results[protocol] = "<br />\n".join(formatted_lines)
Robin Sonnabend's avatar
Robin Sonnabend committed
480
    protocols = sorted(protocols, key=lambda protocol: protocol.date, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
481
    page = _get_page()
482
    page_count = int(math.ceil(len(protocols) / config.PAGE_LENGTH))
Robin Sonnabend's avatar
Robin Sonnabend committed
483
484
485
486
487
    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]
Robin Sonnabend's avatar
Robin Sonnabend committed
488
    protocols_table = ProtocolsTable(protocols, search_results=search_results)
Robin Sonnabend's avatar
Robin Sonnabend committed
489
    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
490
491
492
493
494

@app.route("/protocol/new", methods=["GET", "POST"])
@login_required
def new_protocol():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
495
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
496
    form = NewProtocolForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
497
    upload_form = NewProtocolSourceUploadForm(protocoltypes)
498
    file_upload_form = NewProtocolFileUploadForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
499
500
501
502
503
504
505
506
    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
507
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
508
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
509
510
511
    type_id = request.args.get("type_id")
    if type_id is not None:
        form.protocoltype.data = type_id
512
513
        upload_form.protocoltype.data = type_id
    return render_template("protocol-new.html", form=form, upload_form=upload_form, file_upload_form=file_upload_form, protocoltypes=protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
514
515
516
517
518
519

@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):
520
        flash("Invalides Protokoll oder fehlende Zugriffsrechte.", "alert-error")
Robin Sonnabend's avatar
Robin Sonnabend committed
521
522
        return redirect(request.args.get("next") or url_for("index"))
    errors_table = ErrorsTable(protocol.errors)
Robin Sonnabend's avatar
Robin Sonnabend committed
523
524
    visible_documents = [
        document for document in protocol.documents
525
        if (not document.is_private and document.protocol.has_public_view_right(user))
Robin Sonnabend's avatar
Robin Sonnabend committed
526
527
528
        or (document.is_private and document.protocol.protocoltype.has_private_view_right(user))
    ]
    documents_table = DocumentsTable(visible_documents)
529
    document_upload_form = DocumentUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
530
531
    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
532

Robin Sonnabend's avatar
Robin Sonnabend committed
533
534
535
536
537
538
539
540
541
@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
542
    protocol.delete_orphan_todos()
Robin Sonnabend's avatar
Robin Sonnabend committed
543
544
545
546
547
    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
548
@app.route("/protocol/etherpull/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
549
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
550
551
552
553
554
555
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"))
556
557
558
    if not config.ETHERPAD_ACTIVE:
        flash("Die Etherpadfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
Robin Sonnabend's avatar
Robin Sonnabend committed
559
    protocol.source = get_etherpad_text(protocol.get_identifier())
Robin Sonnabend's avatar
Robin Sonnabend committed
560
561
562
563
564
    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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
@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()
594
    available_types = ProtocolType.get_modifiable_protocoltypes()
Robin Sonnabend's avatar
Robin Sonnabend committed
595
596
597
598
    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")
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
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
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        file = form.source.data
        if file.filename == "":
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        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")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        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"))

@app.route("/protocol/upload/new/file/", methods=["POST"])
@login_required
def upload_new_protocol_by_file():
    user = current_user()
    available_types = ProtocolType.get_modifiable_protocoltypes(user)
    form = NewProtocolFileUploadForm(protocoltypes=available_types)
    if form.validate_on_submit():
        if form.file.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        file = form.file.data
        if file.filename == "":
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        filename = secure_filename(file.filename)
        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")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        protocol = Protocol(protocoltype.id, datetime.now().date(), done=True)
        db.session.add(protocol)
        db.session.commit()
        document = Document(protocol.id, filename, "", False, form.private.data)
        db.session.add(document)
        db.session.commit()
        internal_filename = "{}-{}-{}".format(protocol.id, document.id, filename)
        document.filename = internal_filename
        file.save(os.path.join(config.DOCUMENTS_PATH, internal_filename))
        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
646
647
    return redirect(request.args.get("fail") or url_for("new_protocol"))

648
649


Robin Sonnabend's avatar
Robin Sonnabend committed
650
651
652
653
654
655
656
657
658
659
660
@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
661
662
663
664
665
666
667
668
669
670
671
@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
672
673
674
675
676
677
678
679
@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"))
680
681
682
    if not config.ETHERPAD_ACTIVE:
        flash("Die Etherpadfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
683
684
685
    if not protocol.is_done():
        tasks.set_etherpad_content(protocol)
    return redirect(request.args.get("next") or protocol.get_etherpad_link())
Robin Sonnabend's avatar
Robin Sonnabend committed
686

Robin Sonnabend's avatar
Robin Sonnabend committed
687
@app.route("/protocol/update/<int:protocol_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
688
689
690
691
692
693
694
@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
695
    upload_form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
696
    edit_form = ProtocolForm(obj=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
697
698
699
    if edit_form.validate_on_submit():
        edit_form.populate_obj(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
700
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
701
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
702
    return render_template("protocol-update.html", upload_form=upload_form, edit_form=edit_form, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
703

704
705
706
707
708
709
710
711
712
713
714
715
716
@app.route("/protocol/publish/<int:protocol_id>")
@login_required
def publish_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"))
    protocol.public = True
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))


717
718
719
720
721
722
723
724
@app.route("/prococol/send/<int:protocol_id>")
@login_required
def send_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"))
725
726
727
    if not config.MAIL_ACTIVE:
        flash("Die Mailfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
728
729
730
731
732
    tasks.send_protocol(protocol)
    flash("Das Protokoll wurde versandt.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    

Robin Sonnabend's avatar
Robin Sonnabend committed
733
734
735
736
737
738
739
740
741
742
743
744
745
@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()
Robin Sonnabend's avatar
Robin Sonnabend committed
746
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    else:
        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()
Robin Sonnabend's avatar
Robin Sonnabend committed
766
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
767
768
769
770
771
772
773
774
775
776
777
778
        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
Robin Sonnabend's avatar
Robin Sonnabend committed
779
    protocol = top.protocol
Robin Sonnabend's avatar
Robin Sonnabend committed
780
781
    db.session.delete(top)
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
782
    tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
783
    flash("Der TOP {} wurde gelöscht.".format(name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
784
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
785
786
787
788
789
790
791
792
793
794
795
796

@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()
Robin Sonnabend's avatar
Robin Sonnabend committed
797
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
798
799
800
801
    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
802
803
804
805
806
807
808
809
810
def _get_page():
    try:
        page = request.args.get("page")
        if page is None:
            return 0
        return int(page)
    except ValueError:
        return 0

811
@app.route("/todos/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
812
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
813
814
def list_todos():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
815
816
817
    protocoltype = None
    protocoltype_id = None
    try:
818
        protocoltype_id = int(request.args.get("protocoltype"))
Robin Sonnabend's avatar
Robin Sonnabend committed
819
820
821
    except (ValueError, TypeError):
        pass
    search_term = request.args.get("search")
Robin Sonnabend's avatar
Robin Sonnabend committed
822
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
823
824
    search_form = SearchForm(protocoltypes)
    if protocoltype_id is not None:
825
        search_form.protocoltype.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
826
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
827
828
    if search_term is not None:
        search_form.search.data = search_term
Robin Sonnabend's avatar
Robin Sonnabend committed
829
830
831
832
    todos = [
        todo for todo in Todo.query.all()
        if todo.protocoltype.has_public_view_right(user)
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
833
    if protocoltype_id is not None and protocoltype_id != -1:
Robin Sonnabend's avatar
Robin Sonnabend committed
834
835
836
837
        todos = [
            todo for todo in todos
            if todo.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
838
    if search_term is not None and len(search_term.strip()) > 0:
Robin Sonnabend's avatar
Robin Sonnabend committed
839
840
841
842
        todos = [
            todo for todo in todos
            if search_term.lower() in todo.description.lower()
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
843
844
    def _sort_key(todo):
        first_protocol = todo.get_first_protocol()
845
        result = (not todo.is_done(), first_protocol.date if first_protocol is not None else datetime.now().date())
Robin Sonnabend's avatar
Robin Sonnabend committed
846
847
        return result
    todos = sorted(todos, key=_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
848
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
849
    page_count = int(math.ceil(len(todos) / config.PAGE_LENGTH))
Robin Sonnabend's avatar
Robin Sonnabend committed
850
851
852
853
    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
854
    todos = todos[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
855
    todos_table = TodosTable(todos)
Robin Sonnabend's avatar
Robin Sonnabend committed
856
    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
857

Robin Sonnabend's avatar
Robin Sonnabend committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
@app.route("/todo/new", methods=["GET", "POST"])
@login_required
def new_todo():
    user = current_user()
    protocoltype_id = optional_int_arg("type_id")
    protocol_id = optional_int_arg("protocol_id")
    protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
    protocol = Protocol.query.filter_by(id=protocol_id).first()
    if protocoltype is not None and protocol is not None:
        if protocol.protocoltype != protocoltype:
            flash("Ungültige Protokoll-Typ-Kombination", "alert-error")
            return redirect(request.args.get("next") or url_for("index"))
    if protocoltype is None and protocol is not None:
        protocoltype = protocol.protocoltype
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
    form = NewTodoForm(protocoltypes)
    if form.validate_on_submit():
        added_protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
        if added_protocoltype is None or not added_protocoltype.has_modify_right(user):
            flash("Invalider Protokolltyp.")
            return redirect(request.args.get("next") or url_for("index"))
        todo = Todo(type_id=form.protocoltype_id.data, who=form.who.data,
            description=form.description.data, tags=form.tags.data,
            done=form.done.data)
        if protocol is not None:
            todo.protocols.append(protocol)
        db.session.add(todo)
        db.session.commit()
        todo.number = todo.id
        db.session.commit()
        flash("Todo wurde angelegt.", "alert-success")
        if protocol is not None:
            return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
        else:
            return redirect(request.args.get("next") or url_for("list_todos", protocoltype_id=protocoltype_id))
    else:
        if protocoltype is not None:
            form.protocoltype_id.data = protocoltype.id
    return render_template("todo-new.html", form=form, protocol=protocol, protocoltype=protocoltype)

@app.route("/todo/edit/<int:todo_id>", methods=["GET", "POST"])
@login_required
def edit_todo(todo_id):
    user = current_user()
    todo = Todo.query.filter_by(id=todo_id).first()
    if todo is None or not todo.protocoltype.has_modify_right(user):
        flash("Invalides Todo oder unzureichende Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = TodoForm(obj=todo)
    if form.validate_on_submit():
        form.populate_obj(todo)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("list_todos", protocoltype=todo.protocoltype.id))
    return render_template("todo-edit.html", form=form, todo=todo)

@app.route("/todo/show/<int:todo_id>")
@login_required
def show_todo(todo_id):
    user = current_user()
    todo = Todo.query.filter_by(id=todo_id).first()
    if todo is None or not todo.protocoltype.has_private_view_right(user):
        flash("Invalides Todo oder unzureichende Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    todo_table = TodoTable(todo)
    return render_template("todo-show.html", todo=todo, todo_table=todo_table)

@app.route("/todo/delete/<int:todo_id>")
@login_required
def delete_todo(todo_id):
    user = current_user()
    todo = Todo.query.filter_by(id=todo_id).first()
    if todo is None or not todo.protocoltype.has_private_view_right(user):
        flash("Invalides Todo oder unzureichende Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    type_id = todo.protocoltype.id
    db.session.delete(todo)
    db.session.commit()
    flash("Todo gelöscht.", "alert-success")
    return redirect(request.args.get("next") or url_for("list_todos", protocoltype=type_id))

Robin Sonnabend's avatar
Robin Sonnabend committed
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
@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()
958
        if decision.protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
959
960
961
962
963
964
965
966
967
968
969
    ]
    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()
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
970
971
    decisions = sorted(decisions, key=lambda d: d.protocol.date, reverse=True)
        
Robin Sonnabend's avatar
Robin Sonnabend committed
972
973
974
975
976
977
978
979
980
981
982
    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)


983
984
985
986
987
988
989
990
991
992
@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
993
            and not document.protocol.has_public_view_right(user))):
994
995
        flash("Keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
996
    return send_file(document.as_file_like(), cache_timeout=1, as_attachment=True, attachment_filename=document.name)
997
998
999
1000
1001
1002
1003

@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
1004
        flash("Unzureichende Berechtigung.", "alert-error")
1005
1006
1007
        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
1008
        flash("Es wurde keine Datei ausgewählt.", "alert-error")
1009
1010
1011
        return redirect(request.args.get("next") or url_for("index"))
    file = form.document.data
    if file.filename == "":
Robin Sonnabend's avatar
Robin Sonnabend committed
1012
        flash("Es wurde keine Datei ausgewählt.", "alert-error")
1013
        return redirect(request.args.get("next") or url_for("index"))
Robin Sonnabend's avatar
Robin Sonnabend committed
1014
    # todo: Dateitypen einschränken?
1015
1016
    if file:
        filename = secure_filename(file.filename)
Robin Sonnabend's avatar
Robin Sonnabend committed
1017
        document = Document(protocol.id, filename, "", False, form.private.data)
1018
1019
        db.session.add(document)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
        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")
1041
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
1042

Robin Sonnabend's avatar
Robin Sonnabend committed
1043
1044
1045
1046
1047
1048
1049
1050
@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"))
1051
1052
1053
    if not config.PRINTING_ACTIVE:
        flash("Die Druckfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=document.protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
1054
1055
1056
    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))
1057

Robin Sonnabend's avatar
Robin Sonnabend committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
@app.route("/decision/print/<int:document_id>")
@login_required
def print_decision(document_id):
    user = current_user()
    document = DecisionDocument.query.filter_by(id=document_id).first()
    if document is None or not document.decision.protocol.protocoltype.has_modify_right(user):
        flash("Invalides Dokument oder keine Berechtigung.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    if not config.PRINTING_ACTIVE:
        flash("Die Druckfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=document.decision.protocol.id))
    tasks.print_file(document.get_filename(), document.decision.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.decision.protocol.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
@app.route("/errors/list")
@login_required
def list_errors():
    user = current_user()
    errors = [
        error for error in Error.query.all()
        if error.protocol.protocoltype.has_private_view_right(user)
    ]
    errors_table = ErrorsTable(errors)
    return render_template("errors-list.html", errros=errors, errors_table=errors_table)

@app.route("/error/show/<int:error_id>")
@login_required
def show_error(error_id):
    user = current_user()
    error = Error.query.filter_by(id=error_id).first()
    if error is None or not error.protocol.protocoltype.has_modify_right(user):
        flash("Invalider Fehler oder fehlende Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    error_table = ErrorTable(error)
    return render_template("error-show.html", error=error, error_table=error_table)

@app.route("/error/delete/<int:error_id>")
@login_required
def delete_error(error_id):
    user = current_user()
    error = Error.query.filter_by(id=error_id).first()
    if error is None or not error.protocol.protocoltype.has_modify_right(user):
        flash("Invalider Fehler oder fehlende Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = error.name
    db.session.delete(error)
    db.session.commit()
    flash("Fehler {} gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_errors"))
Robin Sonnabend's avatar
Robin Sonnabend committed
1108
1109
1110
1111

@app.route("/todomails/list")
@login_required
def list_todomails():
1112
    todomails = sorted(TodoMail.query.all(), key=lambda tm: tm.name)
Robin Sonnabend's avatar
Robin Sonnabend committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
    todomails_table = TodoMailsTable(todomails)
    return render_template("todomails-list.html", todomails=todomails, todomails_table=todomails_table)

@app.route("/todomail/new", methods=["GET", "POST"])
@login_required
def new_todomail():
    form = TodoMailForm()
    if form.validate_on_submit():
        todomail = TodoMail(form.name.data, form.mail.data)
        db.session.add(todomail)
        db.session.commit()
        flash("Die Todomailzuordnung für {} wurde angelegt.".format(todomail.name), "alert-success")
        return redirect(request.args.get("next") or url_for("list_todomails"))
    return render_template("todomail-new.html", form=form)

@app.route("/todomail/edit/<int:todomail_id>", methods=["GET", "POST"])
@login_required
def edit_todomail(todomail_id):
    todomail = TodoMail.query.filter_by(id=todomail_id).first()
    if todomail is None:
        flash("Invalide Todo-Mail-Zuordnung.", "alert-error")
        return redirect(request.args.get("next") or url_for("list_todomails"))
    form = TodoMailForm(obj=todomail)
    if form.validate_on_submit():
        form.populate_obj(todomail)
        db.session.commit()
        flash("Die Todo-Mail-Zuordnung wurde geändert.", "alert-success")
        return redirect(request.args.get("next") or url_for("list_todomails"))
    return render_template("todomail-edit.html", todomail=todomail, form=form)

@app.route("/todomail/delete/<int:todomail_id>")
@login_required
def delete_todomail(todomail_id):
    todomail = TodoMail.query.filter_by(id=todomail_id).first()
    if todomail is None:
        flash("Invalide Todomailzuordnung.", "alert-error")
        return redirect(request.args.get("next") or url_for("list_todomails"))
    name = todomail.name
    db.session.delete(todomail)
    db.session.commit()
    flash("Die Todo-Mail-Zuordnung für {} wurde gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_todomails"))
Robin Sonnabend's avatar
Robin Sonnabend committed
1155
    
Robin Sonnabend's avatar
Robin Sonnabend committed
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
@app.route("/defaultmeta/new/<int:type_id>", methods=["GET", "POST"])
@login_required
def new_defaultmeta(type_id):
    user = current_user()
    protocoltype = ProtocolType.query.filter_by(id=type_id).first()
    if protocoltype is None or not protocoltype.has_modify_right(user):
        flash("Invalider Protokolltyp oder unzureichende Rechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = DefaultMetaForm()
    if form.validate_on_submit():
        meta = DefaultMeta(protocoltype_id=type_id, key=form.key.data,
            name=form.name.data)
        db.session.add(meta)
        db.session.commit()
        flash("Metadatenfeld hinzugefügt.", "alert-success")
        return redirect(request.args.get("next") or url_for("show_type", type_id=type_id))
    return render_template("defaultmeta-new.html", form=form, protocoltype=protocoltype)

@app.route("/defaultmeta/edit/<int:meta_id>", methods=["GET", "POST"])
@login_required
def edit_defaultmeta(meta_id):
    user = current_user()
    meta = DefaultMeta.query.filter_by(id=meta_id).first()
    if meta is None or not meta.protocoltype.has_modify_right(user):
        flash("Invalider Protokolltyp oder unzureichende Rechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    form = DefaultMetaForm(obj=meta)
    if form.validate_on_submit():
        form.populate_obj(meta)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_type", type_id=meta.protocoltype.id))
    return render_template("defaultmeta-edit.html", form=form, meta=meta)

@app.route("/defaultmeta/delete/<int:meta_id>")
@login_required
def delete_defaultmeta(meta_id):
    user = current_user()
    meta = DefaultMeta.query.filter_by(id=meta_id).first()
    if meta is None or not meta.protocoltype.has_modify_right(user):
        flash("Invalider Protokolltyp oder unzureichende Rechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("index"))
    name = meta.name
    type_id = meta.protocoltype.id
    db.session.delete(meta)
    db.session.delete()
    flash("Metadatenfeld '{}' gelöscht.", "alert-error")
    return redirect(request.args.get("next") or url_for("show_type", type_id=type_id))
Robin Sonnabend's avatar
Robin Sonnabend committed
1203

1204
1205
1206
1207
@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
1208
        return redirect(request.args.get("next") or url_for("index"))
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
    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)
1219

1220
1221
1222
1223
1224
1225
1226
1227
@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"))
1228

Robin Sonnabend's avatar
Robin Sonnabend committed
1229
def check_and_send_reminders():
1230
1231
    if not config.MAIL_ACTIVE:
        return
Robin Sonnabend's avatar
Robin Sonnabend committed
1232
1233
1234
    with app.app_context():
        current_time = datetime.now()
        current_day = current_time.date()
1235
        print("regular action for reminders")
Robin Sonnabend's avatar
Robin Sonnabend committed
1236
1237
1238
1239
1240
        for protocol in Protocol.query.filter(Protocol.done == False).all():
            day_difference = (protocol.date - current_day).days
            usual_time = protocol.protocoltype.usual_time
            protocol_time = datetime(1, 1, 1, usual_time.hour, usual_time.minute)
            hour_difference = (protocol_time - current_time).seconds // 3600
1241
            print("diff: {} days, {} hours".format(day_difference, hour_difference))
Robin Sonnabend's avatar
Robin Sonnabend committed
1242
            for reminder in protocol.protocoltype.reminders:
1243
                print(reminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
1244
                if day_difference == reminder.days_before and hour_difference == 0:
1245
                    print("reminder matching, sending")
Robin Sonnabend's avatar
Robin Sonnabend committed
1246
                    tasks.send_reminder(reminder, protocol)
1247
1248

if __name__ == "__main__":
Robin Sonnabend's avatar
Robin Sonnabend committed
1249
    make_scheduler(app, config, check_and_send_reminders)
1250
    manager.run()