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.

67 lines
2.0 KiB

  1. # Copyright (c) 2020 Tulir Asokan
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. from io import BytesIO
  7. import os.path
  8. import json
  9. from PIL import Image
  10. from . import matrix
  11. def convert_image(data: bytes) -> (bytes, int, int):
  12. image: Image.Image = Image.open(BytesIO(data)).convert("RGBA")
  13. new_file = BytesIO()
  14. image.save(new_file, "png")
  15. w, h = image.size
  16. if w > 256 or h > 256:
  17. # Set the width and height to lower values so clients wouldn't show them as huge images
  18. if w > h:
  19. h = int(h / (w / 256))
  20. w = 256
  21. else:
  22. w = int(w / (h / 256))
  23. h = 256
  24. return new_file.getvalue(), w, h
  25. def add_to_index(name: str, output_dir: str) -> None:
  26. index_path = os.path.join(output_dir, "index.json")
  27. try:
  28. with open(index_path) as index_file:
  29. index_data = json.load(index_file)
  30. except (FileNotFoundError, json.JSONDecodeError):
  31. index_data = {"packs": []}
  32. if "homeserver_url" not in index_data and matrix.homeserver_url:
  33. index_data["homeserver_url"] = matrix.homeserver_url
  34. if name not in index_data["packs"]:
  35. index_data["packs"].append(name)
  36. with open(index_path, "w") as index_file:
  37. json.dump(index_data, index_file, indent=" ")
  38. print(f"Added {name} to {index_path}")
  39. def make_sticker(mxc: str, width: int, height: int, size: int,
  40. body: str = "") -> matrix.StickerInfo:
  41. return {
  42. "body": body,
  43. "url": mxc,
  44. "info": {
  45. "w": width,
  46. "h": height,
  47. "size": size,
  48. "mimetype": "image/png",
  49. # Element iOS compatibility hack
  50. "thumbnail_url": mxc,
  51. "thumbnail_info": {
  52. "w": width,
  53. "h": height,
  54. "size": size,
  55. "mimetype": "image/png",
  56. },
  57. },
  58. }