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.

194 lines
6.9 KiB

4 years ago
  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 typing import Dict, TypedDict
  7. from io import BytesIO
  8. import argparse
  9. import os.path
  10. import asyncio
  11. import json
  12. import re
  13. from aiohttp import ClientSession
  14. from yarl import URL
  15. from PIL import Image
  16. from telethon import TelegramClient
  17. from telethon.tl.functions.messages import GetAllStickersRequest, GetStickerSetRequest
  18. from telethon.tl.types.messages import AllStickers
  19. from telethon.tl.types import InputStickerSetShortName, Document
  20. from telethon.tl.types.messages import StickerSet as StickerSetFull
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument("--list", help="List your saved sticker packs", action="store_true")
  23. parser.add_argument("--session", help="Telethon session file name", default="sticker-import")
  24. parser.add_argument("--config", help="Path to JSON file with Matrix homeserver and access_token",
  25. type=str, default="config.json")
  26. parser.add_argument("--output-dir", help="Directory to write packs to", default="web/packs/",
  27. type=str)
  28. parser.add_argument("pack", help="Sticker pack URLs to import", action="append", nargs="*")
  29. args = parser.parse_args()
  30. with open(args.config) as config_file:
  31. config = json.load(config_file)
  32. homeserver_url = config["homeserver"]
  33. upload_url = URL(homeserver_url) / "_matrix" / "media" / "r0" / "upload"
  34. access_token = config["access_token"]
  35. async def upload(data: bytes, mimetype: str, filename: str) -> str:
  36. url = upload_url.with_query({"filename": filename})
  37. headers = {"Content-Type": mimetype, "Authorization": f"Bearer {access_token}"}
  38. async with ClientSession() as sess, sess.post(url, data=data, headers=headers) as resp:
  39. return (await resp.json())["content_uri"]
  40. class MatrixMediaInfo(TypedDict):
  41. w: int
  42. h: int
  43. size: int
  44. mimetype: str
  45. class MatrixStickerInfo(TypedDict, total=False):
  46. body: str
  47. url: str
  48. info: MatrixMediaInfo
  49. def convert_image(data: bytes) -> (bytes, int, int):
  50. image: Image.Image = Image.open(BytesIO(data)).convert("RGBA")
  51. image.thumbnail((256, 256), Image.ANTIALIAS)
  52. new_file = BytesIO()
  53. image.save(new_file, "png")
  54. w, h = image.size
  55. return new_file.getvalue(), w, h
  56. async def reupload_document(client: TelegramClient, document: Document) -> MatrixStickerInfo:
  57. print(f"Reuploading {document.id}", end="", flush=True)
  58. data = await client.download_media(document, file=bytes)
  59. print(".", end="", flush=True)
  60. data, width, height = convert_image(data)
  61. print(".", end="", flush=True)
  62. mxc = await upload(data, "image/png", f"{document.id}.png")
  63. print(".", flush=True)
  64. return {
  65. "body": "",
  66. "url": mxc,
  67. "info": {
  68. "w": width,
  69. "h": height,
  70. "size": len(data),
  71. "mimetype": "image/png",
  72. },
  73. }
  74. def add_to_index(name: str) -> None:
  75. index_path = os.path.join(args.output_dir, "index.json")
  76. try:
  77. with open(index_path) as index_file:
  78. index_data = json.load(index_file)
  79. except (FileNotFoundError, json.JSONDecodeError):
  80. index_data = {"packs": [], "homeserver_url": homeserver_url}
  81. if name not in index_data["packs"]:
  82. index_data["packs"].append(name)
  83. with open(index_path, "w") as index_file:
  84. json.dump(index_data, index_file, indent=" ")
  85. print(f"Added {name} to {index_path}")
  86. async def reupload_pack(client: TelegramClient, pack: StickerSetFull) -> None:
  87. if pack.set.animated:
  88. print("Animated stickerpacks are currently not supported")
  89. return
  90. pack_path = os.path.join(args.output_dir, f"{pack.set.short_name}.json")
  91. try:
  92. os.mkdir(os.path.dirname(pack_path))
  93. except FileExistsError:
  94. pass
  95. print(f"Reuploading {pack.set.title} with {pack.set.count} stickers "
  96. f"and writing output to {pack_path}")
  97. already_uploaded = {}
  98. try:
  99. with open(pack_path) as pack_file:
  100. existing_pack = json.load(pack_file)
  101. already_uploaded = {sticker["net.maunium.telegram.sticker"]["id"]: sticker
  102. for sticker in existing_pack["stickers"]}
  103. print(f"Found {len(already_uploaded)} already reuploaded stickers")
  104. except FileNotFoundError:
  105. pass
  106. reuploaded_documents: Dict[int, MatrixStickerInfo] = {}
  107. for document in pack.documents:
  108. try:
  109. reuploaded_documents[document.id] = already_uploaded[document.id]
  110. print(f"Skipped reuploading {document.id}")
  111. except KeyError:
  112. reuploaded_documents[document.id] = await reupload_document(client, document)
  113. for sticker in pack.packs:
  114. for document_id in sticker.documents:
  115. doc = reuploaded_documents[document_id]
  116. doc["body"] = sticker.emoticon
  117. doc["net.maunium.telegram.sticker"] = {
  118. "pack": {
  119. "id": pack.set.id,
  120. "short_name": pack.set.short_name,
  121. },
  122. "id": document_id,
  123. "emoticon": sticker.emoticon,
  124. }
  125. with open(pack_path, "w") as pack_file:
  126. json.dump({
  127. "title": pack.set.title,
  128. "short_name": pack.set.short_name,
  129. "id": pack.set.id,
  130. "hash": pack.set.hash,
  131. "stickers": list(reuploaded_documents.values()),
  132. }, pack_file, ensure_ascii=False)
  133. add_to_index(os.path.basename(pack_path))
  134. pack_url_regex = re.compile(r"^(?:(?:https?://)?(?:t|telegram)\.(?:me|dog)/addstickers/)?"
  135. r"([A-Za-z0-9-_]+)"
  136. r"(?:\.json)?$")
  137. async def main():
  138. client = TelegramClient(args.session, 298751, "cb676d6bae20553c9996996a8f52b4d7")
  139. await client.start()
  140. if args.list:
  141. stickers: AllStickers = await client(GetAllStickersRequest(hash=0))
  142. index = 1
  143. width = len(str(stickers.sets))
  144. print("Your saved sticker packs:")
  145. for saved_pack in stickers.sets:
  146. print(f"{index:>{width}}. {saved_pack.title} "
  147. f"(t.me/addstickers/{saved_pack.short_name})")
  148. elif args.pack[0]:
  149. input_packs = []
  150. for pack_url in args.pack[0]:
  151. match = pack_url_regex.match(pack_url)
  152. if not match:
  153. print(f"'{pack_url}' doesn't look like a sticker pack URL")
  154. return
  155. input_packs.append(InputStickerSetShortName(short_name=match.group(1)))
  156. for input_pack in input_packs:
  157. pack: StickerSetFull = await client(GetStickerSetRequest(input_pack))
  158. await reupload_pack(client, pack)
  159. print(f"Saved {pack.set.title} as {pack.set.short_name}.json")
  160. else:
  161. parser.print_help()
  162. asyncio.run(main())