2022-01-25 09:04:46 +00:00
|
|
|
"""Do further startup configuration and initialization"""
|
2022-01-25 08:22:13 +00:00
|
|
|
import os
|
|
|
|
import urllib
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from django.apps import AppConfig
|
|
|
|
|
|
|
|
from bookwyrm import settings
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2022-01-25 08:37:05 +00:00
|
|
|
|
2022-01-25 08:22:13 +00:00
|
|
|
def download_file(url, destination):
|
2022-01-25 09:04:46 +00:00
|
|
|
"""Downloads a file to the given path"""
|
2022-01-25 08:22:13 +00:00
|
|
|
try:
|
2022-02-02 05:45:13 +00:00
|
|
|
# Ensure our destination directory exists
|
|
|
|
os.makedirs(os.path.dirname(destination))
|
2022-01-25 09:04:46 +00:00
|
|
|
with urllib.request.urlopen(url) as stream:
|
|
|
|
with open(destination, "b+w") as outfile:
|
|
|
|
outfile.write(stream.read())
|
2022-01-25 08:22:13 +00:00
|
|
|
except (urllib.error.HTTPError, urllib.error.URLError):
|
|
|
|
logger.error("Failed to download file %s", url)
|
2022-02-02 05:45:13 +00:00
|
|
|
except OSError:
|
|
|
|
logger.error("Couldn't open font file %s for writing", destination)
|
2022-02-02 05:54:51 +00:00
|
|
|
except: # pylint: disable=bare-except
|
|
|
|
logger.exception("Unknown error in file download")
|
2022-01-25 08:22:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BookwyrmConfig(AppConfig):
|
2022-01-25 09:04:46 +00:00
|
|
|
"""Handles additional configuration"""
|
|
|
|
|
2022-01-25 08:22:13 +00:00
|
|
|
name = "bookwyrm"
|
|
|
|
verbose_name = "BookWyrm"
|
|
|
|
|
|
|
|
def ready(self):
|
|
|
|
if settings.ENABLE_PREVIEW_IMAGES and settings.FONTS:
|
|
|
|
# Download any fonts that we don't have yet
|
|
|
|
logger.debug("Downloading fonts..")
|
|
|
|
for name, config in settings.FONTS.items():
|
|
|
|
font_path = os.path.join(
|
|
|
|
settings.FONT_DIR, config["directory"], config["filename"]
|
|
|
|
)
|
|
|
|
|
|
|
|
if "url" in config and not os.path.exists(font_path):
|
|
|
|
logger.info("Just a sec, downloading %s", name)
|
|
|
|
download_file(config["url"], font_path)
|