server.py 4.41 KB
Newer Older
1
#!/bin/python
Julian Rother's avatar
Julian Rother committed
2
from flask import Flask, render_template, g, request, url_for, redirect
3
import mysql.connector
4
import sqlite3
5
import os
6

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

21
22
23
24
25
26
27
28
29
30
31
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()

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

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

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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)

74
75
@app.route('/')
def index():
76
	return render_template('index.html', latestvideos=query('''
77
				SELECT lectures.*, max(videos.time_updated) AS lastvidtime, courses.short, courses.downloadable, courses.title AS coursetitle
78
79
80
				FROM lectures
				LEFT JOIN videos ON (videos.lecture_id = lectures.id)
				LEFT JOIN courses on (courses.id = lectures.course_id)
81
				WHERE (? OR (courses.visible AND courses.listed AND lectures.visible AND videos.visible))
82
83
				GROUP BY videos.lecture_id
				ORDER BY lastvidtime DESC
Andreas Valder's avatar
.    
Andreas Valder committed
84
				LIMIT 6
85
			''', False))
86

Andreas Valder's avatar
Andreas Valder committed
87
88
@app.route('/videos')
def videos():
89
90
91
92
	c=query("SELECT * FROM courses")
	for i in c:
		if i['semester'] == '':
			i['semester'] = 'zeitlos'
Andreas Valder's avatar
Andreas Valder committed
93
94
95
96
	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
97
98
99

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

Andreas Valder's avatar
Andreas Valder committed
102
103
@app.route('/play')
def play():
Julian Rother's avatar
Julian Rother committed
104
105
106
107
108
109
	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:
110
111
112
113
114
115
116
117
118
119
120
121
122
123
		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
124

125
126
if __name__ == '__main__':
	app.run()