edit.py 10.4 KB
Newer Older
Andreas Valder's avatar
Andreas Valder committed
1
2
from server import *

Andreas Valder's avatar
Andreas Valder committed
3
4
5
6
7
8
9
10
11
12
13
14
# field types:
# 	boolean
# 	shortstring
# 	text
# 	datetime
# 	duration
# 	videotime
editable_tables = {
	'courses': {
		'table': 'courses_data',
		'idcolumn': 'id',
		'editable_fields': {
Andreas Valder's avatar
Andreas Valder committed
15
			'visible':	{'type': 'boolean', 'description': 'Wenn ein Kurs nicht sichtbar ist sind alle Videos davon nicht abrufbar.'},
16
			'listed':	{'type': 'boolean', 'description': 'Soll die Veranstaltung auf der Hauptseite gelistet werden?'},
Andreas Valder's avatar
Andreas Valder committed
17
			'title':	{'type': 'shortstring'},
18
			'short':	{'type': 'shortstring', 'description': 'Abkürzung für die Veranstaltung, z.B. für den Drehplan'},
Andreas Valder's avatar
Andreas Valder committed
19
20
21
22
			'handle':	{'type': 'shortstring'},
			'organizer':	{'type': 'shortstring'},
			'subject':	{'type': 'shortstring'},
			'semester':	{'type': 'shortstring'},
23
			'downloadable':	{'type': 'boolean', 'description': 'Hiermit kann der Download-Button disabled werden'},
Andreas Valder's avatar
Andreas Valder committed
24
25
26
			'internal':	{'type': 'text'},
			'responsible':	{'type': 'shortstring'},
			'deleted':	{'type': 'boolean'},
27
			'description':	{'type': 'text'},
28
			'external':	{'type': 'boolean', 'description': 'Soll die Veranstaltung nicht im Drehplan angezeigt werden?'},
29
30
31
			'coursechapters':	{'type': 'boolean', 'description': 'Sollen auf der Kursseite die Kapitelmarker der Videos angezeigt werden?'},
			'autopublish':	{'type': 'boolean', 'description': 'Sollen encodete Videos automatisch verschoben werden?'},
			'autovisible':	{'type': 'boolean', 'description': 'Sollen neue Videos automatisch sichtbar sein?'}},
Andreas Valder's avatar
Andreas Valder committed
32
33
34
35
36
		'creationtime_fields': ['created_by', 'time_created', 'time_updated'] },
	'lectures': {
		'table': 'lectures_data',
		'idcolumn': 'id',
		'editable_fields': {
Andreas Valder's avatar
Andreas Valder committed
37
			'visible':	{'type': 'boolean', 'description': 'Wenn eine lecture nicht sichtbar ist sind alle Videos davon nicht abrufbar'},
Andreas Valder's avatar
Andreas Valder committed
38
39
40
41
42
43
44
45
			'title':	{'type': 'shortstring'},
			'comment':	{'type': 'text'},
			'internal':	{'type': 'text'},
			'speaker':	{'type': 'shortstring'},
			'place':	{'type': 'shortstring'},
			'time':		{'type': 'datetime'},
			'duration':	{'type': 'duration'},
			'jumplist':	{'type': ''},
46
			'deleted':	{'type': 'boolean'},
Andreas Valder's avatar
Andreas Valder committed
47
48
			'live':		{'type': 'boolean', 'description': 'Ist ein Livestream geplant? Muss gesetzt sein damit der RTMP Stream zugeordnet wird.'},
			'norecording': {'type': 'boolean', 'description:': 'Führt dazu, dass der Termin ausgegraut wird.'}},
Andreas Valder's avatar
Andreas Valder committed
49
50
51
52
53
		'creationtime_fields': ['course_id', 'time_created', 'time_updated'] },
	'videos': {
		'table': 'videos_data',
		'idcolumn': 'id',
		'editable_fields': {
Andreas Valder's avatar
Andreas Valder committed
54
			'visible':	{'type': 'boolean', 'description': 'Ein nicht sichtbares Video kann nicht abgerufen werden.'},
Andreas Valder's avatar
Andreas Valder committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
			'deleted':	{'type': 'boolean'}},
		'creationtime_fields': ['created_by', 'time_created', 'time_updated'] },
	'chapters': {
		'table': 'chapters',
		'idcolumn': 'id',
		'editable_fields': {
			'time':		{'type': 'videotime'},
			'text':		{'type': 'shortstring'},
			'visible':	{'type': 'boolean'},
			'deleted':	{'type': 'boolean'}},
		'creationtime_fields': ['created_by', 'time_created', 'time_updated'] },
	'announcements': {
		'table': 'announcements',
		'idcolumn': 'id',
		'editable_fields': {
			'text':		{'type': 'text'},
			'level':	{'type': 'integer'},
			'visible':	{'type': 'boolean'},
			'deleted':	{'type': 'boolean'},
			'time_publish':	{'type': 'datetime'},
			'time_expire':	{'type': 'datetime'}},
		'creationtime_fields': ['created_by', 'time_created', 'time_updated'] },
	'featured': {
		'table': 'featured',
		'idcolumn': 'id',
		'editable_fields':	{
			'title':	{'type': 'shortstring'},
			'text':		{'type': 'text'},
			'internal':	{'type': 'text'},
			'visible':	{'type': 'boolean'},
			'deleted':	{'type': 'boolean'},
			'param':	{'type': 'shortstring'},
			'param2':	{'type': 'shortstring'},
			'order':	{'type': 'integer' }},
		'creationtime_fields': ['created_by', 'time_created', 'time_updated', 'type'] },
	'perm': {
		'table': 'perm',
		'idcolumn': 'id',
		'editable_fields': {
			'type':		{'type': 'shortstring'},
			'param1':	{'type': 'shortstring'},
			'param2':	{'type': 'shortstring'},
			'deleted':	{'type': 'boolean'}},
		'creationtime_fields': ['course_id', 'lecture_id', 'video_id', 'created_by', 'time_created', 'time_updated'] },
	'sorterrorlog': {
		'table': 'sorterrorlog_data',
		'idcolumn': 'id',
		'editable_fields': {
			'deleted':	{'type': 'boolean'}},
Julian Rother's avatar
Julian Rother committed
104
105
106
107
108
109
110
111
112
113
114
		'creationtime_fields': ['time_created', 'time_updated'] },
	'users': {
		'table': 'users',
		'idcolumn': 'id',
		'editable_fields': {
			'mail_notifications': {'type': 'boolean'},
			'notify_chapter_submitted': {'type': 'boolean'},
			'notify_new_video': {'type': 'boolean'},
			'notify_edit': {'type': 'boolean'}
		},
		'creationtime_fields': [] }
Andreas Valder's avatar
Andreas Valder committed
115
116
117
118
119
120
121
122
123
124
	}

#parses the path to a dict, containing the table, id, field and field type
@app.template_filter(name='parseeditpath')
def parseeditpath(path):
	table, id, column = path.split('.', 2)
	assert table in editable_tables
	assert column in editable_tables[table]['editable_fields']
	type = editable_tables[table]['editable_fields'][column]['type']
	return {'table': table, 'id': id, 'column': column, 'type': type, 'tableinfo': editable_tables[table]}
Andreas Valder's avatar
Andreas Valder committed
125

126
127
128
129
130
131
132
@app.template_filter(name='getfielddescription')
def getfielddescription(path):
	p = parseeditpath(path)
	desc = p['tableinfo']['editable_fields'][p['column']].get('description', '')
	if desc != '':
		desc = '<br>'+desc
	return desc
Andreas Valder's avatar
Andreas Valder committed
133

134
135
136
137
138
139
140
141
@app.template_filter(name='getfieldchangelog')
def getfieldchangelog(path):
	p = parseeditpath(path)
	changelog = query('SELECT * FROM changelog LEFT JOIN users ON (changelog.who = users.id) WHERE `table` = ? AND `id_value` = ? and `field` = ? ORDER BY `when` DESC LIMIT 5', p['table'], p['id'], p['column'])
	for entry in changelog:
		entry['path'] = '.'.join([entry['table'], entry['id_value'], entry['field']])
	return changelog

Andreas Valder's avatar
Andreas Valder committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
@app.route('/internal/edit', methods=['GET', 'POST'])
@mod_required
@csrf_protect
def edit(prefix='', ignore=[]):
	# All editable tables are expected to have a 'time_updated' field
	ignore.append('ref')
	ignore.append('prefix')
	ignore.append('_csrf_token')
	if not prefix and 'prefix' in request.args:
		prefix = request.args['prefix']
	changes = request.values.items()
	if (request.method == 'POST') and (request.get_json()):
		changes = request.get_json().items()
	for key, val in changes:
		if key in ignore:
			continue
		key = prefix+key
Andreas Valder's avatar
Andreas Valder committed
159
160
161
162
163
		path = parseeditpath(key)
		modify('INSERT INTO changelog (`table`,id_value, id_key, field, value_new, value_old, `when`, who, executed) \
			VALUES (?,?,?,?,?,(SELECT `%s` FROM %s WHERE %s = ?),?,?,1)'%(path['column'], path['tableinfo']['table'], path['tableinfo']['idcolumn']),
				path['table'], path['id'], path['tableinfo']['idcolumn'], path['column'], val, path['id'], datetime.now(), session['user']['dbid'])
		modify('UPDATE %s SET `%s` = ?, time_updated = ? WHERE `%s` = ?'%(path['tableinfo']['table'], path['column'], path['tableinfo']['idcolumn']), val, datetime.now(),path['id'])
164
		for func in edit_handlers.get(path['table'], {}).get(None, []):
165
			func(path['table'], path['column'], val, path['id'], session['user']['dbid'])
166
		for func in edit_handlers.get(path['table'], {}).get(path['column'], []):
167
			func(path['table'], path['column'], val, path['id'], session['user']['dbid'])
Andreas Valder's avatar
Andreas Valder committed
168
169
170
171
172
173
174
175
	if 'ref' in request.values:
		return redirect(request.values['ref'])
	return "OK", 200

@app.route('/internal/new/<table>', methods=['GET', 'POST'])
@mod_required
@csrf_protect
def create(table):
Andreas Valder's avatar
Andreas Valder committed
176
	assert table in editable_tables
Andreas Valder's avatar
Andreas Valder committed
177
178
179
180
	defaults = {'created_by': session['user']['dbid'], 'time_created': datetime.now(), 'time_updated': datetime.now()}
	columns = []
	values = []
	for column, val in defaults.items():
Andreas Valder's avatar
Andreas Valder committed
181
		if column in editable_tables[table]['creationtime_fields']:
Andreas Valder's avatar
Andreas Valder committed
182
183
184
185
186
187
188
189
			columns.append(column)
			values.append(val)
	args = request.values.items()
	if (request.method == 'POST') and (request.get_json()):
		args = request.get_json().items()
	for column, val in args:
		if (column == 'ref') or (column == '_csrf_token'):
			continue
Andreas Valder's avatar
Andreas Valder committed
190
		assert column in list(editable_tables[table]['editable_fields'].keys())+editable_tables[table]['creationtime_fields']
Andreas Valder's avatar
Andreas Valder committed
191
192
193
		assert column not in defaults
		columns.append('`'+column+'`')
		values.append(val)
Andreas Valder's avatar
Andreas Valder committed
194
	id = modify('INSERT INTO %s (%s) VALUES (%s)'%(editable_tables[table]['table'],
Andreas Valder's avatar
Andreas Valder committed
195
				','.join(columns), ','.join(['?']*len(values))), *values)
196
197
	if table == 'courses':
		set_responsible(id, session['user']['dbid'], 1)
Andreas Valder's avatar
Andreas Valder committed
198
199
200
	if 'ref' in request.values:
		return redirect(request.values['ref'])
	return str(id), 200
201
202

@app.route('/internal/changelog')
203
@register_navbar('Changelog', icon='book', group='weitere')
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@mod_required
def changelog():
	if 'page' in request.args:
		page = max(0, int(request.args['page']))
	else:
		page = 0
	if 'pagesize' in request.args:
		pagesize = min(500, int(request.args['pagesize']))
	else:
		pagesize = 50
	changelog = query('SELECT * FROM changelog LEFT JOIN users ON (changelog.who = users.id) ORDER BY `when` DESC LIMIT ? OFFSET ?', pagesize, page*pagesize)
	pagecount = math.ceil(query('SELECT count(id) as count FROM changelog')[0]['count']/pagesize)
	for entry in changelog:
		entry['path'] = '.'.join([entry['table'], entry['id_value'], entry['field']])
	return render_template('changelog.html', changelog=changelog, page=page, pagesize=pagesize, pagecount=pagecount)
219
220
221
222
223
224
225
226
227
228
229
230

@app.route('/internal/set/responsible/<int:course_id>/<int:user_id>', defaults={'value': True}, methods=['GET', 'POST'])
@app.route('/internal/unset/responsible/<int:course_id>/<int:user_id>', defaults={'value': False}, methods=['GET', 'POST'])
@mod_required
@csrf_protect
def set_responsible(course_id, user_id, value):
	if value:
		modify('REPLACE INTO responsible (course_id, user_id) values (?, ?)', course_id, user_id);
	else:
		modify('DELETE FROM responsible WHERE course_id = ? AND user_id = ?', course_id, user_id);
	return "OK", 200
	
231
232
233
234
235
236
237
238
239
240
241
242
edit_handlers = {}
def edit_handler(*tables, field=None):
	def wrapper(func):
		for table in tables:
			if table not in edit_handlers:
				edit_handlers[table] = {}
			if field not in edit_handlers[table]:
				edit_handlers[table][field] = []
			edit_handlers[table][field].append(func)
		return func
	return wrapper

243
244
245
246
247
248
249
250
251
252
253
254
@edit_handler('courses')
@edit_handler('lectures')
def notify_edit(table, column, value, id, user_id):
	lecture = None
	if table == 'lectures':
		lecture = query('SELECT * FROM lectures_data WHERE id = ?', id)[0]
		course_id = lecture['course_id']
	elif table == 'courses':
		course_id = id
	course = query('SELECT * FROM courses_data WHERE id = ?', course_id)[0]
	user = query('SELECT * FROM users WHERE id = ?', user_id)[0]
	notify_mods('edit', course_id, exclude_uids=[user_id], course=course, lecture=lecture, table=table, column=column, value=value, user=user)