importer.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import json
  2. import os
  3. from tempfile import TemporaryDirectory
  4. from zipfile import BadZipFile, ZipFile
  5. from django.core.files.uploadedfile import UploadedFile
  6. from django.utils.translation import gettext as _, gettext_lazy
  7. from ..models import Theme
  8. from .css import create_css
  9. from .forms import (
  10. ThemeCssUrlManifest,
  11. ThemeManifest,
  12. create_css_file_manifest,
  13. create_media_file_manifest,
  14. )
  15. from .media import create_media
  16. from .tasks import build_theme_css, update_remote_css_size
  17. INVALID_MANIFEST_ERROR = gettext_lazy(
  18. '"manifest.json" contained by ZIP file is not a valid theme manifest file.'
  19. )
  20. class ThemeImportError(BaseException):
  21. pass
  22. class InvalidThemeManifest(ThemeImportError):
  23. def __init__(self):
  24. super().__init__(INVALID_MANIFEST_ERROR)
  25. def import_theme(name, parent, zipfile):
  26. with TemporaryDirectory() as tmp_dir:
  27. extract_zipfile_to_tmp_dir(zipfile, tmp_dir)
  28. validate_zipfile_contains_single_directory(tmp_dir)
  29. theme_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0])
  30. cleaned_manifest = clean_theme_contents(theme_dir)
  31. theme = create_theme_from_manifest(name, parent, cleaned_manifest)
  32. try:
  33. create_css_from_manifest(theme_dir, theme, cleaned_manifest["css"])
  34. create_media_from_manifest(theme_dir, theme, cleaned_manifest["media"])
  35. except Exception as e:
  36. print(e)
  37. theme.delete()
  38. raise InvalidThemeManifest()
  39. else:
  40. for css in theme.css.filter(url__isnull=False):
  41. update_remote_css_size.delay(css.pk)
  42. build_theme_css.delay(theme.pk)
  43. return theme
  44. def extract_zipfile_to_tmp_dir(zipfile, tmp_dir):
  45. try:
  46. ZipFile(zipfile).extractall(tmp_dir)
  47. except BadZipFile:
  48. raise ThemeImportError(_("Uploaded ZIP file could not be extracted."))
  49. def validate_zipfile_contains_single_directory(tmp_dir):
  50. dir_contents = os.listdir(tmp_dir)
  51. if not dir_contents:
  52. raise ThemeImportError(_("Uploaded ZIP file is empty."))
  53. if len(dir_contents) > 1:
  54. raise ThemeImportError(_("Uploaded ZIP file should contain single directory."))
  55. if not os.path.isdir(os.path.join(tmp_dir, dir_contents[0])):
  56. raise ThemeImportError(_("Uploaded ZIP file didn't contain a directory."))
  57. def clean_theme_contents(theme_dir):
  58. manifest = read_manifest(theme_dir)
  59. return clean_manifest(theme_dir, manifest)
  60. def read_manifest(theme_dir):
  61. try:
  62. with open(os.path.join(theme_dir, "manifest.json")) as fp:
  63. return json.load(fp)
  64. except FileNotFoundError:
  65. raise ThemeImportError(
  66. _('Uploaded ZIP file didn\'t contain a "manifest.json".')
  67. )
  68. except json.decoder.JSONDecodeError:
  69. raise ThemeImportError(
  70. _('"manifest.json" contained by ZIP file is not a valid JSON file.')
  71. )
  72. def clean_manifest(theme_dir, manifest):
  73. if not isinstance(manifest, dict):
  74. raise InvalidThemeManifest()
  75. form = ThemeManifest(manifest)
  76. if not form.is_valid():
  77. raise InvalidThemeManifest()
  78. cleaned_manifest = form.cleaned_data.copy()
  79. cleaned_manifest["css"] = clean_css_list(theme_dir, manifest.get("css"))
  80. cleaned_manifest["media"] = clean_media_list(theme_dir, manifest.get("media"))
  81. return cleaned_manifest
  82. def clean_css_list(theme_dir, manifest):
  83. if not isinstance(manifest, list):
  84. raise InvalidThemeManifest()
  85. theme_css_dir = os.path.join(theme_dir, "css")
  86. if not os.path.isdir(theme_css_dir):
  87. raise InvalidThemeManifest()
  88. cleaned_data = []
  89. for item in manifest:
  90. cleaned_data.append(clean_css_list_item(theme_css_dir, item))
  91. return cleaned_data
  92. def clean_css_list_item(theme_css_dir, item):
  93. if not isinstance(item, dict):
  94. raise InvalidThemeManifest()
  95. if item.get("url"):
  96. return clean_css_url(item)
  97. if item.get("path"):
  98. return clean_css_file(theme_css_dir, item)
  99. raise InvalidThemeManifest()
  100. def clean_css_url(data):
  101. form = ThemeCssUrlManifest(data)
  102. if not form.is_valid():
  103. raise InvalidThemeManifest()
  104. return form.cleaned_data
  105. def clean_css_file(theme_css_dir, data):
  106. file_manifest = create_css_file_manifest(theme_css_dir)
  107. if data.get("path"):
  108. data["path"] = os.path.join(theme_css_dir, str(data["path"]))
  109. form = file_manifest(data)
  110. if not form.is_valid():
  111. raise InvalidThemeManifest()
  112. return form.cleaned_data
  113. def clean_media_list(theme_dir, manifest):
  114. if not isinstance(manifest, list):
  115. raise InvalidThemeManifest()
  116. theme_media_dir = os.path.join(theme_dir, "media")
  117. if not os.path.isdir(theme_media_dir):
  118. raise InvalidThemeManifest()
  119. cleaned_data = []
  120. for item in manifest:
  121. cleaned_data.append(clean_media_list_item(theme_media_dir, item))
  122. return cleaned_data
  123. def clean_media_list_item(theme_media_dir, data):
  124. if not isinstance(data, dict):
  125. raise InvalidThemeManifest()
  126. file_manifest = create_media_file_manifest(theme_media_dir)
  127. if data.get("path"):
  128. data["path"] = os.path.join(theme_media_dir, str(data["path"]))
  129. form = file_manifest(data)
  130. if not form.is_valid():
  131. raise InvalidThemeManifest()
  132. return form.cleaned_data
  133. def create_theme_from_manifest(name, parent, cleaned_data):
  134. return Theme.objects.create(
  135. name=name or cleaned_data["name"],
  136. parent=parent,
  137. version=cleaned_data.get("version") or None,
  138. author=cleaned_data.get("author") or None,
  139. url=cleaned_data.get("url") or None,
  140. )
  141. def create_css_from_manifest(tmp_dir, theme, manifest):
  142. for item in manifest:
  143. if "url" in item:
  144. theme.css.create(**item, order=theme.css.count())
  145. else:
  146. with open(item["path"], "rb") as fp:
  147. file_obj = UploadedFile(
  148. fp,
  149. name=item["name"],
  150. content_type="text/css",
  151. size=os.path.getsize(item["path"]),
  152. )
  153. create_css(theme, file_obj)
  154. def create_media_from_manifest(tmp_dir, theme, manifest):
  155. for item in manifest:
  156. with open(item["path"], "rb") as fp:
  157. file_obj = UploadedFile(
  158. fp,
  159. name=item["name"],
  160. content_type=item["type"],
  161. size=os.path.getsize(item["path"]),
  162. )
  163. create_media(theme, file_obj)