server.py 49.2 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
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
from decorators import db_lookup, require_public_view_right, require_private_view_right, require_modify_right, require_admin_right
Robin Sonnabend's avatar
Robin Sonnabend committed
26
from models.database import ProtocolType, Protocol, DefaultTOP, TOP, Document, Todo, Decision, MeetingReminder, Error, TodoMail, DecisionDocument, TodoState, Meta, DefaultMeta
27
from views.forms import LoginForm, ProtocolTypeForm, DefaultTopForm, MeetingReminderForm, NewProtocolForm, DocumentUploadForm, KnownProtocolSourceUploadForm, NewProtocolSourceUploadForm, ProtocolForm, TopForm, SearchForm, NewProtocolFileUploadForm, NewTodoForm, TodoForm, TodoMailForm, DefaultMetaForm, MetaForm, MergeTodosForm
Robin Sonnabend's avatar
Robin Sonnabend committed
28
from views.tables import ProtocolsTable, ProtocolTypesTable, ProtocolTypeTable, DefaultTOPsTable, MeetingRemindersTable, ErrorsTable, TodosTable, DocumentsTable, DecisionsTable, TodoTable, ErrorTable, TodoMailsTable, DefaultMetasTable
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
Robin Sonnabend's avatar
Robin Sonnabend committed
54
app.jinja_env.filters["datify_short"] = date_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
55
app.jinja_env.filters["datify_long"] = date_filter_long
56
app.jinja_env.filters["url_complete"] = url_manager.complete
57
app.jinja_env.filters["class"] = class_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
58
59
app.jinja_env.filters["todo_get_name"] = todostate_name_filter
app.jinja_env.filters["code"] = code_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
60
app.jinja_env.filters["indent_tab"] = indent_tab_filter
61
app.jinja_env.tests["auth_valid"] = security_manager.check_user
Robin Sonnabend's avatar
Robin Sonnabend committed
62
app.jinja_env.tests["needs_date"] = needs_date_test
63
64
65

import tasks

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

73
74
# blueprints here

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

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@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():
117
    app.run()
118
119
    make_scheduler()

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

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

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

Robin Sonnabend's avatar
Robin Sonnabend committed
188
@app.route("/types/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
189
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
190
191
192
193
194
195
196
197
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)]
198
    types = sorted(types, key=lambda t: t.short_name)
Robin Sonnabend's avatar
Robin Sonnabend committed
199
200
201
202
203
204
205
206
207
208
209
210
    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:
211
212
            protocoltype = ProtocolType()
            form.populate_obj(protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
213
214
215
216
217
218
            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
219
@app.route("/type/edit/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
220
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
221
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
222
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
223
def edit_type(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
224
225
226
227
228
229
230
231
    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
232
            return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
233
234
    return render_template("type-edit.html", form=form, protocoltype=protocoltype)

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

Robin Sonnabend's avatar
Robin Sonnabend committed
246
@app.route("/type/delete/<int:protocoltype_id>")
247
@login_required
248
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
249
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
250
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
251
def delete_type(protocoltype):
252
253
254
255
256
257
    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
258
@app.route("/type/reminders/new/<int:protocoltype_id>", methods=["GET", "POST"])
259
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
260
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
261
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
262
def new_reminder(protocoltype):
263
264
    form = MeetingReminderForm()
    if form.validate_on_submit():
265
266
        meetingreminder = MeetingReminder(protocoltype_id=protocoltype.id)
        form.populate_obj(meetingreminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
267
        db.session.add(meetingreminder)
268
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
269
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
270
271
    return render_template("reminder-new.html", form=form, protocoltype=protocoltype)

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

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

Robin Sonnabend's avatar
Robin Sonnabend committed
294
@app.route("/type/tops/new/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
295
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
296
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
297
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
298
def new_default_top(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
299
300
    form = DefaultTopForm()
    if form.validate_on_submit():
301
302
        defaulttop = DefaultTOP(protocoltype_id=protocoltype.id)
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
303
        db.session.add(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
304
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
305
        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
306
307
308
        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
309
@app.route("/type/tops/edit/<int:protocoltype_id>/<int:defaulttop_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
310
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
311
@db_lookup(ProtocolType, DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
312
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
313
314
def edit_default_top(protocoltype, defaulttop):
    form = DefaultTopForm(obj=defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
315
    if form.validate_on_submit():
Robin Sonnabend's avatar
Robin Sonnabend committed
316
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
317
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
318
319
        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
320

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

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

@app.route("/protocols/list")
343
344
345
def list_protocols():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
346
347
348
    protocoltype = None
    protocoltype_id = None
    try:
349
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
350
351
352
353
354
355
356
357
358
359
360
    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
361
362
363
364
365
366
367
368
369
    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))
            ))
370
    protocols = [
Robin Sonnabend's avatar
Robin Sonnabend committed
371
        protocol for protocol in protocol_query.all()
372
        if protocol.protocoltype.has_public_view_right(user, check_networks=False)
373
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
374
375
376
377
378
379
380
381
382
383
384
385
386
    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
387
388
389
390
391
    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
392
393
394
395
396
    if shall_search:
        protocols = [
            protocol for protocol in protocols
            if (protocol.protocoltype.has_private_view_right(user)
                and _matches_search(protocol.content_private))
397
            or (protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
                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
                ]))
425
            search_results[protocol] = " …<br />\n".join(formatted_lines)
Robin Sonnabend's avatar
Robin Sonnabend committed
426
    protocols = sorted(protocols, key=lambda protocol: protocol.date, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
427
    page = _get_page()
428
    page_count = int(math.ceil(len(protocols) / config.PAGE_LENGTH))
Robin Sonnabend's avatar
Robin Sonnabend committed
429
430
431
432
433
    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
434
    protocols_table = ProtocolsTable(protocols, search_results=search_results)
Robin Sonnabend's avatar
Robin Sonnabend committed
435
    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
436
437
438
439
440

@app.route("/protocol/new", methods=["GET", "POST"])
@login_required
def new_protocol():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
441
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
442
    form = NewProtocolForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
443
    upload_form = NewProtocolSourceUploadForm(protocoltypes)
444
    file_upload_form = NewProtocolFileUploadForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
445
    if form.validate_on_submit():
446
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
447
448
449
        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"))
450
451
        protocol = Protocol(protocoltype_id=protocoltype.id)
        form.populate_obj(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
452
453
        db.session.add(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
454
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
455
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
456
    type_id = request.args.get("protocoltype_id")
Robin Sonnabend's avatar
Robin Sonnabend committed
457
458
    if type_id is not None:
        form.protocoltype.data = type_id
459
460
        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
461
462

@app.route("/protocol/show/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
463
464
@db_lookup(Protocol)
def show_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
465
466
    user = current_user()
    errors_table = ErrorsTable(protocol.errors)
467
    if not protocol.protocoltype.has_public_view_right(user, check_networks=False): # yes, feature
Robin Sonnabend's avatar
Robin Sonnabend committed
468
469
        flash("Die fehlen die nötigen Zugriffsrechte.", "alert-error")
        return redirect(request.args.get("next") or url_for("login"))
Robin Sonnabend's avatar
Robin Sonnabend committed
470
471
    visible_documents = [
        document for document in protocol.documents
472
        if (not document.is_private and document.protocol.has_public_view_right(user))
Robin Sonnabend's avatar
Robin Sonnabend committed
473
474
475
        or (document.is_private and document.protocol.protocoltype.has_private_view_right(user))
    ]
    documents_table = DocumentsTable(visible_documents)
476
    document_upload_form = DocumentUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
477
478
    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
479

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

Administrator's avatar
Administrator committed
589
590
591
@app.route("/protocol/recompile/<int:protocol_id>")
@login_required
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
592
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
593
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
594
def recompile_protocol(protocol):
Administrator's avatar
Administrator committed
595
596
    tasks.parse_protocol(protocol)
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
597

Robin Sonnabend's avatar
Robin Sonnabend committed
598
599
@app.route("/protocol/source/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
600
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
601
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
602
def get_protocol_source(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
603
604
605
    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
606
607
@app.route("/protocol/template/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
608
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
609
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
610
def get_protocol_template(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
611
612
613
    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
614
615
@app.route("/protocol/etherpush/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
616
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
617
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
618
def etherpush_protocol(protocol):
619
620
621
    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))
622
623
624
    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
625

Robin Sonnabend's avatar
Robin Sonnabend committed
626
@app.route("/protocol/update/<int:protocol_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
627
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
628
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
629
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
630
def update_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
631
    upload_form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
632
    edit_form = ProtocolForm(obj=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
633
634
635
    if edit_form.validate_on_submit():
        edit_form.populate_obj(protocol)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
636
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
637
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
638
    return render_template("protocol-update.html", upload_form=upload_form, edit_form=edit_form, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
639

640
641
@app.route("/protocol/publish/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
642
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
643
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
644
def publish_protocol(protocol):
645
646
647
648
    protocol.public = True
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

649
650
@app.route("/prococol/send/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
651
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
652
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
653
def send_protocol(protocol):
654
655
656
    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))
657
658
659
660
    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
661
662
@app.route("/protocol/tops/new/<int:protocol_id>", methods=["GET", "POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
663
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
664
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
665
def new_top(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
666
667
    form = TopForm()
    if form.validate_on_submit():
668
669
        top = TOP(protocol_id=protocol.id, planned=True)
        form.populate_obj(top)
Robin Sonnabend's avatar
Robin Sonnabend committed
670
671
        db.session.add(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
672
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
673
674
675
676
677
678
679
680
681
        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
682
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
683
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
684
def edit_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
685
686
687
688
    form = TopForm(obj=top)
    if form.validate_on_submit():
        form.populate_obj(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
689
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
690
691
692
693
694
        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
695
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
696
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
697
def delete_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
698
    name = top.name
Robin Sonnabend's avatar
Robin Sonnabend committed
699
    protocol = top.protocol
Robin Sonnabend's avatar
Robin Sonnabend committed
700
701
    db.session.delete(top)
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
702
    tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
703
    flash("Der TOP {} wurde gelöscht.".format(name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
704
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
705
706
707

@app.route("/protocol/top/move/<int:top_id>/<diff>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
708
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
709
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
710
def move_top(top, diff):
Robin Sonnabend's avatar
Robin Sonnabend committed
711
712
713
    try:
        top.number += int(diff)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
714
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
715
716
717
718
    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
719
720
721
722
723
724
725
726
727
def _get_page():
    try:
        page = request.args.get("page")
        if page is None:
            return 0
        return int(page)
    except ValueError:
        return 0

728
@app.route("/todos/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
729
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
730
731
def list_todos():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
732
733
734
    protocoltype = None
    protocoltype_id = None
    try:
735
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
736
737
738
    except (ValueError, TypeError):
        pass
    search_term = request.args.get("search")
Robin Sonnabend's avatar
Robin Sonnabend committed
739
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
740
741
    search_form = SearchForm(protocoltypes)
    if protocoltype_id is not None:
742
        search_form.protocoltype.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
743
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
744
745
    if search_term is not None:
        search_form.search.data = search_term
Robin Sonnabend's avatar
Robin Sonnabend committed
746
747
748
749
    todos = [
        todo for todo in Todo.query.all()
        if todo.protocoltype.has_public_view_right(user)
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
750
    if protocoltype_id is not None and protocoltype_id != -1:
Robin Sonnabend's avatar
Robin Sonnabend committed
751
752
753
754
        todos = [
            todo for todo in todos
            if todo.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
755
    if search_term is not None and len(search_term.strip()) > 0:
Robin Sonnabend's avatar
Robin Sonnabend committed
756
757
758
        todos = [
            todo for todo in todos
            if search_term.lower() in todo.description.lower()
759
            or search_term.lower() in todo.who.lower()
Robin Sonnabend's avatar
Robin Sonnabend committed
760
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
761
    def _sort_key(todo):
Administrator's avatar
Administrator committed
762
        return (not todo.is_done(), todo.get_id())
Robin Sonnabend's avatar
Robin Sonnabend committed
763
    todos = sorted(todos, key=_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
764
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
765
    page_count = int(math.ceil(len(todos) / config.PAGE_LENGTH))
Robin Sonnabend's avatar
Robin Sonnabend committed
766
767
768
769
    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
770
    todos = todos[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
771
    todos_table = TodosTable(todos)
Robin Sonnabend's avatar
Robin Sonnabend committed
772
    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
773

Robin Sonnabend's avatar
Robin Sonnabend committed
774
775
776
777
@app.route("/todo/new", methods=["GET", "POST"])
@login_required
def new_todo():
    user = current_user()
778
    protocoltype_id = optional_int_arg("protocoltype_id")
Robin Sonnabend's avatar
Robin Sonnabend committed
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    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"))
795
796
        todo = Todo()
        form.populate_obj(todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
        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
815
@db_lookup(Todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
816
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
817
def edit_todo(todo):
Robin Sonnabend's avatar
Robin Sonnabend committed
818
819
820
821
    form = TodoForm(obj=todo)
    if form.validate_on_submit():
        form.populate_obj(todo)
        db.session.commit()
822
        return redirect(request.args.get("next") or url_for("list_todos", protocoltype_id=todo.protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
823
824
825
826
    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
827
@db_lookup(Todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
828
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
829
def show_todo(todo):
Robin Sonnabend's avatar
Robin Sonnabend committed
830
831
832
833
834
    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
835
@db_lookup(Todo)
Robin Sonnabend's avatar
Robin Sonnabend committed
836
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
837
def delete_todo(todo):
Robin Sonnabend's avatar
Robin Sonnabend committed
838
839
840
841
    type_id = todo.protocoltype.id
    db.session.delete(todo)
    db.session.commit()
    flash("Todo gelöscht.", "alert-success")
842
    return redirect(request.args.get("next") or url_for("list_todos", protocoltype_id=type_id))
Robin Sonnabend's avatar
Robin Sonnabend committed
843

844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
@app.route("/todo/merge", methods=["GET", "POST"])
@login_required
@group_required(config.ADMIN_GROUP)
def merge_todos():
    form = MergeTodosForm(request.args.get("todo_id"))
    if form.validate_on_submit():
        todo1 = Todo.query.filter_by(id=form.todo1.data).first()
        todo2 = Todo.query.filter_by(id=todo.todo2.data).first()
        if todo1 is None or todo2 is None:
            flash("Missing todos.", "alert-error")
        else:
            id1 = todo1.id
            id2 = todo2.id
            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()
            flash("Merged todos {} and {}.".format(id1, id2), "alert-success")
864
            return redirect(request.args.get("next") or url_for("list_todos"))
865
866
    return render_template("todos-merge.html", form=form, next_url=request.args.get("next"))

Robin Sonnabend's avatar
Robin Sonnabend committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
@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()
887
        if decision.protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
888
889
890
891
892
893
894
895
896
897
898
    ]
    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
899
900
    decisions = sorted(decisions, key=lambda d: d.protocol.date, reverse=True)
        
Robin Sonnabend's avatar
Robin Sonnabend committed
901
902
903
904
905
906
907
908
909
910
    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)

911
@app.route("/document/download/<int:document_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
912
913
@db_lookup(Document)
def download_document(document):
914
915
916
917
    user = current_user()
    if ((document.is_private
            and not document.protocol.protocoltype.has_private_view_right(user))
        or (not document.is_private
918
            and not document.protocol.has_public_view_right(user))):
Robin Sonnabend's avatar
Robin Sonnabend committed
919
        flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
920
        return redirect(request.args.get("next") or url_for("index"))
921
    return send_file(document.as_file_like(), cache_timeout=1, as_attachment=True, attachment_filename=document.name)
922
923
924

@app.route("/document/upload/<int:protocol_id>", methods=["POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
925
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
926
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
927
def upload_document(protocol):
928
929
    form = DocumentUploadForm()
    if form.document.data is None:
Robin Sonnabend's avatar
Robin Sonnabend committed
930
        flash("Es wurde keine Datei ausgewählt.", "alert-error")
931
932
933
        return redirect(request.args.get("next") or url_for("index"))
    file = form.document.data
    if file.