summaryrefslogtreecommitdiffstats
path: root/app.py
blob: cbac1f78575442fa31fdf177b1357677e1968747 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import magic, os

from fit import Fit
from flask import Flask, render_template, request, flash, redirect, \
                    url_for,jsonify
from flask.ext.wtf import Form, TextField, Required, FileField, SelectField,\
                    ValidationError, file_required
from werkzeug import secure_filename
from datetime import date


fit = Fit('static/fit.git')

app = Flask(__name__)
app.config.from_object('settings')

ALLOWED_EXTENSIONS = ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'zip', 'gs', 'gz' ]

MODULES= [
  ('new', u'neues Modul hinzufügen'),
  ('alp1', u'ALP1 - Funktionale Programmierung'),
  ('alp2', u'ALP2 - Objektorientierte Programmierung'),
  ('alp3', u'ALP3 - Datenstrukturen'),
  ('alp4', u'ALP4 - Nichtsequentielle Programmierung'),
  ('alp5', u'ALP5 - Netzprogrammierung'),
  ('ti1', u'TI1 - Grundlagen der Technischen Informatik'),
  ('ti2', u'TI2 - Rechnerarchitektur'),
  ('ti3', u'TI3 - Betriebs- und Kommunikationssysteme'),
  ('mafi1', u'MafI1 - Logik und Diskrete Mathematik'),
  ('mafi2', u'MafI2 - Analysis'),
  ('mafi3', u'MafI3 - Lineare Algebra'),
  ('gti', u'Grundlagen der Theoretischen Informatik'),
  ('dbs', u'Datenbanksysteme'),
  ('swt', u'Softwaretechnik'),
  ('aws', u'Anwendungssysteme')
  ]

TERM_START_YEAR = 1999
YEARS = [(str(x),x) for x in xrange(date.today().year, TERM_START_YEAR, -1)]



class UploadForm(Form):
    """ Upload Form class for validation """
    exam   = FileField('Klausur')
    module = SelectField(
                'Kurs',
                validators=[Required()],
                choices = MODULES
             )
    module_new = TextField('Modulname', default='Modulname')
    year   = SelectField(
                'Jahr',
                validators=[Required()],
                choices = YEARS
           )

    def validate_exam(form, field):
      ext = map(lambda x: field.data.filename.endswith(x), ALLOWED_EXTENSIONS)
      if not any(ext):
        raise ValidationError('Invalid file type')

      if field.data.content_length > app.config['MAX_CONTENT_LENGTH']:
        raise ValidationError('File is too big')



@app.route('/upload', methods=['GET', 'POST'])
def upload():
  form = UploadForm()

  if form.validate_on_submit():
      if form.module.data == 'new':
        module = form.module_new.data
        slug = module.encode('ascii', errors='ignore')
        MODULES.append((slug,module))
      else:
        module = dict(MODULES)[form.module.data]

      year = form.year.data
      filename = secure_filename(form.exam.data.filename)
      path = os.path.join(module,year,filename).encode('ascii', errors='ignore')

      try:
        oid =  fit.add_file(form.exam.data.stream.getvalue(), path)
      except:
        oid =  fit.add_file(form.exam.data.stream.read(), path)

      flash("Datei %s gespeichert." % filename)

      return redirect(url_for('index', module = module))

  return render_template('upload.html', form = form)



@app.route('/files/<oid>')
def show(oid):
  data = fit.get_file(oid)
  mime = magic.Magic(mime=True)
  header = { 'Content-Type' : mime.from_buffer(data[:1024]) }
  return data, 200, header



@app.route('/')
@app.route('/modules')
@app.route('/modules/<module>')
def index(module=None):
  if module:
    return render_template(
      'module_show.html', module=module, entries=fit.get_module(module)
    )

  return render_template('module_list.html', modules=fit.get_modules())



if __name__ == "__main__":
    modules = dict(MODULES)
    # extend module list with git values
    for module in fit.get_modules():
      # check if module is already listed
      if all(map(lambda (k,v): v != module, modules.items())):
        slug = module.encode('ascii', errors='ignore')
        MODULES.append((slug, module))

    app.run()