TranslateSitePlugin.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import time
  2. from Plugin import PluginManager
  3. from Translate import translate
  4. @PluginManager.registerTo("UiRequest")
  5. class UiRequestPlugin(object):
  6. def actionSiteMedia(self, path, **kwargs):
  7. file_name = path.split("/")[-1].lower()
  8. if not file_name: # Path ends with /
  9. file_name = "index.html"
  10. extension = file_name.split(".")[-1]
  11. if extension == "html": # Always replace translate variables in html files
  12. should_translate = True
  13. elif extension == "js" and translate.lang != "en":
  14. should_translate = True
  15. else:
  16. should_translate = False
  17. if should_translate:
  18. path_parts = self.parsePath(path)
  19. kwargs["header_length"] = False
  20. file_generator = super(UiRequestPlugin, self).actionSiteMedia(path, **kwargs)
  21. if "__next__" in dir(file_generator): # File found and generator returned
  22. site = self.server.sites.get(path_parts["address"])
  23. if not site or not site.content_manager.contents.get("content.json"):
  24. return file_generator
  25. return self.actionPatchFile(site, path_parts["inner_path"], file_generator)
  26. else:
  27. return file_generator
  28. else:
  29. return super(UiRequestPlugin, self).actionSiteMedia(path, **kwargs)
  30. def actionUiMedia(self, path):
  31. file_generator = super(UiRequestPlugin, self).actionUiMedia(path)
  32. if translate.lang != "en" and path.endswith(".js"):
  33. s = time.time()
  34. data = b"".join(list(file_generator))
  35. data = translate.translateData(data.decode("utf8"))
  36. self.log.debug("Patched %s (%s bytes) in %.3fs" % (path, len(data), time.time() - s))
  37. return iter([data.encode("utf8")])
  38. else:
  39. return file_generator
  40. def actionPatchFile(self, site, inner_path, file_generator):
  41. content_json = site.content_manager.contents.get("content.json")
  42. lang_file = "languages/%s.json" % translate.lang
  43. lang_file_exist = False
  44. if site.settings.get("own"): # My site, check if the file is exist (allow to add new lang without signing)
  45. if site.storage.isFile(lang_file):
  46. lang_file_exist = True
  47. else: # Not my site the reference in content.json is enough (will wait for download later)
  48. if lang_file in content_json.get("files", {}):
  49. lang_file_exist = True
  50. if not lang_file_exist or inner_path not in content_json.get("translate", []):
  51. for part in file_generator:
  52. if inner_path.endswith(".html"):
  53. yield part.replace(b"lang={lang}", b"lang=" + translate.lang.encode("utf8")) # lang get parameter to .js file to avoid cache
  54. else:
  55. yield part
  56. else:
  57. s = time.time()
  58. data = b"".join(list(file_generator)).decode("utf8")
  59. # if site.content_manager.contents["content.json"]["files"].get(lang_file):
  60. site.needFile(lang_file, priority=10)
  61. try:
  62. if inner_path.endswith("js"):
  63. data = translate.translateData(data, site.storage.loadJson(lang_file), "js")
  64. else:
  65. data = translate.translateData(data, site.storage.loadJson(lang_file), "html")
  66. except Exception as err:
  67. site.log.error("Error loading translation file %s: %s" % (lang_file, err))
  68. self.log.debug("Patched %s (%s bytes) in %.3fs" % (inner_path, len(data), time.time() - s))
  69. yield data.encode("utf8")