summaryrefslogtreecommitdiffstats
path: root/app/backend.py
blob: e601c0c3edf068cc75d035f9d26479fa533bd203 (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
# -*- coding: utf-8 -*-

import os
import magic
from functools import partial

class Storage:
    def __init__(self, path_rel, path_app):
        self.path = path_app 
        self.root = path_rel

    def _join(self, *arg):
      return os.path.join(self.path, *arg)

    def get_courses(self):
      """ Lists all courses of a study """
      return [o.decode('utf-8') for o in os.listdir(self.path)
                                if os.path.isdir(self._join(o))]

    def exam_exists(self, course, year, name):
      """ Exists if an exam (file) exists """
      return os.path.exists(self._join(course, year, name))

    def add_exam(self, course, year, filename, data):
      # create course dir with year if it does not exist already
      dir_name = self._join(course, year)
      if not os.path.exists(dir_name):
        os.makedirs(dir_name)

      # save exam
      path = self._join(course, year, filename)
      with open(path, 'wb') as f:
        f.write(data)

    def get_exams(self, name):
      """ Lists all exams of a given course """
      # loop over all directories which do not contain any subdirs
      for root, dirs, files in os.walk(self._join(name).encode('utf-8')):
        if len(dirs) == 0:
          # metainformation is encoded in path: course/year/exam.pdf
          splitted = root.split(os.path.sep)
          if len(splitted) > 1:
            year  = splitted[-1]
            course = splitted[-2]
            if year.isdigit():
              # yield entries as tuples (name, path) grouped by years
              func = partial(os.path.join, self.root, course, year)
              entries = [(f, func(f)) for f in files]
              yield (year, entries)