forked from niccokunzmann/open-web-calendar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·204 lines (179 loc) · 7.17 KB
/
app.py
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/python3
from flask import Flask, render_template, make_response, request, jsonify, \
redirect, send_from_directory
from flask_caching import Cache
import json
import os
import tempfile
import requests
import icalendar
import datetime
from dateutil.rrule import rrulestr
from pprint import pprint
import yaml
import traceback
import io
import sys
from convert_to_dhtmlx import ConvertToDhtmlx
from convert_to_ics import ConvertToICS
# configuration
DEBUG = os.environ.get("APP_DEBUG", "true").lower() == "true"
PORT = int(os.environ.get("PORT", "5000"))
CACHE_REQUESTED_URLS_FOR_SECONDS = int(os.environ.get("CACHE_REQUESTED_URLS_FOR_SECONDS", 600))
# constants
HERE = os.path.dirname(__name__) or "."
DEFAULT_SPECIFICATION_PATH = os.path.join(HERE, "default_specification.yml")
TEMPLATE_FOLDER_NAME = "templates"
TEMPLATE_FOLDER = os.path.join(HERE, TEMPLATE_FOLDER_NAME)
CALENDARS_TEMPLATE_FOLDER_NAME = "calendars"
CALENDAR_TEMPLATE_FOLDER = os.path.join(TEMPLATE_FOLDER, CALENDARS_TEMPLATE_FOLDER_NAME)
STATIC_FOLDER_NAME = "static"
STATIC_FOLDER_PATH = os.path.join(HERE, STATIC_FOLDER_NAME)
DHTMLX_LANGUAGES_FILE = os.path.join(STATIC_FOLDER_PATH, "js", "dhtmlx", "locale", "languages.json")
# specification
PARAM_SPECIFICATION_URL = "specification_url"
# globals
app = Flask(__name__, template_folder="templates")
# Check Configuring Flask-Cache section for more details
cache = Cache(app, config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': tempfile.mktemp(prefix="cache-")})
# caching
__URL_CACHE = {}
def cache_url(url, text):
"""Cache the value of a url."""
__URL_CACHE[url] = text
try:
get_text_from_url(url)
finally:
del __URL_CACHE[url]
# configuration
def get_configuration():
"""Return the configuration for the browser"""
config = {
"default_specification": get_default_specification()
}
with open(DHTMLX_LANGUAGES_FILE, encoding="UTF-8") as file:
config["dhtmlx"] = {
"languages" : json.load(file)
}
return config
def set_JS_headers(response):
repsonse = make_response(response)
response.headers['Access-Control-Allow-Origin'] = '*'
# see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowHeaderFromPreflight
response.headers['Access-Control-Allow-Headers'] = request.headers.get("Access-Control-Request-Headers")
response.headers['Content-Type'] = 'text/calendar'
return response
def set_js_headers(func):
"""Set the response headers for a valid CORS request."""
def with_js_response(*args, **kw):
return set_JS_headers(func(*args, **kw))
return with_js_response
@cache.memoize(
CACHE_REQUESTED_URLS_FOR_SECONDS,
forced_update=lambda: bool(__URL_CACHE))
def get_text_from_url(url):
"""Return the text from a url.
The result is cached CACHE_REQUESTED_URLS_FOR_SECONDS.
"""
if __URL_CACHE:
return __URL_CACHE[url]
return requests.get(url).text
def get_default_specification():
"""Return the default specification."""
with open(DEFAULT_SPECIFICATION_PATH, encoding="UTF-8") as file:
return yaml.safe_load(file)
def get_specification(query=None):
"""Build the calendar specification."""
if query is None:
query = request.args
specification = get_default_specification()
# get a request parameter, see https://stackoverflow.com/a/11774434
url = query.get(PARAM_SPECIFICATION_URL, None)
if url:
url_specification_response = get_text_from_url(url)
try:
url_specification_values = json.loads(url_specification_response)
except json.JSONDecodeError:
url_specification_values = yaml.safe_load(url_specification_response)
specification.update(url_specification_values)
for parameter in query:
# get a list of arguments
# see http://werkzeug.pocoo.org/docs/0.14/datastructures/#werkzeug.datastructures.MultiDict
value = query.getlist(parameter, None)
if len(value) == 1:
value = value[0]
specification[parameter] = value
return specification
def get_query_string():
return "?" + request.query_string.decode()
def render_app_template(template, specification):
return render_template(template,
specification=specification,
json=json,
get_query_string=get_query_string
)
@app.route("/calendar.<type>", methods=['GET', 'OPTIONS'])
# use query string in cache, see https://stackoverflow.com/a/47181782/1320237
#@cache.cached(timeout=CACHE_TIMEOUT, query_string=True)
def get_calendar(type):
"""Return a calendar."""
specification = get_specification()
if type == "spec":
return jsonify(specification)
if type == "events.json":
strategy = ConvertToDhtmlx(specification, get_text_from_url)
strategy.retrieve_calendars()
return strategy.merge()
if type == "ics":
strategy = ConvertToICS(specification, get_text_from_url)
strategy.retrieve_calendars()
return strategy.merge()
if type == "html":
template_name = specification["template"]
all_template_names = os.listdir(CALENDAR_TEMPLATE_FOLDER)
assert template_name in all_template_names, "Template names must be file names like \"{}\", not \"{}\".".format("\", \"".join(all_template_names), template_name)
template = os.path.join(CALENDARS_TEMPLATE_FOLDER_NAME, template_name)
return render_app_template(template, specification)
raise ValueError("Cannot use extension {}. Please see the documentation or report an error.".format(type))
for folder_name in os.listdir(STATIC_FOLDER_PATH):
folder_path = os.path.join(STATIC_FOLDER_PATH, folder_name)
if not os.path.isdir(folder_path):
continue
@app.route('/' + folder_name + '/<path:path>', endpoint="static/" + folder_name)
def send_static(path, folder_name=folder_name):
return send_from_directory('static/' + folder_name, path)
@app.route("/")
def serve_index():
return send_from_directory("static", "index.html")
@app.route("/about.html")
def serve_about():
specification = get_specification()
return render_app_template("about.html", specification)
@app.route("/configuration.js")
def serve_configuration():
return "/* generated */\nconst configuration = {};".format(json.dumps(get_configuration()))
@app.errorhandler(500)
def unhandledException(error):
"""Called when an error occurs.
See https://stackoverflow.com/q/14993318
"""
file = io.StringIO()
traceback.print_exception(type(error), error, error.__traceback__, file=file)
return """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>500 Internal Server Error</title>
</head>
<body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
<pre>\r\n{traceback}
</pre>
</body>
</html>
""".format(traceback=file.getvalue()), 500 # return error code from https://stackoverflow.com/a/7824605
if __name__ == "__main__":
app.run(debug=DEBUG, host="0.0.0.0", port=PORT)