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.

77 lines
2.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 io import BytesIO
  17. import os.path
  18. import json
  19. from PIL import Image
  20. from . import matrix
  21. def convert_image(data: bytes) -> (bytes, int, int):
  22. image: Image.Image = Image.open(BytesIO(data)).convert("RGBA")
  23. new_file = BytesIO()
  24. image.save(new_file, "png")
  25. w, h = image.size
  26. if w > 256 or h > 256:
  27. # Set the width and height to lower values so clients wouldn't show them as huge images
  28. if w > h:
  29. h = int(h / (w / 256))
  30. w = 256
  31. else:
  32. w = int(w / (h / 256))
  33. h = 256
  34. return new_file.getvalue(), w, h
  35. def add_to_index(name: str, output_dir: str) -> None:
  36. index_path = os.path.join(output_dir, "index.json")
  37. try:
  38. with open(index_path) as index_file:
  39. index_data = json.load(index_file)
  40. except (FileNotFoundError, json.JSONDecodeError):
  41. index_data = {"packs": []}
  42. if "homeserver_url" not in index_data and matrix.homeserver_url:
  43. index_data["homeserver_url"] = matrix.homeserver_url
  44. if name not in index_data["packs"]:
  45. index_data["packs"].append(name)
  46. with open(index_path, "w") as index_file:
  47. json.dump(index_data, index_file, indent=" ")
  48. print(f"Added {name} to {index_path}")
  49. def make_sticker(mxc: str, width: int, height: int, size: int,
  50. body: str = "") -> matrix.StickerInfo:
  51. return {
  52. "body": body,
  53. "url": mxc,
  54. "info": {
  55. "w": width,
  56. "h": height,
  57. "size": size,
  58. "mimetype": "image/png",
  59. # Element iOS compatibility hack
  60. "thumbnail_url": mxc,
  61. "thumbnail_info": {
  62. "w": width,
  63. "h": height,
  64. "size": size,
  65. "mimetype": "image/png",
  66. },
  67. },
  68. }