summaryrefslogtreecommitdiffstats
path: root/app.py
blob: ce7e7b431c5b473dfdec51a61ad92b7477fd98f1 (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
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/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, FileField, SelectField,\
                    validators, ValidationError
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' ]

FORM_MODULE_LIST= [
  ('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'),
  ('', u'---'),
  ('new', u'neues Modul hinzufügen')
]

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', choices = FORM_MODULE_LIST)
    module_new = TextField('Modulname', validators=[validators.Optional(),
    validators.Length(min=5)])
    year   = SelectField(
                'Jahr',
                validators=[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(u'Ungültiger Dateityp')

      if field.data.content_length > app.config['MAX_CONTENT_LENGTH']:
        raise ValidationError(u'Zu große Datei')
    
    def validate_module(form, field):
      modules = dict(FORM_MODULE_LIST)
      data = form.module.data
      if module not in modules or data == '':
        raise ValidationError(u'Bitte wähle ein Modul!')





@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')
        FORM_MODULE_LIST.append((slug,module))
      else:
        module = dict(FORM_MODULE_LIST)[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())



@app.route('/403')
@app.errorhandler(403)
def forbidden():
  return render_template('403.html')



if __name__ == "__main__":
    modules = dict(FORM_MODULE_LIST)
    # 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')
        FORM_MODULE_LIST.insert(len(FORM_MODULE_LIST) - 2, (slug, module))

    app.run()