2019-06-28 07:24:28 +02:00
|
|
|
from contextlib import contextmanager
|
|
|
|
|
|
|
|
from ..core.config import config
|
|
|
|
from .models import Mediafile
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def watch_and_update_configs():
|
|
|
|
"""
|
|
|
|
Watches each font and logo config for changes. If some mediafiles were updated
|
|
|
|
(also their parents, so some path changes) or were deleted, all affected configs
|
|
|
|
are updated.
|
|
|
|
"""
|
|
|
|
# 1) map logo and font config keys to mediafile ids
|
2019-11-04 14:56:01 +01:00
|
|
|
mediafiles = Mediafile.objects.get_prefetched_queryset().all()
|
2019-06-28 07:24:28 +02:00
|
|
|
logos = build_mapping("logos_available", mediafiles)
|
|
|
|
fonts = build_mapping("fonts_available", mediafiles)
|
|
|
|
yield
|
|
|
|
# 2) update changed paths/urls
|
2019-11-04 14:56:01 +01:00
|
|
|
mediafiles = Mediafile.objects.get_prefetched_queryset().all()
|
2019-06-28 07:24:28 +02:00
|
|
|
update_mapping(logos, mediafiles)
|
|
|
|
update_mapping(fonts, mediafiles)
|
|
|
|
|
|
|
|
|
|
|
|
def build_mapping(base_config_key, mediafiles):
|
2021-06-21 07:46:13 +02:00
|
|
|
"""Returns a map of config keys to mediafile ids"""
|
|
|
|
mapping = {}
|
2019-06-28 07:24:28 +02:00
|
|
|
for key in config[base_config_key]:
|
|
|
|
url = config[key]["path"]
|
|
|
|
|
|
|
|
for mediafile in mediafiles:
|
|
|
|
if mediafile.url == url:
|
2021-06-21 07:46:13 +02:00
|
|
|
mapping[key] = mediafile.id
|
2019-06-28 07:24:28 +02:00
|
|
|
break
|
2021-06-21 07:46:13 +02:00
|
|
|
return mapping
|
2019-06-28 07:24:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
def update_mapping(mapping, mediafiles):
|
|
|
|
"""
|
|
|
|
Tries to get the mediafile from the id for a specific config field.
|
|
|
|
If the file was found and the path changed, the config is updated. If the
|
2021-06-21 07:46:13 +02:00
|
|
|
mediafile could not be found, the config is cleared (mediafile deleted).
|
2019-06-28 07:24:28 +02:00
|
|
|
"""
|
|
|
|
for key, id in mapping.items():
|
2021-06-21 07:46:13 +02:00
|
|
|
config_value = config[key]
|
2019-06-28 07:24:28 +02:00
|
|
|
try:
|
|
|
|
mediafile = mediafiles.filter(pk=id)[0]
|
2021-06-21 07:46:13 +02:00
|
|
|
if config_value["path"] != mediafile.url:
|
|
|
|
config_value["path"] = mediafile.url
|
|
|
|
config[key] = config_value
|
2019-06-28 07:24:28 +02:00
|
|
|
except IndexError:
|
2021-06-21 07:46:13 +02:00
|
|
|
config_value["path"] = ""
|
|
|
|
config[key] = config_value
|