2020-09-22 09:54:26 +00:00
|
|
|
'''
|
|
|
|
Do not execute this file directly.
|
2021-01-20 08:39:01 +00:00
|
|
|
Use etiquette_flask_dev.py or etiquette_flask_prod.py.
|
2020-09-22 09:54:26 +00:00
|
|
|
'''
|
2018-01-12 03:40:56 +00:00
|
|
|
import flask; from flask import request
|
2021-10-31 22:11:17 +00:00
|
|
|
import functools
|
2023-02-04 21:49:42 +00:00
|
|
|
import json
|
2018-01-12 03:40:56 +00:00
|
|
|
import mimetypes
|
|
|
|
import traceback
|
|
|
|
|
2018-03-19 04:42:31 +00:00
|
|
|
from voussoirkit import bytestring
|
2023-02-04 21:49:42 +00:00
|
|
|
from voussoirkit import configlayers
|
2021-04-03 01:31:44 +00:00
|
|
|
from voussoirkit import flasktools
|
2018-01-12 03:40:56 +00:00
|
|
|
from voussoirkit import pathclass
|
2023-02-04 21:49:42 +00:00
|
|
|
from voussoirkit import vlogging
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2018-11-05 03:27:20 +00:00
|
|
|
import etiquette
|
|
|
|
|
2021-01-05 21:03:41 +00:00
|
|
|
from . import client_caching
|
2018-04-15 07:59:54 +00:00
|
|
|
from . import jinja_filters
|
2023-02-04 21:49:42 +00:00
|
|
|
from . import permissions
|
2018-02-03 09:43:41 +00:00
|
|
|
from . import sessions
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2023-02-04 21:49:42 +00:00
|
|
|
log = vlogging.getLogger(__name__)
|
|
|
|
|
|
|
|
# Constants ########################################################################################
|
|
|
|
|
|
|
|
DEFAULT_SERVER_CONFIG = {
|
|
|
|
'anonymous_read': True,
|
|
|
|
'anonymous_write': True,
|
|
|
|
}
|
|
|
|
|
|
|
|
BROWSER_CACHE_DURATION = 180
|
|
|
|
|
2020-09-22 09:54:26 +00:00
|
|
|
# Flask init #######################################################################################
|
2020-09-19 10:13:23 +00:00
|
|
|
|
2021-10-31 22:10:54 +00:00
|
|
|
# __file__ = .../etiquette_flask/backend/common.py
|
|
|
|
# root_dir = .../etiquette_flask
|
2018-02-03 09:43:41 +00:00
|
|
|
root_dir = pathclass.Path(__file__).parent.parent
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2023-02-04 21:49:42 +00:00
|
|
|
P = None
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
TEMPLATE_DIR = root_dir.with_child('templates')
|
|
|
|
STATIC_DIR = root_dir.with_child('static')
|
|
|
|
FAVICON_PATH = STATIC_DIR.with_child('favicon.png')
|
2023-02-04 21:49:42 +00:00
|
|
|
SERVER_CONFIG_FILENAME = 'etiquette_flask_config.json'
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
site = flask.Flask(
|
|
|
|
__name__,
|
|
|
|
template_folder=TEMPLATE_DIR.absolute_path,
|
|
|
|
static_folder=STATIC_DIR.absolute_path,
|
|
|
|
)
|
|
|
|
site.config.update(
|
2019-01-13 22:47:13 +00:00
|
|
|
SEND_FILE_MAX_AGE_DEFAULT=BROWSER_CACHE_DURATION,
|
2018-01-12 03:40:56 +00:00
|
|
|
TEMPLATES_AUTO_RELOAD=True,
|
|
|
|
)
|
2023-02-04 21:49:42 +00:00
|
|
|
site.server_config = None
|
2018-01-12 03:40:56 +00:00
|
|
|
site.jinja_env.add_extension('jinja2.ext.do')
|
|
|
|
site.jinja_env.trim_blocks = True
|
|
|
|
site.jinja_env.lstrip_blocks = True
|
2020-09-09 20:23:16 +00:00
|
|
|
jinja_filters.register_all(site)
|
2020-09-30 22:15:49 +00:00
|
|
|
site.localhost_only = False
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2018-03-19 04:23:48 +00:00
|
|
|
session_manager = sessions.SessionManager(maxlen=10000)
|
2021-01-05 21:03:41 +00:00
|
|
|
file_etag_manager = client_caching.FileEtagManager(
|
2018-03-19 04:42:31 +00:00
|
|
|
maxlen=10000,
|
2022-11-14 03:12:50 +00:00
|
|
|
max_filesize=5 * bytestring.MEBIBYTE,
|
2019-01-13 22:47:13 +00:00
|
|
|
max_age=BROWSER_CACHE_DURATION,
|
2018-03-19 04:42:31 +00:00
|
|
|
)
|
2023-02-04 21:49:42 +00:00
|
|
|
permission_manager = permissions.PermissionManager(site)
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2020-09-19 10:13:23 +00:00
|
|
|
# Response wrappers ################################################################################
|
|
|
|
|
2022-03-23 21:58:41 +00:00
|
|
|
def catch_etiquette_exception(endpoint):
|
|
|
|
'''
|
|
|
|
If an EtiquetteException is raised, automatically catch it and convert it
|
|
|
|
into a json response so that the user doesn't receive error 500.
|
|
|
|
'''
|
|
|
|
@functools.wraps(endpoint)
|
|
|
|
def wrapped(*args, **kwargs):
|
|
|
|
try:
|
|
|
|
return endpoint(*args, **kwargs)
|
|
|
|
except etiquette.exceptions.EtiquetteException as exc:
|
|
|
|
if isinstance(exc, etiquette.exceptions.NoSuch):
|
|
|
|
status = 404
|
|
|
|
else:
|
|
|
|
status = 400
|
|
|
|
response = flasktools.json_response(exc.jsonify(), status=status)
|
|
|
|
flask.abort(response)
|
|
|
|
return wrapped
|
2020-09-12 18:43:25 +00:00
|
|
|
|
2020-09-30 22:15:49 +00:00
|
|
|
@site.before_request
|
|
|
|
def before_request():
|
2021-10-25 06:21:11 +00:00
|
|
|
# Note for prod: If you see that remote_addr is always 127.0.0.1 for all
|
|
|
|
# visitors, make sure your reverse proxy is properly setting X-Forwarded-For
|
|
|
|
# so that werkzeug's proxyfix can set that as the remote_addr.
|
|
|
|
# In NGINX: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
2021-06-05 04:33:55 +00:00
|
|
|
request.is_localhost = (request.remote_addr == '127.0.0.1')
|
2021-02-26 02:52:25 +00:00
|
|
|
if site.localhost_only and not request.is_localhost:
|
2023-02-02 06:04:44 +00:00
|
|
|
return flask.abort(403)
|
|
|
|
|
2023-06-26 04:13:52 +00:00
|
|
|
if request.url_rule is None:
|
|
|
|
return flask.abort(404)
|
|
|
|
|
|
|
|
# Since we don't define this route (/static/ is a default from flask),
|
|
|
|
# I can't just add this where it belongs. Sorry.
|
2023-02-04 21:49:42 +00:00
|
|
|
if request.url_rule.rule == '/static/<path:filename>':
|
|
|
|
permission_manager.global_public()
|
|
|
|
|
2023-02-02 06:04:44 +00:00
|
|
|
session_manager._before_request(request)
|
2020-09-30 22:15:49 +00:00
|
|
|
|
2021-01-05 09:27:14 +00:00
|
|
|
@site.after_request
|
|
|
|
def after_request(response):
|
2023-02-04 21:49:42 +00:00
|
|
|
if response.status_code < 400 and not hasattr(request, 'checked_permissions'):
|
|
|
|
log.error('You forgot to set checked_permissions for ' + request.path)
|
|
|
|
return flask.abort(500)
|
2021-04-03 01:31:44 +00:00
|
|
|
response = flasktools.gzip_response(request, response)
|
2023-02-02 06:04:44 +00:00
|
|
|
response = session_manager._after_request(response)
|
2020-09-12 06:12:37 +00:00
|
|
|
return response
|
|
|
|
|
2022-03-23 21:58:41 +00:00
|
|
|
site.route = flasktools.decorate_and_route(
|
|
|
|
flask_app=site,
|
|
|
|
decorators=[
|
|
|
|
flasktools.ensure_response_type,
|
|
|
|
functools.partial(
|
|
|
|
flasktools.give_theme_cookie,
|
|
|
|
cookie_name='etiquette_theme',
|
|
|
|
default_theme='slate',
|
|
|
|
),
|
|
|
|
catch_etiquette_exception,
|
|
|
|
],
|
|
|
|
)
|
|
|
|
|
2020-09-19 10:13:23 +00:00
|
|
|
# P functions ######################################################################################
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
def P_wrapper(function):
|
2020-02-27 01:50:36 +00:00
|
|
|
def P_wrapped(thingid, response_type):
|
|
|
|
if response_type not in {'html', 'json'}:
|
|
|
|
raise TypeError(f'response_type should be html or json, not {response_type}.')
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
try:
|
|
|
|
return function(thingid)
|
|
|
|
|
|
|
|
except etiquette.exceptions.EtiquetteException as exc:
|
|
|
|
if isinstance(exc, etiquette.exceptions.NoSuch):
|
|
|
|
status = 404
|
|
|
|
else:
|
|
|
|
status = 400
|
|
|
|
|
|
|
|
if response_type == 'html':
|
|
|
|
flask.abort(status, exc.error_message)
|
|
|
|
else:
|
2021-01-01 20:56:05 +00:00
|
|
|
response = exc.jsonify()
|
2021-10-02 06:05:46 +00:00
|
|
|
response = flasktools.json_response(response, status=status)
|
2018-01-12 03:40:56 +00:00
|
|
|
flask.abort(response)
|
|
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
traceback.print_exc()
|
|
|
|
if response_type == 'html':
|
|
|
|
flask.abort(500)
|
|
|
|
else:
|
2021-10-02 06:05:46 +00:00
|
|
|
flask.abort(flasktools.json_response({}, status=500))
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
return P_wrapped
|
|
|
|
|
|
|
|
@P_wrapper
|
|
|
|
def P_album(album_id):
|
|
|
|
return P.get_album(album_id)
|
|
|
|
|
2020-09-28 06:21:12 +00:00
|
|
|
@P_wrapper
|
|
|
|
def P_albums(album_ids):
|
|
|
|
return P.get_albums_by_id(album_ids)
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
@P_wrapper
|
2018-07-29 08:25:53 +00:00
|
|
|
def P_bookmark(bookmark_id):
|
|
|
|
return P.get_bookmark(bookmark_id)
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
@P_wrapper
|
|
|
|
def P_photo(photo_id):
|
|
|
|
return P.get_photo(photo_id)
|
|
|
|
|
2018-05-02 01:09:35 +00:00
|
|
|
@P_wrapper
|
|
|
|
def P_photos(photo_ids):
|
|
|
|
return P.get_photos_by_id(photo_ids)
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
@P_wrapper
|
|
|
|
def P_tag(tagname):
|
2018-02-17 06:25:56 +00:00
|
|
|
return P.get_tag(name=tagname)
|
2018-01-12 03:40:56 +00:00
|
|
|
|
2018-07-20 05:42:21 +00:00
|
|
|
@P_wrapper
|
|
|
|
def P_tag_id(tag_id):
|
|
|
|
return P.get_tag(id=tag_id)
|
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
@P_wrapper
|
|
|
|
def P_user(username):
|
|
|
|
return P.get_user(username=username)
|
|
|
|
|
|
|
|
@P_wrapper
|
|
|
|
def P_user_id(user_id):
|
|
|
|
return P.get_user(id=user_id)
|
|
|
|
|
2020-09-19 10:13:23 +00:00
|
|
|
# Other functions ##################################################################################
|
|
|
|
|
|
|
|
def back_url():
|
|
|
|
return request.args.get('goto') or request.referrer or '/'
|
|
|
|
|
2020-09-12 17:13:24 +00:00
|
|
|
def render_template(request, template_name, **kwargs):
|
2021-06-05 04:29:23 +00:00
|
|
|
theme = request.cookies.get('etiquette_theme', None)
|
2020-09-10 02:26:11 +00:00
|
|
|
|
|
|
|
response = flask.render_template(
|
2020-09-12 17:13:24 +00:00
|
|
|
template_name,
|
2021-02-26 02:52:25 +00:00
|
|
|
request=request,
|
2020-09-10 02:26:11 +00:00
|
|
|
theme=theme,
|
2019-08-14 20:40:52 +00:00
|
|
|
**kwargs,
|
|
|
|
)
|
2020-09-10 02:26:11 +00:00
|
|
|
return response
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
def send_file(filepath, override_mimetype=None):
|
|
|
|
'''
|
|
|
|
Range-enabled file sending.
|
|
|
|
'''
|
2018-03-19 04:40:32 +00:00
|
|
|
filepath = pathclass.Path(filepath)
|
2018-03-13 09:50:54 +00:00
|
|
|
|
2018-03-19 04:40:32 +00:00
|
|
|
if not filepath.is_file:
|
2018-01-12 03:40:56 +00:00
|
|
|
flask.abort(404)
|
|
|
|
|
2020-09-22 09:54:26 +00:00
|
|
|
file_size = filepath.size
|
|
|
|
|
2021-01-05 20:59:18 +00:00
|
|
|
headers = file_etag_manager.get_304_headers(request=request, filepath=filepath)
|
2018-07-23 03:18:06 +00:00
|
|
|
if headers:
|
|
|
|
response = flask.Response(status=304, headers=headers)
|
|
|
|
return response
|
2018-03-19 04:42:31 +00:00
|
|
|
|
2018-01-12 03:40:56 +00:00
|
|
|
outgoing_headers = {}
|
|
|
|
if override_mimetype is not None:
|
|
|
|
mimetype = override_mimetype
|
|
|
|
else:
|
2018-03-19 04:40:32 +00:00
|
|
|
mimetype = mimetypes.guess_type(filepath.absolute_path)[0]
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
if mimetype is not None:
|
|
|
|
if 'text/' in mimetype:
|
|
|
|
mimetype += '; charset=utf-8'
|
|
|
|
outgoing_headers['Content-Type'] = mimetype
|
|
|
|
|
|
|
|
if 'range' in request.headers:
|
|
|
|
desired_range = request.headers['range'].lower()
|
|
|
|
desired_range = desired_range.split('bytes=')[-1]
|
|
|
|
|
|
|
|
int_helper = lambda x: int(x) if x.isdigit() else None
|
|
|
|
if '-' in desired_range:
|
|
|
|
(desired_min, desired_max) = desired_range.split('-')
|
|
|
|
range_min = int_helper(desired_min)
|
|
|
|
range_max = int_helper(desired_max)
|
|
|
|
else:
|
|
|
|
range_min = int_helper(desired_range)
|
2018-03-19 04:40:32 +00:00
|
|
|
range_max = None
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
if range_min is None:
|
|
|
|
range_min = 0
|
|
|
|
if range_max is None:
|
2020-09-22 09:54:26 +00:00
|
|
|
range_max = file_size
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
# because ranges are 0-indexed
|
2020-09-22 09:54:26 +00:00
|
|
|
range_max = min(range_max, file_size - 1)
|
2018-01-12 03:40:56 +00:00
|
|
|
range_min = max(range_min, 0)
|
|
|
|
|
|
|
|
range_header = 'bytes {min}-{max}/{outof}'.format(
|
|
|
|
min=range_min,
|
|
|
|
max=range_max,
|
2020-09-22 09:54:26 +00:00
|
|
|
outof=file_size,
|
2018-01-12 03:40:56 +00:00
|
|
|
)
|
|
|
|
outgoing_headers['Content-Range'] = range_header
|
|
|
|
status = 206
|
|
|
|
else:
|
2020-09-22 09:54:26 +00:00
|
|
|
range_max = file_size - 1
|
2018-01-12 03:40:56 +00:00
|
|
|
range_min = 0
|
|
|
|
status = 200
|
|
|
|
|
|
|
|
outgoing_headers['Accept-Ranges'] = 'bytes'
|
|
|
|
outgoing_headers['Content-Length'] = (range_max - range_min) + 1
|
2021-01-05 20:59:18 +00:00
|
|
|
|
|
|
|
file_etag = file_etag_manager.get_file(filepath)
|
|
|
|
if file_etag is not None:
|
|
|
|
outgoing_headers.update(file_etag.get_headers())
|
2018-01-12 03:40:56 +00:00
|
|
|
|
|
|
|
if request.method == 'HEAD':
|
|
|
|
outgoing_data = bytes()
|
|
|
|
else:
|
|
|
|
outgoing_data = etiquette.helpers.read_filebytes(
|
2018-03-19 04:40:32 +00:00
|
|
|
filepath.absolute_path,
|
2018-01-12 03:40:56 +00:00
|
|
|
range_min=range_min,
|
|
|
|
range_max=range_max,
|
|
|
|
chunk_size=P.config['file_read_chunk'],
|
|
|
|
)
|
|
|
|
|
|
|
|
response = flask.Response(
|
|
|
|
outgoing_data,
|
|
|
|
status=status,
|
|
|
|
headers=outgoing_headers,
|
|
|
|
)
|
|
|
|
return response
|
2020-09-22 09:54:26 +00:00
|
|
|
|
|
|
|
####################################################################################################
|
|
|
|
|
2021-04-04 18:17:45 +00:00
|
|
|
# These functions will be called by the launcher, flask_dev, flask_prod.
|
|
|
|
|
2020-09-22 09:54:26 +00:00
|
|
|
def init_photodb(*args, **kwargs):
|
|
|
|
global P
|
2021-01-09 23:41:52 +00:00
|
|
|
P = etiquette.photodb.PhotoDB.closest_photodb(*args, **kwargs)
|
2023-02-04 21:49:42 +00:00
|
|
|
load_config()
|
|
|
|
|
|
|
|
def load_config() -> None:
|
|
|
|
log.debug('Loading server config file.')
|
|
|
|
config_file = P.data_directory.with_child(SERVER_CONFIG_FILENAME)
|
|
|
|
(config, needs_rewrite) = configlayers.load_file(
|
|
|
|
filepath=config_file,
|
|
|
|
default_config=DEFAULT_SERVER_CONFIG,
|
|
|
|
)
|
|
|
|
site.server_config = config
|
|
|
|
|
|
|
|
if needs_rewrite:
|
|
|
|
save_config()
|
|
|
|
|
|
|
|
def save_config() -> None:
|
|
|
|
log.debug('Saving server config file.')
|
|
|
|
config_file = P.data_directory.with_child(SERVER_CONFIG_FILENAME)
|
|
|
|
with config_file.open('w', encoding='utf-8') as handle:
|
|
|
|
handle.write(json.dumps(site.server_config, indent=4, sort_keys=True))
|