You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.6 KiB

  1. # Copyright (c) 2019 Tildes contributors <code@tildes.net>
  2. # SPDX-License-Identifier: AGPL-3.0-or-later
  3. """Script to generate CSS related to site icons based on which have been downloaded."""
  4. import os
  5. import shutil
  6. import stat
  7. from tempfile import NamedTemporaryFile
  8. ICON_FOLDER = "/opt/tildes/static/images/site-icons"
  9. OUTPUT_FILE = "/opt/tildes/static/css/site-icons.css"
  10. CSS_RULE = """
  11. .topic-icon-{domain} {{
  12. background-image: url('/images/site-icons/{filename}');
  13. }}
  14. """
  15. def _is_output_file_outdated() -> bool:
  16. """Return whether the output file needs an update yet."""
  17. # check if any icon files have a modified time higher than the output file's
  18. try:
  19. output_file_modified = os.stat(OUTPUT_FILE).st_mtime
  20. except FileNotFoundError:
  21. return True
  22. for entry in os.scandir(ICON_FOLDER):
  23. if entry.stat().st_mtime > output_file_modified:
  24. return True
  25. return False
  26. def generate_css() -> None:
  27. """Generate the CSS file for site icons and replace the old one."""
  28. if not _is_output_file_outdated():
  29. return
  30. with NamedTemporaryFile(mode="w") as temp_file:
  31. for filename in os.listdir(ICON_FOLDER):
  32. split_filename = filename.split(".")
  33. if len(split_filename) < 2 or split_filename[1] != "png":
  34. continue
  35. temp_file.write(
  36. CSS_RULE.format(domain=split_filename[0], filename=filename)
  37. )
  38. temp_file.flush()
  39. shutil.copy(temp_file.name, OUTPUT_FILE)
  40. # set file permissions to 644 (rw-r--r--)
  41. os.chmod(OUTPUT_FILE, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)