1
0

utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import os.path
  2. import random
  3. import re
  4. import string
  5. from django.conf import settings
  6. from django.template.defaultfilters import slugify
  7. from django.utils.encoding import force_str
  8. from django.utils.module_loading import import_string
  9. # Non-image file icons, matched from top to bottom
  10. fileicons_path = "{}/file-icons/".format(
  11. getattr(settings, "CKEDITOR_FILEICONS_PATH", "/static/ckeditor")
  12. )
  13. # This allows adding or overriding the default icons used by Gallerific by getting an additional two-tuple list from
  14. # the project settings. If it does not exist, it is ignored. If the same file extension exists twice, the settings
  15. # file version is used instead of the default.
  16. override_icons = getattr(settings, "CKEDITOR_FILEICONS", [])
  17. ckeditor_icons = [
  18. (r"\.pdf$", fileicons_path + "pdf.png"),
  19. (r"\.doc$|\.docx$|\.odt$", fileicons_path + "doc.png"),
  20. (r"\.txt$", fileicons_path + "txt.png"),
  21. (r"\.ppt$", fileicons_path + "ppt.png"),
  22. (r"\.xls$", fileicons_path + "xls.png"),
  23. (".*", fileicons_path + "file.png"), # Default
  24. ]
  25. CKEDITOR_FILEICONS = override_icons + ckeditor_icons
  26. IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif"}
  27. # Allow for a custom storage backend defined in settings.
  28. def get_storage_class():
  29. return import_string(
  30. getattr(
  31. settings,
  32. "CKEDITOR_STORAGE_BACKEND",
  33. "django.core.files.storage.DefaultStorage",
  34. )
  35. )()
  36. storage = get_storage_class()
  37. def slugify_filename(filename):
  38. """Slugify filename"""
  39. name, ext = os.path.splitext(filename)
  40. slugified = get_slugified_name(name)
  41. return slugified + ext
  42. def get_slugified_name(filename):
  43. slugified = slugify(filename)
  44. return slugified or get_random_string()
  45. def get_random_string():
  46. return "".join(random.sample(string.ascii_lowercase * 6, 6))
  47. def get_icon_filename(file_name):
  48. """
  49. Return the path to a file icon that matches the file name.
  50. """
  51. for regex, iconpath in CKEDITOR_FILEICONS:
  52. if re.search(regex, file_name, re.I):
  53. return iconpath
  54. def get_thumb_filename(file_name):
  55. """
  56. Generate thumb filename by adding _thumb to end of
  57. filename before . (if present)
  58. """
  59. return force_str("{0}_thumb{1}").format(*os.path.splitext(file_name))
  60. def get_media_url(path):
  61. """
  62. Determine system file's media URL.
  63. """
  64. return storage.url(path)
  65. def is_valid_image_extension(file_path):
  66. extension = os.path.splitext(file_path.lower())[1]
  67. return extension in IMAGE_EXTENSIONS