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.

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