1
0
mirror of https://github.com/spl0k/supysonic.git synced 2024-11-12 21:22:17 +00:00
supysonic/supysonic/web.py

97 lines
3.0 KiB
Python
Raw Normal View History

# This file is part of Supysonic.
2014-03-02 17:31:32 +00:00
# Supysonic is a Python implementation of the Subsonic server API.
#
# Copyright (C) 2013-2023 Alban 'spl0k' Féron
2019-02-09 15:19:30 +00:00
# 2018-2019 Carey 'pR0Ps' Metcalfe
2017-08-07 07:47:39 +00:00
# 2017 Óscar García Amor
2014-03-02 17:31:32 +00:00
#
# Distributed under terms of the GNU AGPLv3 license.
2014-03-02 17:31:32 +00:00
import logging
2017-11-27 21:30:13 +00:00
import mimetypes
2017-12-19 22:16:55 +00:00
from flask import Flask
2023-03-05 12:07:19 +00:00
from logging.handlers import TimedRotatingFileHandler
from os import makedirs, path
2012-10-13 09:29:48 +00:00
2017-12-11 18:46:51 +00:00
from .config import IniConfig
Implement a cache manager for album art and transcodes Quick summary ------------- - Adds a Cache class (plus tests for it) that provides an API for managing a cache of files on disk - Adds two new settings to the configuration file: `cache_size` (default 512MB) and `transcode_cache_size` (default 1GB). - Creates two cache managers using the settings above: one for general stuff (currently album art) and one for transcodes - Adds the caching of transcoded files to disk for future use - Modifies the existing image caching to use the cache manager Longer explanations and justifications -------------------------------------- The reason I separated out transcodes into an entirely separate cache is that I could imagine a single transcode pushing out a ton of smaller images or other cached content. By separating them it should reduce the number of deletes caused by adding something to the cache. The cache manager allows for caching a value from a generator via passthrough. This means that a generator can be transparently wrapped to save its output in the cache. The bytes from the generator will be written to a temp file in the cache and yielded back. When it completes, the temp file will be renamed according to the provided cache key. This is how caching transcoded music is implemented. If multiple generators for the same key are started, they will all write to individual temp files until they complete and race to overwrite each other. Since the key should uniquely represent the content it indexes the files will be identical so overwriting them is harmless. The cache will store everything for a minimum amount of time (configurable, default is set at 5 minutes). After this time has elapsed, the data can be deleted to free up space. This minimum is so that when you cache a file to the disk you can expect it to be there after, even if another large file is added to the cache and requests that some files are deleted to make space. To ensure that a file will not be paged out of the cache regardless of the minimum time, there is a `protect` context manager that will refuse the delete the key from the cache as long as it's active. The cache has a maximum size, however this is more of a recommendation as opposed to a hard limit. The actual size will frequently exceed the limit temporarily until something can be paged out.
2019-01-14 06:46:21 +00:00
from .cache import Cache
from .db import init_database, open_connection, close_connection
from .utils import get_secret_key
2012-10-13 09:29:48 +00:00
logger = logging.getLogger(__package__)
2019-06-29 15:25:44 +00:00
def create_application(config=None):
global app
2014-03-03 20:43:06 +00:00
2017-08-07 07:47:39 +00:00
# Flask!
app = Flask(__name__)
2019-06-29 15:25:44 +00:00
app.config.from_object("supysonic.config.DefaultConfig")
2014-03-03 20:43:06 +00:00
2019-06-29 15:25:44 +00:00
if not config: # pragma: nocover
2017-11-27 21:30:13 +00:00
config = IniConfig.from_common_locations()
app.config.from_object(config)
2014-03-16 17:51:19 +00:00
2017-08-07 07:47:39 +00:00
# Set loglevel
2019-06-29 15:25:44 +00:00
logfile = app.config["WEBAPP"]["log_file"]
if logfile: # pragma: nocover
2023-03-05 12:07:19 +00:00
if app.config["WEBAPP"]["log_rotate"]:
handler = TimedRotatingFileHandler(logfile, when="midnight")
else:
handler = logging.FileHandler(logfile)
2019-06-29 15:25:44 +00:00
handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
)
logger.addHandler(handler)
2019-06-29 15:25:44 +00:00
loglevel = app.config["WEBAPP"]["log_level"]
if loglevel:
logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET))
2014-03-03 20:43:06 +00:00
2017-12-19 22:16:55 +00:00
# Initialize database
2019-06-29 15:25:44 +00:00
init_database(app.config["BASE"]["database_uri"])
if not app.testing:
def open_conn(): # Just to discard the return value
open_connection()
app.before_request(open_conn)
app.teardown_request(lambda exc: close_connection())
2017-12-19 22:16:55 +00:00
2017-11-27 21:30:13 +00:00
# Insert unknown mimetypes
2019-06-29 15:25:44 +00:00
for k, v in app.config["MIMETYPES"].items():
extension = "." + k.lower()
2017-11-27 21:30:13 +00:00
if extension not in mimetypes.types_map:
mimetypes.add_type(v, extension, False)
Implement a cache manager for album art and transcodes Quick summary ------------- - Adds a Cache class (plus tests for it) that provides an API for managing a cache of files on disk - Adds two new settings to the configuration file: `cache_size` (default 512MB) and `transcode_cache_size` (default 1GB). - Creates two cache managers using the settings above: one for general stuff (currently album art) and one for transcodes - Adds the caching of transcoded files to disk for future use - Modifies the existing image caching to use the cache manager Longer explanations and justifications -------------------------------------- The reason I separated out transcodes into an entirely separate cache is that I could imagine a single transcode pushing out a ton of smaller images or other cached content. By separating them it should reduce the number of deletes caused by adding something to the cache. The cache manager allows for caching a value from a generator via passthrough. This means that a generator can be transparently wrapped to save its output in the cache. The bytes from the generator will be written to a temp file in the cache and yielded back. When it completes, the temp file will be renamed according to the provided cache key. This is how caching transcoded music is implemented. If multiple generators for the same key are started, they will all write to individual temp files until they complete and race to overwrite each other. Since the key should uniquely represent the content it indexes the files will be identical so overwriting them is harmless. The cache will store everything for a minimum amount of time (configurable, default is set at 5 minutes). After this time has elapsed, the data can be deleted to free up space. This minimum is so that when you cache a file to the disk you can expect it to be there after, even if another large file is added to the cache and requests that some files are deleted to make space. To ensure that a file will not be paged out of the cache regardless of the minimum time, there is a `protect` context manager that will refuse the delete the key from the cache as long as it's active. The cache has a maximum size, however this is more of a recommendation as opposed to a hard limit. The actual size will frequently exceed the limit temporarily until something can be paged out.
2019-01-14 06:46:21 +00:00
# Initialize Cache objects
# Max size is MB in the config file but Cache expects bytes
2019-06-29 15:25:44 +00:00
cache_dir = app.config["WEBAPP"]["cache_dir"]
2022-12-10 14:48:06 +00:00
max_size_cache = app.config["WEBAPP"]["cache_size"] * 1024**2
max_size_transcodes = app.config["WEBAPP"]["transcode_cache_size"] * 1024**2
Implement a cache manager for album art and transcodes Quick summary ------------- - Adds a Cache class (plus tests for it) that provides an API for managing a cache of files on disk - Adds two new settings to the configuration file: `cache_size` (default 512MB) and `transcode_cache_size` (default 1GB). - Creates two cache managers using the settings above: one for general stuff (currently album art) and one for transcodes - Adds the caching of transcoded files to disk for future use - Modifies the existing image caching to use the cache manager Longer explanations and justifications -------------------------------------- The reason I separated out transcodes into an entirely separate cache is that I could imagine a single transcode pushing out a ton of smaller images or other cached content. By separating them it should reduce the number of deletes caused by adding something to the cache. The cache manager allows for caching a value from a generator via passthrough. This means that a generator can be transparently wrapped to save its output in the cache. The bytes from the generator will be written to a temp file in the cache and yielded back. When it completes, the temp file will be renamed according to the provided cache key. This is how caching transcoded music is implemented. If multiple generators for the same key are started, they will all write to individual temp files until they complete and race to overwrite each other. Since the key should uniquely represent the content it indexes the files will be identical so overwriting them is harmless. The cache will store everything for a minimum amount of time (configurable, default is set at 5 minutes). After this time has elapsed, the data can be deleted to free up space. This minimum is so that when you cache a file to the disk you can expect it to be there after, even if another large file is added to the cache and requests that some files are deleted to make space. To ensure that a file will not be paged out of the cache regardless of the minimum time, there is a `protect` context manager that will refuse the delete the key from the cache as long as it's active. The cache has a maximum size, however this is more of a recommendation as opposed to a hard limit. The actual size will frequently exceed the limit temporarily until something can be paged out.
2019-01-14 06:46:21 +00:00
app.cache = Cache(path.join(cache_dir, "cache"), max_size_cache)
app.transcode_cache = Cache(path.join(cache_dir, "transcodes"), max_size_transcodes)
2017-11-27 21:30:13 +00:00
# Test for the cache directory
2019-06-29 15:25:44 +00:00
cache_path = app.config["WEBAPP"]["cache_dir"]
2017-11-27 21:30:13 +00:00
if not path.exists(cache_path):
2019-06-29 15:25:44 +00:00
makedirs(cache_path) # pragma: nocover
2018-04-01 10:32:36 +00:00
# Read or create secret key
2019-06-29 15:25:44 +00:00
app.secret_key = get_secret_key("cookies_secret")
2017-11-27 21:30:13 +00:00
2017-08-07 07:47:39 +00:00
# Import app sections
2019-06-29 15:25:44 +00:00
if app.config["WEBAPP"]["mount_webui"]:
from .frontend import frontend
2019-06-29 15:25:44 +00:00
app.register_blueprint(frontend)
2019-06-29 15:25:44 +00:00
if app.config["WEBAPP"]["mount_api"]:
from .api import api
2014-03-03 20:43:06 +00:00
2019-06-29 15:25:44 +00:00
app.register_blueprint(api, url_prefix="/rest")
2017-11-27 21:30:13 +00:00
if not app.testing:
close_connection()
2019-06-29 15:25:44 +00:00
return app