-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
144 lines (119 loc) · 5.46 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
import datetime
import os
import sys
import threading
import flask
from flask import Flask, request, render_template
import config
import utils.scheduler
import utils.weather_manager
from blueprints.api import api
from blueprints.rss import rss
from blueprints.views import views
from database import Database
from notifications import Feed
from telegram import bot as telegram_bot
from utils.jsonencoder import CustomJSONEncoder
print("waiting until db is ready")
os.popen(f"/bin/bash ./docker/wait-for-it.sh {config.MySql.host}:{str(config.MySql.port)}").read()
print("db ready")
# Check whether the script is started from the directory it's contained in
if not os.path.isfile("app.py"):
print("You need to start this script from the directory it's contained in. Please cd into that folder.")
exit()
path = os.path.abspath("logs")
if not os.path.exists(path): os.mkdir(path)
print("################################")
print("# BeeLogger #")
print("# ----------------------- #")
print("# by Fabian R., Soenke K. #")
print("################################")
print("\nInitializing database...")
database = Database()
try:
database.prepare_database()
print("Database prepared.")
except Exception as exception:
print("An error occurred while trying to connect to (and prepare) the database:")
raise exception
# Initialize Flask app
app = Flask("BeeLogger", static_folder='public', static_url_path='', template_folder='pages')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SERVER_NAME'] = config.server_name
app.json_encoder = CustomJSONEncoder
# Set app redirect scheme
if config.server_scheme == "https":
app.config['PREFERRED_URL_SCHEME'] = "https"
# Initialize all routes that display a rendered template
app.register_blueprint(views, url_prefix='/')
# Initialize all routes of the REST API
app.register_blueprint(api, url_prefix='/api')
# Initialize all routes for the RSS feeds
app.register_blueprint(rss, url_prefix='/rss')
@app.route("/opt-in/")
def opt_in():
if "OPT_IN_COMNFIRM" in request.args.keys():
response = flask.make_response(flask.redirect(flask.url_for("views.dashboard", _external=True, _scheme=config.server_scheme)))
response.headers.add('Set-Cookie', 'opt-in=true; Path=/; SameSite=None; Secure; Max-Age=2592000') # Set opt-in cookie for 30 days
return response
return render_template("opt-in.html", privacy_url=config.privacy_url)
@app.route("/opt-out/")
def opt_out():
response = flask.make_response(flask.redirect(flask.url_for("views.dashboard", _external=True, _scheme=config.server_scheme)))
response.headers.add('Set-Cookie', 'opt-in=false; Path=/; SameSite=None; Secure; Max-Age=0') # Delete opt-in cookie
return response
# Route to check if provider can insert
@app.route("/healthcheck/")
def check_provider():
if "insert" in request.args.keys():
if request.args["token"] == config.insert_token:
return "OK"
else:
return "Invalid token", 401
else:
return "Don't know how to check", 400
@app.after_request
def add_header_check_cookies(r):
if request.cookies.get("opt-in") != "true" and request.path.split("/")[1] not in ["opt-in",
"display",
"healthcheck",
"opt-out",
"api",
"rss",
"lib",
"assets",
"css",
"js",
"favicon.ico"]:
response = flask.make_response(flask.redirect(flask.url_for("opt_in", _external=True, _scheme=config.server_scheme)))
for cookie in request.cookies:
response.delete_cookie(cookie)
return response
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
Credit: https://stackoverflow.com/a/34067710
"""
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
if not config.telegram_bot_token == "":
telegram_bot_thread = threading.Thread(target=telegram_bot.infinity_polling)
telegram_bot_thread.daemon = True
telegram_bot_thread.start()
else:
print(">>> Not starting telegram bot because there is no token")
scheduler_thread = threading.Thread(target=utils.scheduler.run_tasks)
scheduler_thread.daemon = True
scheduler_thread.start()
Feed().push_notification("admin", "Beelogger gestartet", "BeeLogger wurde gerade gestartet...")
# Start the app
if __name__ == "__main__":
try:
app.run(host='0.0.0.0', port=config.web_port)
except (KeyboardInterrupt, SystemExit):
print(">>> Stopping BeeLogger...")
database.connection_pool.close()
sys.exit(0)