web.py 4.08 KB
Newer Older
Christoph's avatar
Christoph committed
1
2
3
#!/usr/bin/python
# -*- coding: utf-8 -*-

4
5
6
from jinja2 import Environment, FileSystemLoader, BaseLoader
from jinja2.exceptions import TemplateNotFound

Christoph's avatar
Christoph committed
7
8
from werkzeug import Local, LocalManager, Response
from werkzeug.routing import Map, Rule
9
from werkzeug.exceptions import BadRequest
10

11
import os
12
import netaddr
13

Christoph's avatar
Christoph committed
14
import util.gitVersion
Christoph's avatar
Christoph committed
15
import util.univis
16
17
import config

Christoph's avatar
Christoph committed
18
19
from backend.db import public_pdf_db

20
21
22
23
24
25
26
27
28
29
30
def expose(rule, **kw):
    def decorate(f):
        kw['endpoint'] = f.__name__
        url_map.add(Rule(rule, **kw))
        url_map.add(Rule('/static/<file>', endpoint='static', build_only=True))
        return f
    return decorate

def url_for(endpoint, _external=False, **values):
    return local.url_adapter.build(endpoint, values, force_external=_external)

31
32
33
34
35
36
37
def theme_for_url(url):
    for k, v in config.themes_by_url:
        if k == url:
            return v

    return config.default_theme

38
def render_template(template, **context):
Christoph's avatar
Christoph committed
39
40
41
42
    try:
        context['git_commit'] = util.gitVersion.gitVersion(config.basedir)
    except:
        pass
43

44
    return Response(jinja_env.get_template(template).render(**context),
45
        mimetype='application/xhtml+xml')
46

47
48

def profify(name, title):
49
50
    "Return name with title attached. Currently no title is displayed"
    return name
51

Christoph's avatar
Christoph committed
52
53
54
55
56
57
58
def completion_hints():
    return {'names': public_pdf_db.collect_unique_field("name"),
            'lectures': public_pdf_db.collect_unique_field("lecture"),
            'semesters': public_pdf_db.collect_unique_field("semester"),
            'types': public_pdf_db.collect_unique_field("lecture_type"),
            'titles': public_pdf_db.collect_unique_field("title")}

59
60
61
62
63
64
65
66
67
68
69
def update_meta_from_request(metadata, form):
    metadata['lecture'] = form.get('lecture')
    metadata['lecture_type'] = form.get('lecture_type')
    metadata['semester'] = (int(form.get('semester_jahr')),
                                form.get('semester_typ'))

    metadata['title'] = form.get('title')
    metadata['name'] = form.get('name')
    if metadata['name'] == u'':
        metadata['name'] = None

70
    metadata['internal_net_only'] = bool(form.get('internal_net_only'))
71

72
73
74
75
    metadata['comment'] = form.get('comment')
    if metadata['comment'] == u'' or not 'keeptext' in form:
        metadata['comment'] = None

76
77
78
79
80
    metadata['department'] = form.get('department')
    if metadata['department'] == u'':
        metadata['department'] = None

    metadata['courses'] = set()
Christoph's avatar
Christoph committed
81
82
83
84
85
86
    if not form.get('courses') == '':
        for coursestring in form.get('courses').strip().split('\n'):
            course = coursestring.split()
            if len(course) != 3:
                return None
            metadata['courses'].add(tuple(course))
87

88
89
90
    return metadata


91
92
93
94
95
96
97
98
99
100
101
102
103
104
class ThemeSupportTemplateLoader(BaseLoader):
    def __init__(self, themes):
        self.loaders = dict([
            (theme, FileSystemLoader(os.path.join(config.templates, theme))) \
                    for theme in themes])
        self.default_loader = FileSystemLoader(config.templates)

    def get_source(self, environment, template):
        theme = local.theme
        try:
            return self.loaders[theme].get_source(environment, template)
        except TemplateNotFound:
            return self.default_loader.get_source(environment, template)

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

def get_remote_addr(request):
    try:
        return request.environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
    except KeyError:
        return request.environ['REMOTE_ADDR']

def remote_is_internal_network(request):
    remote_addr = netaddr.IPAddress(get_remote_addr(request))
    for net in config.local_networks:
        if remote_addr in netaddr.IPNetwork(net):
            return True
    return False


120
121
available_themes = set([it[1] for it in config.themes_by_url])
available_themes.add(config.default_theme)
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
122
jinja_env = Environment(loader=ThemeSupportTemplateLoader(available_themes), cache_size=0)
123
jinja_env.globals['url_for'] = url_for
124

125
jinja_env.filters['profify'] = profify
Christoph's avatar
Christoph committed
126
jinja_env.filters['univislink'] = util.univis.generate_univis_link
127
128
129
130
131
132

local = Local()
local_manager = LocalManager([local])
application = local('application')

url_map = Map()