server.py 55.8 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_
12
13
14
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
Robin Sonnabend's avatar
Robin Sonnabend committed
15
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
23
from shared import db, date_filter, datetime_filter, date_filter_long, date_filter_short, time_filter, time_filter_short, 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
from decorators import db_lookup, require_public_view_right, require_private_view_right, require_modify_right, require_admin_right
26
27
from models.database import ProtocolType, Protocol, DefaultTOP, TOP, LocalTOP, Document, Todo, Decision, MeetingReminder, Error, TodoMail, DecisionDocument, TodoState, Meta, DefaultMeta, DecisionCategory
from views.forms import LoginForm, ProtocolTypeForm, DefaultTopForm, MeetingReminderForm, NewProtocolForm, DocumentUploadForm, KnownProtocolSourceUploadForm, NewProtocolSourceUploadForm, ProtocolForm, TopForm, LocalTopForm, SearchForm, DecisionSearchForm, ProtocolSearchForm, TodoSearchForm, NewProtocolFileUploadForm, NewTodoForm, TodoForm, TodoMailForm, DefaultMetaForm, MetaForm, MergeTodosForm, DecisionCategoryForm
28
from views.tables import ProtocolsTable, ProtocolTypesTable, ProtocolTypeTable, DefaultTOPsTable, MeetingRemindersTable, ErrorsTable, TodosTable, DocumentsTable, DecisionsTable, TodoTable, ErrorTable, TodoMailsTable, DefaultMetasTable, DecisionCategoriesTable
29
from legacy import import_old_todos, import_old_protocols, import_old_todomails
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

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
53
app.jinja_env.filters["timify"] = time_filter
54
app.jinja_env.filters["timify_short"] = time_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
55
app.jinja_env.filters["datify_short"] = date_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
56
app.jinja_env.filters["datify_long"] = date_filter_long
57
app.jinja_env.filters["url_complete"] = url_manager.complete
58
app.jinja_env.filters["class"] = class_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
59
60
app.jinja_env.filters["todo_get_name"] = todostate_name_filter
app.jinja_env.filters["code"] = code_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
61
app.jinja_env.filters["indent_tab"] = indent_tab_filter
62
app.jinja_env.tests["auth_valid"] = security_manager.check_user
Robin Sonnabend's avatar
Robin Sonnabend committed
63
app.jinja_env.tests["needs_date"] = needs_date_test
64
65
66

import tasks

67
68
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
69
app.jinja_env.globals.update(zip=zip)
Robin Sonnabend's avatar
Robin Sonnabend committed
70
71
72
app.jinja_env.globals.update(min=min)
app.jinja_env.globals.update(max=max)
app.jinja_env.globals.update(dir=dir)
73

74
75
# blueprints here

76
77
@manager.command
def import_legacy():
78
    """Import the old todos and protocols from an sql dump"""
79
    filename = prompt("SQL-file")
80
    #filename = "legacy.sql"
81
82
    with open(filename, "rb") as sqlfile:
        content = sqlfile.read().decode("utf-8")
83
84
        import_old_todos(content)
        import_old_protocols(content)
85
        import_old_todomails(content)
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@manager.command
def recompile_all():
    for protocol in sorted(Protocol.query.all(), key=lambda p: p.date):
        if protocol.is_done():
            print(protocol.get_identifier())
            tasks.parse_protocol(protocol)

@manager.command
def merge_todos():
    todo_by_id = {}
    todos = Todo.query.all()
    for todo in todos:
        todo_id = todo.get_id()
        if todo_id in todo_by_id:
            todo1, todo2 = todo, todo_by_id[todo_id]
            print(todo1)
            print(todo2)
            if todo2.id > todo1.id:
                todo2, todo1 = todo1, todo2
            for protocol in todo2.protocols:
                if protocol not in todo1.protocols:
                    todo1.protocols.append(protocol)
                todo2.protocols.remove(protocol)
            db.session.delete(todo2)
            db.session.commit()
            todo_by_id[todo_id] = todo1
        else:
            todo_by_id[todo_id] = todo

@manager.command
def runserver():
118
    app.run()
119
120
    make_scheduler()

121
122
123
124
# 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)
125
126
127
128
129
130
131
132
    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"
133
    return response
134

135
136
@app.route("/")
def index():
Robin Sonnabend's avatar
Robin Sonnabend committed
137
138
139
    user = current_user()
    protocols = [
        protocol for protocol in Protocol.query.all()
140
141
        if protocol.protocoltype.has_public_view_right(user,
            check_networks=False)
Robin Sonnabend's avatar
Robin Sonnabend committed
142
    ]
143
    def _protocol_sort_key(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
144
145
146
        if protocol.date is not None:
            return protocol.date
        return datetime.now().date()
Robin Sonnabend's avatar
Robin Sonnabend committed
147
    current_day = datetime.now().date()
148
    open_protocols = sorted(
Robin Sonnabend's avatar
Robin Sonnabend committed
149
150
151
152
153
        [
            protocol for protocol in protocols
            if not protocol.done
            and (protocol.date - current_day).days < config.MAX_INDEX_DAYS
        ],
154
        key=_protocol_sort_key
Robin Sonnabend's avatar
Robin Sonnabend committed
155
156
    )
    finished_protocols = sorted(
157
158
159
160
161
        [
            protocol for protocol in protocols
            if protocol.done
            and (protocol.has_public_view_right(user)
                or protocol.has_private_view_right(user))
162
            and protocol.protocoltype.has_public_view_right(user)
163
        ],
164
165
        key=_protocol_sort_key,
        reverse=True
Robin Sonnabend's avatar
Robin Sonnabend committed
166
167
168
169
170
    )
    protocol = finished_protocols[0] if len(finished_protocols) > 0 else None
    todos = None
    if check_login():
        todos = [
171
            todo for todo in Todo.query.all()
172
            if todo.protocoltype.has_private_view_right(user)
173
            and not todo.is_done()
Robin Sonnabend's avatar
Robin Sonnabend committed
174
        ]
175
176
177
178
        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
179
    todos_table = TodosTable(todos) if todos is not None else None
180
    return render_template("index.html", open_protocols=open_protocols, protocol=protocol, todos=todos)
181

Robin Sonnabend's avatar
Robin Sonnabend committed
182
@app.route("/documentation")
Robin Sonnabend's avatar
Robin Sonnabend committed
183
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
184
def documentation():
Robin Sonnabend's avatar
Robin Sonnabend committed
185
186
187
    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
188

Robin Sonnabend's avatar
Robin Sonnabend committed
189
@app.route("/types/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
190
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
191
192
193
194
195
196
197
198
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)]
199
    types = sorted(types, key=lambda t: t.short_name)
Robin Sonnabend's avatar
Robin Sonnabend committed
200
201
202
203
204
205
206
207
208
209
210
211
    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:
212
213
            protocoltype = ProtocolType()
            form.populate_obj(protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
214
215
216
217
218
219
            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)

Robin Sonnabend's avatar
Robin Sonnabend committed
220
@app.route("/type/edit/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
221
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
222
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
223
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
224
def edit_type(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
225
226
227
228
229
230
231
232
    user = current_user()
    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()
Robin Sonnabend's avatar
Robin Sonnabend committed
233
            return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
234
235
    return render_template("type-edit.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
236
@app.route("/type/show/<int:protocoltype_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
237
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
238
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
239
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
240
def show_type(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
241
242
    protocoltype_table = ProtocolTypeTable(protocoltype)
    default_tops_table = DefaultTOPsTable(protocoltype.default_tops, protocoltype)
243
    reminders_table = MeetingRemindersTable(protocoltype.reminders, protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
244
    metas_table = DefaultMetasTable(protocoltype.metas, protocoltype)
245
246
    categories_table = DecisionCategoriesTable(protocoltype.decisioncategories, 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, categories_table=categories_table)
247

Robin Sonnabend's avatar
Robin Sonnabend committed
248
@app.route("/type/delete/<int:protocoltype_id>")
249
@login_required
250
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
251
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
252
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
253
def delete_type(protocoltype):
254
255
256
257
258
259
    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"))

Robin Sonnabend's avatar
Robin Sonnabend committed
260
@app.route("/type/reminders/new/<int:protocoltype_id>", methods=["GET", "POST"])
261
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
262
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
263
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
264
def new_reminder(protocoltype):
265
266
    form = MeetingReminderForm()
    if form.validate_on_submit():
267
268
        meetingreminder = MeetingReminder(protocoltype_id=protocoltype.id)
        form.populate_obj(meetingreminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
269
        db.session.add(meetingreminder)
270
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
271
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
272
273
    return render_template("reminder-new.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
274
@app.route("/type/reminder/edit/<int:meetingreminder_id>", methods=["GET", "POST"])
275
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
276
@db_lookup(MeetingReminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
277
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
278
279
def edit_reminder(meetingreminder):
    form = MeetingReminderForm(obj=meetingreminder)
280
    if form.validate_on_submit():
Robin Sonnabend's avatar
Robin Sonnabend committed
281
        form.populate_obj(meetingreminder)
282
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
283
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
284
    return render_template("reminder-edit.html", form=form, meetingreminder=meetingreminder)
285

Robin Sonnabend's avatar
Robin Sonnabend committed
286
@app.route("/type/reminder/delete/<int:meetingreminder_id>")
287
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
288
@db_lookup(MeetingReminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
289
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
290
291
292
def delete_reminder(meetingreminder):
    protocoltype = meetingreminder.protocoltype
    db.session.delete(meetingreminder)
293
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
294
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
295

Robin Sonnabend's avatar
Robin Sonnabend committed
296
@app.route("/type/tops/new/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
297
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
298
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
299
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
300
def new_default_top(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
301
302
    form = DefaultTopForm()
    if form.validate_on_submit():
303
304
        defaulttop = DefaultTOP(protocoltype_id=protocoltype.id)
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
305
        db.session.add(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
306
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
307
        flash("Der Standard-TOP {} wurde für dem Protokolltyp {} hinzugefügt.".format(defaulttop.name, protocoltype.name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
308
309
310
        return redirect(request.args.get("next") or url_for("index"))
    return render_template("default-top-new.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
311
@app.route("/type/tops/edit/<int:protocoltype_id>/<int:defaulttop_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
312
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
313
@db_lookup(ProtocolType, DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
314
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
315
316
def edit_default_top(protocoltype, defaulttop):
    form = DefaultTopForm(obj=defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
317
    if form.validate_on_submit():
Robin Sonnabend's avatar
Robin Sonnabend committed
318
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
319
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
320
321
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
    return render_template("default-top-edit.html", form=form, protocoltype=protocoltype, defaulttop=defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
322

Robin Sonnabend's avatar
Robin Sonnabend committed
323
@app.route("/type/tops/delete/<int:defaulttop_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
324
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
325
@db_lookup(DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
326
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
327
328
def delete_default_top(defaulttop):
    db.session.delete(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
329
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
330
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
331

Robin Sonnabend's avatar
Robin Sonnabend committed
332
@app.route("/type/tops/move/<int:defaulttop_id>/<diff>/")
Robin Sonnabend's avatar
Robin Sonnabend committed
333
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
334
@db_lookup(DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
335
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
336
def move_default_top(defaulttop, diff):
Robin Sonnabend's avatar
Robin Sonnabend committed
337
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
338
        defaulttop.number += int(diff)
Robin Sonnabend's avatar
Robin Sonnabend committed
339
340
341
        db.session.commit()
    except ValueError:
        flash("Die angegebene Differenz ist keine Zahl.", "alert-error")
Robin Sonnabend's avatar
Robin Sonnabend committed
342
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=defaulttop.protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
343
344

@app.route("/protocols/list")
345
346
347
def list_protocols():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
348
349
350
    protocoltype = None
    protocoltype_id = None
    try:
351
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
352
353
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
354
    state_open = -1
Robin Sonnabend's avatar
Robin Sonnabend committed
355
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
356
        state_open = int(request.args.get("state_open"))
Robin Sonnabend's avatar
Robin Sonnabend committed
357
358
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
359
360
    search_term = request.args.get("search")
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
361
    search_form = ProtocolSearchForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
362
    if protocoltype_id is not None:
363
        search_form.protocoltype_id.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
364
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
365
366
    if state_open is not None:
        search_form.state_open.data = state_open
Robin Sonnabend's avatar
Robin Sonnabend committed
367
368
369
    if search_term is not None:
        search_form.search.data = search_term
    protocol_query = Protocol.query
Robin Sonnabend's avatar
Robin Sonnabend committed
370
371
372
373
374
375
376
377
378
    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))
            ))
379
    protocols = [
Robin Sonnabend's avatar
Robin Sonnabend committed
380
        protocol for protocol in protocol_query.all()
381
        if protocol.protocoltype.has_public_view_right(user, check_networks=False)
382
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
383
384
385
386
387
388
389
390
391
392
393
394
395
    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
396
397
398
399
400
    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
401
402
    if state_open is not None and state_open != -1:
        protocol_done = bool(state_open)
Robin Sonnabend's avatar
Robin Sonnabend committed
403
404
405
406
        protocols = [
            protocol for protocol in protocols
            if protocol.is_done() == protocol_done
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
407
408
409
410
411
    if shall_search:
        protocols = [
            protocol for protocol in protocols
            if (protocol.protocoltype.has_private_view_right(user)
                and _matches_search(protocol.content_private))
412
            or (protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
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
                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
                ]))
440
            search_results[protocol] = " …<br />\n".join(formatted_lines)
Robin Sonnabend's avatar
Robin Sonnabend committed
441
    protocols = sorted(protocols, key=lambda protocol: protocol.date, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
442
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
443
444
    page_length = _get_page_length()
    page_count = int(math.ceil(len(protocols) / page_length))
Robin Sonnabend's avatar
Robin Sonnabend committed
445
446
    if page >= page_count:
        page = 0
Robin Sonnabend's avatar
Robin Sonnabend committed
447
448
449
    begin_index = page * page_length
    end_index = (page + 1) * page_length
    max_page_length_exp = math.ceil(math.log10(len(protocols)))
Robin Sonnabend's avatar
Robin Sonnabend committed
450
    protocols = protocols[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
451
    protocols_table = ProtocolsTable(protocols, search_results=search_results)
Robin Sonnabend's avatar
Robin Sonnabend committed
452
    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, state_open=state_open, page_length=page_length, max_page_length_exp=max_page_length_exp)
Robin Sonnabend's avatar
Robin Sonnabend committed
453
454
455
456
457

@app.route("/protocol/new", methods=["GET", "POST"])
@login_required
def new_protocol():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
458
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
459
    form = NewProtocolForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
460
    upload_form = NewProtocolSourceUploadForm(protocoltypes)
461
    file_upload_form = NewProtocolFileUploadForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
462
    if form.validate_on_submit():
463
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
464
465
466
        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"))
467
468
        protocol = Protocol(protocoltype_id=protocoltype.id)
        form.populate_obj(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
469
470
        db.session.add(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
471
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
472
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
473
    type_id = request.args.get("protocoltype_id")
Robin Sonnabend's avatar
Robin Sonnabend committed
474
475
    if type_id is not None:
        form.protocoltype.data = type_id
476
477
        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
478
479

@app.route("/protocol/show/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
480
481
@db_lookup(Protocol)
def show_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
482
483
    user = current_user()
    errors_table = ErrorsTable(protocol.errors)
484
    if not protocol.protocoltype.has_public_view_right(user, check_networks=False): # yes, feature
Robin Sonnabend's avatar
Robin Sonnabend committed
485
        flash("Die fehlen die nötigen Zugriffsrechte.", "alert-error")
486
        return redirect(request.args.get("next") or url_for("login", next=request.url))
Robin Sonnabend's avatar
Robin Sonnabend committed
487
488
    visible_documents = [
        document for document in protocol.documents
489
        if (not document.is_private and document.protocol.has_public_view_right(user))
Robin Sonnabend's avatar
Robin Sonnabend committed
490
491
492
        or (document.is_private and document.protocol.protocoltype.has_private_view_right(user))
    ]
    documents_table = DocumentsTable(visible_documents)
493
    document_upload_form = DocumentUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
494
    source_upload_form = KnownProtocolSourceUploadForm()
495
496
497
    time_diff = protocol.date - datetime.now().date()
    large_time_diff = not protocol.is_done() and time_diff.days > 0
    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, time_diff=time_diff, large_time_diff=large_time_diff)
Robin Sonnabend's avatar
Robin Sonnabend committed
498

Robin Sonnabend's avatar
Robin Sonnabend committed
499
500
@app.route("/protocol/delete/<int:protocol_id>")
@login_required
501
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
502
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
503
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
504
def delete_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
505
    name = protocol.get_identifier()
Robin Sonnabend's avatar
Robin Sonnabend committed
506
    protocol.delete_orphan_todos()
Robin Sonnabend's avatar
Robin Sonnabend committed
507
508
509
510
511
    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
512
@app.route("/protocol/etherpull/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
513
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
514
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
515
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
516
def etherpull_protocol(protocol):
517
518
519
    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
520
    protocol.source = get_etherpad_text(protocol.get_identifier())
Robin Sonnabend's avatar
Robin Sonnabend committed
521
522
523
524
525
    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
526
527
@app.route("/protocol/upload/known/<int:protocol_id>", methods=["POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
528
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
529
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
530
def upload_source_to_known_protocol(protocol):
531
    form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
    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()
552
    available_types = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
553
554
555
556
    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")
557
558
559
560
561
562
            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")
563
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
564
565
566
        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"))
567
        protocol = Protocol(protocoltype_id=protocoltype.id, source=source)
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        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)
589
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
590
591
592
        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"))
593
        protocol = Protocol(protocoltype_id=protocoltype.id, date=datetime.now().date(), done=True)
594
595
        db.session.add(protocol)
        db.session.commit()
596
597
598
        document = Document(protocol_id=protocol.id, name=filename,
            filename="", is_compiled=False)
        form.populate_obj(document)
599
600
601
602
603
604
605
        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
606
607
    return redirect(request.args.get("fail") or url_for("new_protocol"))

Administrator's avatar
Administrator committed
608
609
610
@app.route("/protocol/recompile/<int:protocol_id>")
@login_required
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
611
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
612
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
613
def recompile_protocol(protocol):
Administrator's avatar
Administrator committed
614
615
    tasks.parse_protocol(protocol)
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
616

Robin Sonnabend's avatar
Robin Sonnabend committed
617
618
@app.route("/protocol/source/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
619
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
620
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
621
def get_protocol_source(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
622
623
624
    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
625
626
@app.route("/protocol/template/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
627
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
628
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
629
def get_protocol_template(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
630
631
632
    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
633
634
@app.route("/protocol/etherpush/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
635
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
636
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
637
def etherpush_protocol(protocol):
638
639
640
    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))
641
642
643
    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
644

Robin Sonnabend's avatar
Robin Sonnabend committed
645
@app.route("/protocol/update/<int:protocol_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
646
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
647
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
648
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
649
def update_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
650
    upload_form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
651
    edit_form = ProtocolForm(obj=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
652
653
654
    if edit_form.validate_on_submit():
        edit_form.populate_obj(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
655
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
656
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
657
    return render_template("protocol-update.html", upload_form=upload_form, edit_form=edit_form, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
658

659
660
@app.route("/protocol/publish/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
661
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
662
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
663
def publish_protocol(protocol):
664
665
666
667
    protocol.public = True
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

668
669
@app.route("/prococol/send/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
670
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
671
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
672
def send_protocol(protocol):
673
674
675
    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))
676
677
678
679
    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))

680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
@app.route("/protocol/reminder/<int:protocol_id>")
@login_required
@db_lookup(Protocol)
@require_modify_right()
def send_protocol_reminder(protocol):
    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))
    meetingreminders = MeetingReminder.query.filter_by(protocoltype_id=protocol.protocoltype.id).all()
    if len(meetingreminders) == 0:
        flash("Für diesen Protokolltyp sind keine Einladungsmails konfiguriert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
    day_difference = (protocol.date - datetime.now().date()).days
    past_reminders = [
        meetingreminder for meetingreminder in meetingreminders
        if meetingreminder.days_before > day_difference
    ]
    if len(past_reminders) == 0:
        flash("Bisher hätte keine Einladungsmail verschickt werden sollen, schicke letzte.", "alert-info")
        past_reminders = meetingreminders
    past_reminders = sorted(past_reminders, key=lambda r: r.days_before)
    choosen_reminder = past_reminders[0]
    tasks.send_reminder(choosen_reminder, protocol)
    flash("Einladungsmail ist 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
707
708
@app.route("/protocol/tops/new/<int:protocol_id>", methods=["GET", "POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
709
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
710
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
711
def new_top(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
712
713
    form = TopForm()
    if form.validate_on_submit():
714
715
        top = TOP(protocol_id=protocol.id, planned=True)
        form.populate_obj(top)
Robin Sonnabend's avatar
Robin Sonnabend committed
716
717
        db.session.add(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
718
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
719
720
721
722
723
724
725
726
727
        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
Robin Sonnabend's avatar
Robin Sonnabend committed
728
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
729
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
730
def edit_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
731
732
733
734
    form = TopForm(obj=top)
    if form.validate_on_submit():
        form.populate_obj(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
735
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
736
737
738
739
740
        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
Robin Sonnabend's avatar
Robin Sonnabend committed
741
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
742
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
743
def delete_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
744
    name = top.name
Robin Sonnabend's avatar
Robin Sonnabend committed
745
    protocol = top.protocol
Robin Sonnabend's avatar
Robin Sonnabend committed
746
747
    db.session.delete(top)
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
748
    tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
749
    flash("Der TOP {} wurde gelöscht.".format(name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
750
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
751
752
753

@app.route("/protocol/top/move/<int:top_id>/<diff>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
754
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
755
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
756
def move_top(top, diff):
Robin Sonnabend's avatar
Robin Sonnabend committed
757
758
759
    try:
        top.number += int(diff)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
760
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
761
762
763
764
    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))

765
766
767
768
769
770
771
772
773
774
775
776
@app.route("/protocol/localtop/edit/<int:localtop_id>", methods=["GET", "POST"])
@login_required
@db_lookup(LocalTOP)
@require_modify_right()
def edit_localtop(localtop):
    form = LocalTopForm(obj=localtop)
    if form.validate_on_submit():
        form.populate_obj(localtop)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=localtop.protocol.id))
    return render_template("localtop-edit.html", form=form, localtop=localtop)

Robin Sonnabend's avatar
Robin Sonnabend committed
777
778
779
780
781
782
783
784
785
def _get_page():
    try:
        page = request.args.get("page")
        if page is None:
            return 0
        return int(page)
    except ValueError:
        return 0

Robin Sonnabend's avatar
Robin Sonnabend committed
786
787
788
789
790
791
792
793
794
def _get_page_length():
    try:
        page_length = request.args.get("page_length")
        if page_length is None:
            return config.PAGE_LENGTH
        return int(page_length)
    except ValueError:
        return config.PAGE_LENGTH

795
@app.route("/todos/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
796
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
797
798
def list_todos():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
799
800
801
    protocoltype = None
    protocoltype_id = None
    try:
802
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
803
804
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
805
    state_open = -1
Robin Sonnabend's avatar
Robin Sonnabend committed
806
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
807
        state_open = int(request.args.get("state_open"))
Robin Sonnabend's avatar
Robin Sonnabend committed
808
809
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
810
    search_term = request.args.get("search")
Robin Sonnabend's avatar
Robin Sonnabend committed
811
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
812
    search_form = TodoSearchForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
813
    if protocoltype_id is not None:
814
        search_form.protocoltype_id.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
815
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
816
817
    if state_open is not None:
        search_form.state_open.data = state_open
818
819
    if search_term is not None:
        search_form.search.data = search_term
Robin Sonnabend's avatar
Robin Sonnabend committed
820
821
822
823
    todos = [
        todo for todo in Todo.query.all()
        if todo.protocoltype.has_public_view_right(user)
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
824
    if protocoltype_id is not None and protocoltype_id != -1:
Robin Sonnabend's avatar
Robin Sonnabend committed
825
826
827
828
        todos = [
            todo for todo in todos
            if todo.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
829
830
    if state_open is not None and state_open != -1:
        todo_done = bool(state_open)
Robin Sonnabend's avatar
Robin Sonnabend committed
831
832
833
834
        todos = [
            todo for todo in todos
            if todo.is_done() == todo_done
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
835
    if search_term is not None and len(search_term.strip()) > 0:
Robin Sonnabend's avatar
Robin Sonnabend committed
836
837
838
        todos = [
            todo for todo in todos
            if search_term.lower() in todo.description.lower()
839
            or search_term.lower() in todo.who.lower()
Robin Sonnabend's avatar
Robin Sonnabend committed
840
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
841
    def _sort_key(todo):
Administrator's avatar
Administrator committed
842
        return (not todo.is_done(), todo.get_id())
Robin Sonnabend's avatar
Robin Sonnabend committed
843
    todos = sorted(todos, key=_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
844
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
845
846
    page_length = _get_page_length()
    page_count = int(math.ceil(len(todos) / page_length))
Robin Sonnabend's avatar
Robin Sonnabend committed
847
848
    if page >= page_count:
        page = 0
Robin Sonnabend's avatar
Robin Sonnabend committed
849
850
851
    begin_index = page * page_length
    end_index = (page + 1) * page_length
    max_page_length_exp = math.ceil(math.log10(len(todos)))
Robin Sonnabend's avatar
Robin Sonnabend committed
852
    todos = todos[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
853
    todos_table = TodosTable(todos)
Robin Sonnabend's avatar
Robin Sonnabend committed
854
    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, state_open=state_open, page_length=page_length, max_page_length_exp=max_page_length_exp)
Robin Sonnabend's avatar
Robin Sonnabend committed
855

Robin Sonnabend's avatar
Robin Sonnabend committed
856
857
858
859
@app.route("/todo/new", methods=["GET", "POST"])
@login_required
def new_todo():
    user = current_user()
860
    protocoltype_id = optional_int_arg("protocoltype_id")
Robin Sonnabend's avatar
Robin Sonnabend committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
    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"))
877
878
        todo = Todo()
        form.populate_obj(todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
        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
Robin Sonnabend's avatar
Robin Sonnabend committed
897
@db_lookup(Todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
898
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
899
def edit_todo(todo):
Robin Sonnabend's avatar
Robin Sonnabend committed
900
901
902
903
    form = TodoForm(obj=todo)
    if form.validate_on_submit():
        form.populate_obj(todo)
        db.session.commit()
904
        return redirect(request.args.get("next") or url_for("list_todos", protocoltype_id=todo.protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
905
906
907
908
    return render_template("todo-edit.html", form=form, todo=todo)

@app.route("/todo/show/<int:todo_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
909
@db_lookup(Todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
910
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
911
def show_todo(todo):
Robin Sonnabend's avatar
Robin Sonnabend committed
912
913
914
915
916
    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
Robin Sonnabend's avatar
Robin Sonnabend committed
917
@db_lookup(Todo)