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.

197 lines
7.3 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() 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. ext = mimetypes.guess_extension(mime)
  45. if mime.startswith("video/"):
  46. # run ffmpeg to fix duration
  47. with tempfile.NamedTemporaryFile(suffix=ext) as temp:
  48. temp.write(data)
  49. temp.flush()
  50. with tempfile.NamedTemporaryFile(suffix=ext) as temp_fixed:
  51. import subprocess
  52. print(".", end="", flush=True)
  53. result = subprocess.run(["ffmpeg", "-y", "-i", temp.name, "-codec", "copy", temp_fixed.name],
  54. capture_output=True)
  55. if result.returncode != 0:
  56. raise RuntimeError(f"Run ffmpeg failed with code {result.returncode}, Error occurred:\n{result.stderr}")
  57. temp_fixed.seek(0)
  58. data = temp_fixed.read()
  59. with tempfile.NamedTemporaryFile(suffix=ext) as temp:
  60. temp.write(data)
  61. temp.flush()
  62. with tempfile.NamedTemporaryFile(suffix=".gif") as gif:
  63. from moviepy.editor import VideoFileClip
  64. clip = VideoFileClip(temp.name)
  65. clip.write_gif(gif.name, logger=None)
  66. gif.seek(0)
  67. return gif.read()
  68. def _convert_image(data: bytes, mimetype: str) -> (bytes, int, int):
  69. image: Image.Image = Image.open(BytesIO(data))
  70. new_file = BytesIO()
  71. suffix = mimetypes.guess_extension(mimetype)
  72. if suffix:
  73. suffix = suffix[1:]
  74. # Determine if the image is a GIF
  75. is_animated = getattr(image, "is_animated", False)
  76. if is_animated:
  77. frames = [frame.convert("RGBA") for frame in ImageSequence.Iterator(image)]
  78. # Save the new GIF
  79. frames[0].save(
  80. new_file,
  81. format='GIF',
  82. save_all=True,
  83. append_images=frames[1:],
  84. loop=image.info.get('loop', 0), # Default loop to 0 if not present
  85. duration=image.info.get('duration', 100), # Set a default duration if not present
  86. transparency=image.info.get('transparency', 255), # Default to 255 if transparency is not present
  87. disposal=image.info.get('disposal', 2) # Default to disposal method 2 (restore to background)
  88. )
  89. # Get the size of the first frame to determine resizing
  90. w, h = frames[0].size
  91. else:
  92. image = image.convert("RGBA")
  93. image.save(new_file, format=suffix)
  94. w, h = image.size
  95. if w > 256 or h > 256:
  96. # Set the width and height to lower values so clients wouldn't show them as huge images
  97. if w > h:
  98. h = int(h / (w / 256))
  99. w = 256
  100. else:
  101. w = int(w / (h / 256))
  102. h = 256
  103. return new_file.getvalue(), w, h
  104. def _convert_sticker(data: bytes) -> (bytes, str, int, int):
  105. mimetype = guess_mime(data)
  106. if mimetype.startswith("video/"):
  107. data = video_to_gif(data, mimetype)
  108. print(".", end="", flush=True)
  109. mimetype = "image/gif"
  110. elif mimetype.startswith("application/gzip"):
  111. print(".", end="", flush=True)
  112. # unzip file
  113. import gzip
  114. with gzip.open(BytesIO(data), "rb") as f:
  115. data = f.read()
  116. mimetype = guess_mime(data)
  117. suffix = mimetypes.guess_extension(mimetype)
  118. with tempfile.NamedTemporaryFile(suffix=suffix) as temp:
  119. temp.write(data)
  120. with tempfile.NamedTemporaryFile(suffix=".gif") as gif:
  121. # run lottie_convert.py input output
  122. print(".", end="", flush=True)
  123. import subprocess
  124. cmd = ["lottie_convert.py", temp.name, gif.name]
  125. result = subprocess.run(cmd, capture_output=True, text=True)
  126. if result.returncode != 0:
  127. raise RuntimeError(f"Run {cmd} failed with code {retcode}, Error occurred:\n{result.stderr}")
  128. gif.seek(0)
  129. data = gif.read()
  130. mimetype = "image/gif"
  131. rlt = _convert_image(data, mimetype)
  132. suffix = mimetypes.guess_extension(mimetype)
  133. return rlt[0], mimetype, rlt[1], rlt[2]
  134. def convert_sticker(data: bytes) -> (bytes, str, int, int):
  135. try:
  136. return _convert_sticker(data)
  137. except Exception as e:
  138. mimetype = guess_mime(data)
  139. print(f"Error converting image, mimetype: {mimetype}")
  140. ext = mimetypes.guess_extension(mimetype)
  141. with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp:
  142. temp.write(data)
  143. print(f"Saved to {temp.name}")
  144. raise e
  145. def add_to_index(name: str, output_dir: str) -> None:
  146. index_path = os.path.join(output_dir, "index.json")
  147. try:
  148. with open_utf8(index_path) as index_file:
  149. index_data = json.load(index_file)
  150. except (FileNotFoundError, json.JSONDecodeError):
  151. index_data = {"packs": []}
  152. if "homeserver_url" not in index_data and matrix.homeserver_url:
  153. index_data["homeserver_url"] = matrix.homeserver_url
  154. if name not in index_data["packs"]:
  155. index_data["packs"].append(name)
  156. with open_utf8(index_path, "w") as index_file:
  157. json.dump(index_data, index_file, indent=" ")
  158. print(f"Added {name} to {index_path}")
  159. def make_sticker(mxc: str, width: int, height: int, size: int,
  160. mimetype: str, body: str = "") -> matrix.StickerInfo:
  161. return {
  162. "body": body,
  163. "url": mxc,
  164. "info": {
  165. "w": width,
  166. "h": height,
  167. "size": size,
  168. "mimetype": mimetype,
  169. # Element iOS compatibility hack
  170. "thumbnail_url": mxc,
  171. "thumbnail_info": {
  172. "w": width,
  173. "h": height,
  174. "size": size,
  175. "mimetype": mimetype,
  176. },
  177. },
  178. "msgtype": "m.sticker",
  179. }