summaryrefslogtreecommitdiffstats
path: root/app.py
blob: baaf3d21a97617d70470f2be627249afcd59c0c2 (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
144
145
146
147
#!/usr/bin/python2
# -*- coding: utf-8 -*-

import magic, os

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


app = Flask(__name__)
app.config.from_pyfile('settings.py')

# populate Module-List
fit = {}
for i, study in enumerate(app.config['STUDIES'].items()):
  abbr = study[0]
  fit[abbr] = Fit(os.path.join('static','studies',abbr + '.git'))

  modules = app.config['STUDIES'][study[0]]
  # extend module list with git values
  for module in fit[abbr].get_modules():
    # check if module is already listed
    if all(map(lambda (k,v): v != module, modules)):
      slug = module.encode('ascii', errors='ignore')
      app.config['STUDIES'][study[0]].append((slug, module))

class UploadForm(Form):
    """ Upload Form class for validation """
    study = TextField('Studiengang')
    exam   = FileField('Klausur')
    module = SelectField('Kurs')
    module_new = TextField('Modulname', validators=[validators.Optional(),
    validators.Length(min=5)])
    year   = SelectField(
                'Jahr',
                validators=[validators.Required()],
                choices = [ (str(x),x) for x in 
                  xrange(date.today().year, app.config['FORM_START_YEAR']-1, -1)
                ]
           )

    def validate_exam(form, field):
      exts = app.config['ALLOWED_EXTENSIONS']
      ext = map(field.data.filename.endswith, exts)

      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(app.config['STUDIES'][form.study.data])
      data = form.module.data
      if data not in modules or data == '':
        raise ValidationError(u'Bitte wähle ein Modul!')




@app.route('/<study>/upload/', methods=['GET', 'POST'])
@app.route('/<study>/upload/<module>', methods=['GET', 'POST'])
def upload(study, module = None):
  form = UploadForm()
  form.study.data = study

  form.module.choices = app.config['STUDIES'][study]
  if 'new' not in dict(form.module.choices):
    if len(form.module.choices) > 0:
      form.module.choices.append(('', u'---'))
    form.module.choices.append(('new', u'neues Modul hinzufügen'))


  if form.validate_on_submit():
      if form.module.data == 'new':
        module = form.module_new.data
        slug = module.encode('ascii', errors='ignore')
        app.config['STUDIES'][study].append((slug,module))
      else:
        module = dict(app.config['STUDIES'][study])[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[study].add_file(form.exam.data.stream.getvalue(), path)
      except:
        oid =  fit[study].add_file(form.exam.data.stream.read(), path)

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

      return redirect(url_for('study_index', study = study, module = module))

  try: form.module.data = [k for (k,v) in form.module.choices if v == module][0]
  except: pass

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



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



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

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



@app.route('/')
def index():
  get_img_path = lambda x: os.path.join('images', x +'.png')
  studies = [(name,get_img_path(name)) for name,m in app.config['STUDIES'].items()]

  return render_template(
            'index.html',
            studies = studies
         )



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



if __name__ == "__main__":
    app.run()