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.

145 lines
5.0 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 typing import Dict, Optional
  17. from hashlib import sha256
  18. import mimetypes
  19. import argparse
  20. import os.path
  21. import asyncio
  22. import string
  23. import json
  24. try:
  25. import magic
  26. except ImportError:
  27. print("[Warning] Magic is not installed, using file extensions to guess mime types")
  28. magic = None
  29. from .lib import matrix, util
  30. def convert_name(name: str) -> str:
  31. name_translate = {
  32. ord(" "): ord("_"),
  33. }
  34. allowed_chars = string.ascii_letters + string.digits + "_-/.#"
  35. return "".join(filter(lambda char: char in allowed_chars, name.translate(name_translate)))
  36. async def upload_sticker(file: str, directory: str, old_stickers: Dict[str, matrix.StickerInfo]
  37. ) -> Optional[matrix.StickerInfo]:
  38. if file.startswith("."):
  39. return None
  40. path = os.path.join(directory, file)
  41. if not os.path.isfile(path):
  42. return None
  43. if magic:
  44. mime = magic.from_file(path, mime=True)
  45. else:
  46. mime, _ = mimetypes.guess_type(file)
  47. if not mime.startswith("image/"):
  48. return None
  49. print(f"Processing {file}", end="", flush=True)
  50. try:
  51. with open(path, "rb") as image_file:
  52. image_data = image_file.read()
  53. except Exception as e:
  54. print(f"... failed to read file: {e}")
  55. return None
  56. name = os.path.splitext(file)[0]
  57. # If the name starts with "number-", remove the prefix
  58. name_split = name.split("-", 1)
  59. if len(name_split) == 2 and name_split[0].isdecimal():
  60. name = name_split[1]
  61. sticker_id = f"sha256:{sha256(image_data).hexdigest()}"
  62. print(".", end="", flush=True)
  63. if sticker_id in old_stickers:
  64. sticker = {
  65. **old_stickers[sticker_id],
  66. "body": name,
  67. }
  68. print(f".. using existing upload")
  69. else:
  70. image_data, mimetype, width, height = util.convert_sticker(image_data)
  71. print(".", end="", flush=True)
  72. mxc = await matrix.upload(image_data, mimetype, file)
  73. print(".", end="", flush=True)
  74. sticker = util.make_sticker(mxc, width, height, len(image_data), mimetype, name)
  75. sticker["id"] = sticker_id
  76. print(" uploaded", flush=True)
  77. return sticker
  78. async def main(args: argparse.Namespace) -> None:
  79. await matrix.load_config(args.config)
  80. dirname = os.path.basename(os.path.abspath(args.path))
  81. meta_path = os.path.join(args.path, "pack.json")
  82. try:
  83. with util.open_utf8(meta_path) as pack_file:
  84. pack = json.load(pack_file)
  85. print(f"Loaded existing pack meta from {meta_path}")
  86. except FileNotFoundError:
  87. pack = {
  88. "title": args.title or dirname,
  89. "id": args.id or convert_name(dirname),
  90. "stickers": [],
  91. }
  92. old_stickers = {}
  93. else:
  94. old_stickers = {sticker["id"]: sticker for sticker in pack["stickers"]}
  95. pack["stickers"] = []
  96. for file in sorted(os.listdir(args.path)):
  97. sticker = await upload_sticker(file, args.path, old_stickers=old_stickers)
  98. if sticker:
  99. pack["stickers"].append(sticker)
  100. with util.open_utf8(meta_path, "w") as pack_file:
  101. json.dump(pack, pack_file)
  102. print(f"Wrote pack to {meta_path}")
  103. if args.add_to_index:
  104. picker_file_name = f"{pack['id']}.json"
  105. picker_pack_path = os.path.join(args.add_to_index, picker_file_name)
  106. with util.open_utf8(picker_pack_path, "w") as pack_file:
  107. json.dump(pack, pack_file)
  108. print(f"Copied pack to {picker_pack_path}")
  109. util.add_to_index(picker_file_name, args.add_to_index)
  110. parser = argparse.ArgumentParser()
  111. parser.add_argument("--config",
  112. help="Path to JSON file with Matrix homeserver and access_token",
  113. type=str, default="config.json", metavar="file")
  114. parser.add_argument("--title", help="Override the sticker pack displayname", type=str,
  115. metavar="title")
  116. parser.add_argument("--id", help="Override the sticker pack ID", type=str, metavar="id")
  117. parser.add_argument("--add-to-index", help="Sticker picker pack directory (usually 'web/packs/')",
  118. type=str, metavar="path")
  119. parser.add_argument("path", help="Path to the sticker pack directory", type=str)
  120. def cmd():
  121. asyncio.get_event_loop().run_until_complete(main(parser.parse_args()))
  122. if __name__ == "__main__":
  123. cmd()