server.py 7.22 KB
Newer Older
1

2
from flask import *
3
from functools import wraps
4
import sqlite3
5
import os
Julian Rother's avatar
Julian Rother committed
6
import re
7

8
app = Flask(__name__)
9
config = app.config
10
11
config['DB_SCHEMA'] = 'db_schema.sql'
config['DB_DATA'] = 'db_example.sql'
12
13
14
config['DB_ENGINE'] = 'sqlite'
config['SQLITE_DB'] = 'db.sqlite'
config['SQLITE_INIT_SCHEMA'] = True
15
config['SQLITE_INIT_DATA'] = False
16
17
18
19
20
config['DEBUG'] = False
if __name__ == '__main__':
	config['SQLITE_INIT_DATA'] = True
	config['DEBUG'] = True
config.from_pyfile('config.py', silent=True)
21

22
23
24
25
26
27
28
29
30
31
32
if config['DB_ENGINE'] == 'sqlite':
	created = not os.path.exists(config['SQLITE_DB'])
	db = sqlite3.connect(config['SQLITE_DB'])
	cur = db.cursor()
	if config['SQLITE_INIT_SCHEMA']:
		cur.executescript(open(config['DB_SCHEMA']).read())
	if config['SQLITE_INIT_DATA'] and created:
		cur.executescript(open(config['DB_DATA']).read())
	db.commit()
	db.close()

33
34
35
36
37
# Row wrapper for sqlite
def dict_factory(cursor, row):
	d = {}
	for idx, col in enumerate(cursor.description):
		if type(row[idx]) == str:
38
			d[col[0].split('.')[-1]] = row[idx].replace('\\n','\n').replace('\\r','\r')
39
40
41
42
		else:
			d[col[0].split('.')[-1]] = row[idx]
	return d

43
def query(operation, *params):
44
	if config['DB_ENGINE'] == 'mysql':
45
		import mysql.connector
46
		if 'db' not in g or not g.db.is_connected():
47
			g.db = mysql.connector.connect(user=config['MYSQL_USER'], password=config['MYSQL_PASSWD'], host=config['MYSQL_HOST'], database=config['MYSQL_DB'])
Julian Rother's avatar
Julian Rother committed
48
49
50
		if not hasattr(request, 'db'):
			request.db = g.db.cursor(dictionary=True)
		request.db.execute(operation.replace('?', '%s'), params)
51
	elif config['DB_ENGINE'] == 'sqlite':
Julian Rother's avatar
Julian Rother committed
52
		if 'db' not in g:
53
			g.db = sqlite3.connect(config['SQLITE_DB'])
54
			g.db.row_factory = dict_factory
Julian Rother's avatar
Julian Rother committed
55
56
57
58
59
60
		if not hasattr(request, 'db'):
			request.db = g.db.cursor()
		request.db.execute(operation, params)
	else:
		return []
	return request.db.fetchall()
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def searchquery(text, columns, match, tables, suffix, *suffixparams):
	params = []
	subexprs = []
	words = text.split(' ')
	prio = len(words)+1
	for word in words:
		if word == '' or word.isspace():
			continue
		matchexpr = ' OR '.join(['%s LIKE ?'%column for column in match])
		subexprs.append('SELECT %s, %s AS _prio FROM %s WHERE %s'%(columns, str(prio), tables, matchexpr))
		params += ['%'+word+'%']*len(match)
		prio -= 1
	if subexprs == []:
		return []
	expr = 'SELECT *,SUM(_prio) AS _score FROM (%s) AS _tmp %s'%(' UNION '.join(subexprs), suffix)
	return query(expr, *params, *suffixparams)

Julian Rother's avatar
Julian Rother committed
79
LDAP_USERRE = re.compile(r'[^a-z0-9]')
Julian Rother's avatar
Julian Rother committed
80
81
82
83
84
notldap = {
	'videoag':('videoag', ['users','videoag'], {'uid': 'videoag', 'givenName': 'Video', 'sn': 'Geier'}),
	'gustav':('passwort', ['users'], {'uid': 'gustav', 'givenName': 'Gustav', 'sn': 'Geier'})
}

Julian Rother's avatar
Julian Rother committed
85
86
87
def ldapauth(user, password):
	user = LDAP_USERRE.sub(r'', user.lower())
	if 'LDAP_HOST' in config:
88
		import ldap3
Julian Rother's avatar
Julian Rother committed
89
90
91
92
93
94
95
96
97
98
99
100
		try:
			conn = ldap3.Connection(config['LDAP_HOST'], 'uid=%s,ou=users,dc=fsmpi,dc=rwth-aachen,dc=de'%user, password, auto_bind=True)
			if conn.search("ou=groups,dc=fsmpi,dc=rwth-aachen,dc=de", "(&(cn=*)(memberUid=%s))"%user, attributes=['cn']):
				groups = [e.cn.value for e in conn.entries]
			conn.unbind()
			return user, groups
		except ldap3.core.exceptions.LDAPBindError:
			pass
	elif config.get('DEBUG') and user in notldap and password == notldap[user][0]:
		return user, notldap[user][1]
	return None, []

Julian Rother's avatar
Julian Rother committed
101
102
103
def ldapget(user):
	user = LDAP_USERRE.sub(r'', user.lower())
	if 'LDAP_HOST' in config:
104
		import ldap3
Julian Rother's avatar
Julian Rother committed
105
106
107
108
109
110
		conn = ldap3.Connection('ldaps://rumo.fsmpi.rwth-aachen.de', auto_bind=True)
		conn.search("ou=users,dc=fsmpi,dc=rwth-aachen,dc=de", "(uid=%s)"%user,
				attributes=ldap3.ALL_ATTRIBUTES)
		e = conn.entries[0]
		return {'uid': user, 'givenName': e.givenName.value, 'sn':e.sn.value}
	else:
Julian Rother's avatar
Julian Rother committed
111
		return notldap[user][2]
Julian Rother's avatar
Julian Rother committed
112

113
114
115
116
117
118
119
120
121
122
def login_required(func):
	@wraps(func)
	def decorator(*args, **kwargs):
		if not 'user' in session:
			flash('Diese Funktion ist nur für Moderatoren verfügbar!')
			return redirect(url_for('login', ref=request.url))
		else:
			return func(*args, **kwargs)
	return decorator

123
124
@app.route('/')
def index():
125
	return render_template('index.html', latestvideos=query('''
126
				SELECT lectures.*, max(videos.time_updated) AS lastvidtime, courses.short, courses.downloadable, courses.title AS coursetitle
127
128
129
				FROM lectures
				LEFT JOIN videos ON (videos.lecture_id = lectures.id)
				LEFT JOIN courses on (courses.id = lectures.course_id)
130
				WHERE (? OR (courses.visible AND courses.listed AND lectures.visible AND videos.visible))
131
132
				GROUP BY videos.lecture_id
				ORDER BY lastvidtime DESC
Andreas Valder's avatar
.    
Andreas Valder committed
133
				LIMIT 6
134
			''', False))
135

Andreas Valder's avatar
Andreas Valder committed
136
137
@app.route('/videos')
def videos():
138
139
140
141
	c=query("SELECT * FROM courses")
	for i in c:
		if i['semester'] == '':
			i['semester'] = 'zeitlos'
Andreas Valder's avatar
Andreas Valder committed
142
143
144
145
	groupedby = request.args.get('groupedby')
	if groupedby not in ['title','semester','organizer']:
		groupedby = 'semester'
	return render_template('videos.html', courses=c, groupedby=groupedby)
Andreas Valder's avatar
Andreas Valder committed
146
147
148

@app.route('/faq')
def faq():
149
	return render_template('faq.html')
Andreas Valder's avatar
Andreas Valder committed
150

Andreas Valder's avatar
Andreas Valder committed
151
152
@app.route('/play')
def play():
Julian Rother's avatar
Julian Rother committed
153
154
155
156
157
158
	if 'lectureid' in request.args:
		id = request.args['lectureid']
		return render_template('play.html',
				lecture=query('SELECT * FROM lectures WHERE id = ?', id)[0],
				videos=query('SELECT * FROM videos WHERE lecture_id = ?', id))
	else:
159
160
161
162
163
164
165
166
167
168
169
170
171
172
		return redirect(url_for('index'))

@app.route('/search')
def search():
	if 'q' not in request.args:
		return redirect(url_for('index'))
	q = request.args['q']
	courses = searchquery(q, '*', ['title', 'short', 'organizer', 'subject', 'description'],
			'courses', 'WHERE (? OR (visible AND listed)) GROUP BY id ORDER BY _score DESC, semester DESC LIMIT 20', False)
	lectures = searchquery(q, 'lectures.*, courses.visible AS coursevisible, courses.listed, courses.short, courses.downloadable, courses.title AS coursetitle',
			['lectures.title', 'lectures.comment', 'lectures.speaker', 'courses.short'],
			'lectures LEFT JOIN courses on (courses.id = lectures.course_id)',
			'WHERE (? OR (coursevisible AND listed AND visible)) GROUP BY id ORDER BY _score DESC, time DESC LIMIT 30', False)
	return render_template('search.html', searchtext=request.args['q'], courses=courses, lectures=lectures)
Andreas Valder's avatar
Andreas Valder committed
173

Andreas Valder's avatar
Andreas Valder committed
174
175
176
177
@app.route('/course')
def course():
	if 'courseid' in request.args:
		id = request.args['courseid']
Andreas Valder's avatar
Andreas Valder committed
178
		course = query('SELECT * FROM courses WHERE handle = ?', id)[0]
Andreas Valder's avatar
Andreas Valder committed
179
		return render_template('course.html',
Andreas Valder's avatar
Andreas Valder committed
180
				course=course,
Andreas Valder's avatar
Andreas Valder committed
181
182
				lectures=query('SELECT * FROM lectures  WHERE course_id = ?', course['id']),
				videos=query('SELECT *, formats.description AS format_description  FROM videos JOIN lectures ON (videos.lecture_id = lectures.id) JOIN formats ON (videos.video_format = formats.id) WHERE lectures.course_id= ? ORDER BY formats.prio DESC', course['id']))
Andreas Valder's avatar
Andreas Valder committed
183
184
185
	else:
		return redirect(url_for('index'))

186
@app.route('/login', methods=['GET', 'POST'])
Julian Rother's avatar
Julian Rother committed
187
def login():
188
189
	if request.method == 'GET':
		return render_template('login.html')
Julian Rother's avatar
Julian Rother committed
190
	user, groups = ldapauth(request.form.get('user'), request.form.get('password'))
Julian Rother's avatar
Julian Rother committed
191
	if user and 'users' in groups:
Julian Rother's avatar
Julian Rother committed
192
		session['user'] = ldapget(user)
193
194
	else:
		flash('Login fehlgeschlagen!')
Julian Rother's avatar
Julian Rother committed
195
196
197
198
199
200
201
202
203
204
205
206
	if 'ref' in request.values:
		return redirect(request.values['ref'])
	else:
		return redirect(url_for('index'))

@app.route('/logout')
def logout():
	session.pop('user')
	if 'ref' in request.values:
		return redirect(request.values['ref'])
	else:
		return redirect(url_for('index'))
Julian Rother's avatar
Julian Rother committed
207

208
209
if __name__ == '__main__':
	app.run()