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.

183 lines
6.5 KiB

  1. # maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from functools import partial
  17. from io import BytesIO
  18. import os.path
  19. import json
  20. import tempfile
  21. import mimetypes
  22. try:
  23. import magic
  24. except ImportError:
  25. print("[Warning] Magic is not installed, using file extensions to guess mime types")
  26. magic = None
  27. from PIL import Image, ImageSequence
  28. from . import matrix
  29. open_utf8 = partial(open, encoding='UTF-8')
  30. def guess_mime(data: bytes) -> str:
  31. mime = None
  32. if magic:
  33. try:
  34. return magic.Magic(mime=True).from_buffer(data)
  35. except Exception:
  36. pass
  37. else:
  38. with tempfile.NamedTemporaryFile(delete=False) as temp:
  39. temp.write(data)
  40. temp.close()
  41. mime, _ = mimetypes.guess_type(temp.name)
  42. return mime or "image/png"
  43. def video_to_gif(data: bytes, mime: str) -> bytes:
  44. from moviepy.editor import VideoFileClip
  45. ext = mimetypes.guess_extension(mime)
  46. with tempfile.NamedTemporaryFile(suffix=ext) as temp:
  47. temp.write(data)
  48. temp.flush()
  49. with tempfile.NamedTemporaryFile(suffix=".gif") as gif:
  50. clip = VideoFileClip(temp.name)
  51. clip.write_gif(gif.name, logger=None)
  52. gif.seek(0)
  53. return gif.read()
  54. def _convert_image(data: bytes, mimetype: str) -> (bytes, int, int):
  55. image: Image.Image = Image.open(BytesIO(data))
  56. new_file = BytesIO()
  57. suffix = mimetypes.guess_extension(mimetype)
  58. if suffix:
  59. suffix = suffix[1:]
  60. # Determine if the image is a GIF
  61. is_animated = getattr(image, "is_animated", False)
  62. if is_animated:
  63. frames = [frame.convert("RGBA") for frame in ImageSequence.Iterator(image)]
  64. # Save the new GIF
  65. frames[0].save(
  66. new_file,
  67. format='GIF',
  68. save_all=True,
  69. append_images=frames[1:],
  70. loop=image.info.get('loop', 0), # Default loop to 0 if not present
  71. duration=image.info.get('duration', 100), # Set a default duration if not present
  72. transparency=image.info.get('transparency', 255), # Default to 255 if transparency is not present
  73. disposal=image.info.get('disposal', 2) # Default to disposal method 2 (restore to background)
  74. )
  75. # Get the size of the first frame to determine resizing
  76. w, h = frames[0].size
  77. else:
  78. image = image.convert("RGBA")
  79. image.save(new_file, format=suffix)
  80. w, h = image.size
  81. if w > 256 or h > 256:
  82. # Set the width and height to lower values so clients wouldn't show them as huge images
  83. if w > h:
  84. h = int(h / (w / 256))
  85. w = 256
  86. else:
  87. w = int(w / (h / 256))
  88. h = 256
  89. return new_file.getvalue(), w, h
  90. def _convert_sticker(data: bytes) -> (bytes, str, int, int):
  91. mimetype = guess_mime(data)
  92. if mimetype.startswith("video/"):
  93. data = video_to_gif(data, mimetype)
  94. print(".", end="", flush=True)
  95. mimetype = "image/gif"
  96. elif mimetype.startswith("application/gzip"):
  97. print(".", end="", flush=True)
  98. # unzip file
  99. import gzip
  100. with gzip.open(BytesIO(data), "rb") as f:
  101. data = f.read()
  102. mimetype = guess_mime(data)
  103. suffix = mimetypes.guess_extension(mimetype)
  104. with tempfile.NamedTemporaryFile(suffix=suffix) as temp:
  105. temp.write(data)
  106. with tempfile.NamedTemporaryFile(suffix=".gif") as gif:
  107. # run lottie_convert.py input output
  108. print(".", end="", flush=True)
  109. import subprocess
  110. cmd = ["lottie_convert.py", temp.name, gif.name]
  111. result = subprocess.run(cmd, capture_output=True, text=True)
  112. if result.returncode != 0:
  113. raise RuntimeError(f"Run {cmd} failed with code {retcode}, Error occurred:\n{result.stderr}")
  114. gif.seek(0)
  115. data = gif.read()
  116. mimetype = "image/gif"
  117. rlt = _convert_image(data, mimetype)
  118. suffix = mimetypes.guess_extension(mimetype)
  119. return rlt[0], mimetype, rlt[1], rlt[2]
  120. def convert_sticker(data: bytes) -> (bytes, str, int, int):
  121. try:
  122. return _convert_sticker(data)
  123. except Exception as e:
  124. mimetype = guess_mime(data)
  125. print(f"Error converting image, mimetype: {mimetype}")
  126. ext = mimetypes.guess_extension(mimetype)
  127. with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp:
  128. temp.write(data)
  129. print(f"Saved to {temp.name}")
  130. raise e
  131. def add_to_index(name: str, output_dir: str) -> None:
  132. index_path = os.path.join(output_dir, "index.json")
  133. try:
  134. with open_utf8(index_path) as index_file:
  135. index_data = json.load(index_file)
  136. except (FileNotFoundError, json.JSONDecodeError):
  137. index_data = {"packs": []}
  138. if "homeserver_url" not in index_data and matrix.homeserver_url:
  139. index_data["homeserver_url"] = matrix.homeserver_url
  140. if name not in index_data["packs"]:
  141. index_data["packs"].append(name)
  142. with open_utf8(index_path, "w") as index_file:
  143. json.dump(index_data, index_file, indent=" ")
  144. print(f"Added {name} to {index_path}")
  145. def make_sticker(mxc: str, width: int, height: int, size: int,
  146. mimetype: str, body: str = "") -> matrix.StickerInfo:
  147. return {
  148. "body": body,
  149. "url": mxc,
  150. "info": {
  151. "w": width,
  152. "h": height,
  153. "size": size,
  154. "mimetype": mimetype,
  155. # Element iOS compatibility hack
  156. "thumbnail_url": mxc,
  157. "thumbnail_info": {
  158. "w": width,
  159. "h": height,
  160. "size": size,
  161. "mimetype": mimetype,
  162. },
  163. },
  164. "msgtype": "m.sticker",
  165. }