matrix-archive.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #!/usr/bin/env python3
  2. """matrix-archive
  3. Archive Matrix room messages. Creates a YAML log of all room
  4. messages, including media.
  5. Use the unattended batch mode to fetch everything in one go without
  6. having to type anything during script execution. You can set all
  7. the necessary values with arguments to your command call.
  8. If you don't want to put your passwords in the command call, you
  9. can still set the default values for homeserver, user ID and room
  10. keys path already to have them suggested to you during interactive
  11. execution. Rooms that you specify in the command call will be
  12. automatically fetched before prompting for further input.
  13. Example calls:
  14. ./matrix-archive.py
  15. Run program in interactive mode.
  16. ./matrix-archive.py backups
  17. Set output folder for selected rooms.
  18. ./matrix-archive.py --batch --user '@user:matrix.org' --userpass secret --keys element-keys.txt --keyspass secret
  19. Use unattended batch mode to login.
  20. ./matrix-archive.py --room '!Abcdefghijklmnopqr:matrix.org'
  21. Automatically fetch a room.
  22. ./matrix-archive.py --room '!Abcdefghijklmnopqr:matrix.org' --room '!Bcdefghijklmnopqrs:matrix.org'
  23. Automatically fetch two rooms.
  24. ./matrix-archive.py --roomregex '.*:matrix.org'
  25. Automatically fetch every rooms which matches a regex pattern.
  26. ./matrix-archive.py --all-rooms
  27. Automatically fetch all available rooms.
  28. """
  29. from nio import (
  30. AsyncClient,
  31. AsyncClientConfig,
  32. MatrixRoom,
  33. MessageDirection,
  34. RedactedEvent,
  35. RoomEncryptedMedia,
  36. RoomMessage,
  37. RoomMessageFormatted,
  38. RoomMessageMedia,
  39. crypto,
  40. store,
  41. exceptions
  42. )
  43. from functools import partial
  44. from typing import Union, TextIO
  45. from urllib.parse import urlparse
  46. import aiofiles
  47. import argparse
  48. import asyncio
  49. import getpass
  50. import itertools
  51. import os
  52. import re
  53. import sys
  54. import yaml
  55. import json
  56. DEVICE_NAME = "matrix-archive"
  57. def parse_args():
  58. """Parse arguments from command line call"""
  59. parser = argparse.ArgumentParser(
  60. description=__doc__,
  61. add_help=False, # Use individual setting below instead
  62. formatter_class=argparse.RawDescriptionHelpFormatter,
  63. )
  64. parser.add_argument(
  65. "folder",
  66. metavar="FOLDER",
  67. default=".",
  68. nargs="?", # Make positional argument optional
  69. help="""Set output folder
  70. """,
  71. )
  72. parser.add_argument(
  73. "--help",
  74. action="help",
  75. help="""Show this help message and exit
  76. """,
  77. )
  78. parser.add_argument(
  79. "--batch",
  80. action="store_true",
  81. help="""Use unattended batch mode
  82. """,
  83. )
  84. parser.add_argument(
  85. "--server",
  86. metavar="HOST",
  87. default="https://matrix-client.matrix.org",
  88. help="""Set default Matrix homeserver
  89. """,
  90. )
  91. parser.add_argument(
  92. "--user",
  93. metavar="USER_ID",
  94. default="@user:matrix.org",
  95. help="""Set default user ID
  96. """,
  97. )
  98. parser.add_argument(
  99. "--userpass",
  100. metavar="PASSWORD",
  101. help="""Set default user password
  102. """,
  103. )
  104. parser.add_argument(
  105. "--keys",
  106. metavar="FILENAME",
  107. default="element-keys.txt",
  108. help="""Set default path to room E2E keys
  109. """,
  110. )
  111. parser.add_argument(
  112. "--keyspass",
  113. metavar="PASSWORD",
  114. help="""Set default passphrase for room E2E keys
  115. """,
  116. )
  117. parser.add_argument(
  118. "--room",
  119. metavar="ROOM_ID",
  120. default=[],
  121. action="append",
  122. help="""Add room to list of automatically fetched rooms
  123. """,
  124. )
  125. parser.add_argument(
  126. "--roomregex",
  127. metavar="PATTERN",
  128. default=[],
  129. action="append",
  130. help="""Same as --room but by regex pattern
  131. """,
  132. )
  133. parser.add_argument(
  134. "--all-rooms",
  135. action="store_true",
  136. help="""Select all rooms
  137. """,
  138. )
  139. parser.add_argument(
  140. "--no-media",
  141. action="store_true",
  142. help="""Don't download media
  143. """,
  144. )
  145. return parser.parse_args()
  146. def mkdir(path):
  147. try:
  148. os.mkdir(path)
  149. except FileExistsError:
  150. pass
  151. return path
  152. async def create_client() -> AsyncClient:
  153. homeserver = ARGS.server
  154. user_id = ARGS.user
  155. password = ARGS.userpass
  156. if not ARGS.batch:
  157. homeserver = input(f"Enter URL of your homeserver: [{homeserver}] ") or homeserver
  158. user_id = input(f"Enter your full user ID: [{user_id}] ") or user_id
  159. password = getpass.getpass()
  160. client = AsyncClient(
  161. homeserver=homeserver,
  162. user=user_id,
  163. config=AsyncClientConfig(store=store.SqliteMemoryStore),
  164. )
  165. await client.login(password, DEVICE_NAME)
  166. client.load_store()
  167. room_keys_path = ARGS.keys
  168. room_keys_password = ARGS.keyspass
  169. if not ARGS.batch:
  170. room_keys_path = input(f"Enter full path to room E2E keys: [{room_keys_path}] ") or room_keys_path
  171. room_keys_password = getpass.getpass("Room keys password: ")
  172. print("Importing keys. This may take a while...")
  173. await client.import_keys(room_keys_path, room_keys_password)
  174. return client
  175. async def select_room(client: AsyncClient) -> MatrixRoom:
  176. print("\nList of joined rooms (room id, display name):")
  177. for room_id, room in client.rooms.items():
  178. print(f"{room_id}, {room.display_name}")
  179. room_id = input(f"Enter room id: ")
  180. return client.rooms[room_id]
  181. def choose_filename(filename):
  182. start, ext = os.path.splitext(filename)
  183. for i in itertools.count(1):
  184. if not os.path.exists(filename):
  185. break
  186. filename = f"{start}({i}){ext}"
  187. return filename
  188. async def write_event(
  189. client: AsyncClient, room: MatrixRoom, output_file: TextIO, event: RoomMessage
  190. ) -> None:
  191. if not ARGS.no_media:
  192. media_dir = mkdir(f"{OUTPUT_DIR}/{room.display_name}_{room.room_id}_media")
  193. sender_name = f"<{event.sender}>"
  194. if event.sender in room.users:
  195. # If user is still present in room, include current nickname
  196. sender_name = f"{room.users[event.sender].display_name} {sender_name}"
  197. serialize_event = lambda event_payload: yaml.dump(
  198. [
  199. {
  200. **dict(
  201. sender_id=event.sender,
  202. sender_name=sender_name,
  203. timestamp=event.server_timestamp,
  204. ),
  205. **event_payload,
  206. }
  207. ]
  208. )
  209. if isinstance(event, RoomMessageFormatted):
  210. await output_file.write(serialize_event(dict(type="text", body=event.body,)))
  211. elif isinstance(event, (RoomMessageMedia, RoomEncryptedMedia)):
  212. media_data = await download_mxc(client, event.url)
  213. filename = choose_filename(f"{media_dir}/{event.body}")
  214. async with aiofiles.open(filename, "wb") as f:
  215. try:
  216. await f.write(
  217. crypto.attachments.decrypt_attachment(
  218. media_data,
  219. event.source["content"]["file"]["key"]["k"],
  220. event.source["content"]["file"]["hashes"]["sha256"],
  221. event.source["content"]["file"]["iv"],
  222. )
  223. )
  224. except KeyError: # EAFP: Unencrypted media produces KeyError
  225. await f.write(media_data)
  226. # Set atime and mtime of file to event timestamp
  227. os.utime(filename, ns=((event.server_timestamp * 1000000,) * 2))
  228. await output_file.write(serialize_event(dict(type="media", src="." + filename[len(OUTPUT_DIR):],)))
  229. elif isinstance(event, RedactedEvent):
  230. await output_file.write(serialize_event(dict(type="redacted",)))
  231. async def save_avatars(client: AsyncClient, room: MatrixRoom) -> None:
  232. avatar_dir = mkdir(f"{OUTPUT_DIR}/{room.display_name}_{room.room_id}_avatars")
  233. for user in room.users.values():
  234. if user.avatar_url:
  235. async with aiofiles.open(f"{avatar_dir}/{user.user_id}", "wb") as f:
  236. await f.write(await download_mxc(client, user.avatar_url))
  237. async def download_mxc(client: AsyncClient, url: str):
  238. mxc = urlparse(url)
  239. response = await client.download(mxc.netloc, mxc.path.strip("/"))
  240. if hasattr(response, "body"):
  241. return response.body
  242. else:
  243. return b''
  244. def is_valid_event(event):
  245. events = (RoomMessageFormatted, RedactedEvent)
  246. if not ARGS.no_media:
  247. events += (RoomMessageMedia, RoomEncryptedMedia)
  248. return isinstance(event, events)
  249. async def fetch_room_events(
  250. client: AsyncClient,
  251. start_token: str,
  252. room: MatrixRoom,
  253. direction: MessageDirection,
  254. ) -> list:
  255. events = []
  256. while True:
  257. response = await client.room_messages(
  258. room.room_id, start_token, limit=1000, direction=direction
  259. )
  260. if len(response.chunk) == 0:
  261. break
  262. events.extend(event for event in response.chunk if is_valid_event(event))
  263. start_token = response.end
  264. return events
  265. async def write_room_events(client, room):
  266. print(f"Fetching {room.room_id} room messages and writing to disk...")
  267. sync_resp = await client.sync(
  268. full_state=True, sync_filter={"room": {"timeline": {"limit": 1}}}
  269. )
  270. start_token = sync_resp.rooms.join[room.room_id].timeline.prev_batch
  271. # Generally, it should only be necessary to fetch back events but,
  272. # sometimes depending on the sync, front events need to be fetched
  273. # as well.
  274. fetch_room_events_ = partial(fetch_room_events, client, start_token, room)
  275. async with aiofiles.open(
  276. f"{OUTPUT_DIR}/{room.display_name}_{room.room_id}.json", "w"
  277. ) as f_json:
  278. for events in [
  279. reversed(await fetch_room_events_(MessageDirection.back)),
  280. await fetch_room_events_(MessageDirection.front),
  281. ]:
  282. events_parsed = []
  283. for event in events:
  284. try:
  285. if not ARGS.no_media:
  286. media_dir = mkdir(f"{OUTPUT_DIR}/{room.display_name}_{room.room_id}_media")
  287. # add additional information to the message source
  288. sender_name = f"<{event.sender}>"
  289. if event.sender in room.users:
  290. # If user is still present in room, include current nickname
  291. sender_name = f"{room.users[event.sender].display_name} {sender_name}"
  292. event.source["_sender_name"] = sender_name
  293. # download media if necessary
  294. if isinstance(event, (RoomMessageMedia, RoomEncryptedMedia)):
  295. media_data = await download_mxc(client, event.url)
  296. filename = choose_filename(f"{media_dir}/{event.body}")
  297. event.source["_file_path"] = filename
  298. async with aiofiles.open(filename, "wb") as f_media:
  299. try:
  300. await f_media.write(
  301. crypto.attachments.decrypt_attachment(
  302. media_data,
  303. event.source["content"]["file"]["key"]["k"],
  304. event.source["content"]["file"]["hashes"]["sha256"],
  305. event.source["content"]["file"]["iv"],
  306. )
  307. )
  308. except KeyError: # EAFP: Unencrypted media produces KeyError
  309. await f_media.write(media_data)
  310. # Set atime and mtime of file to event timestamp
  311. os.utime(filename, ns=((event.server_timestamp * 1000000,) * 2))
  312. # write out the processed message source
  313. events_parsed.append(event.source)
  314. except exceptions.EncryptionError as e:
  315. print(e, file=sys.stderr)
  316. # serialise message array
  317. await f_json.write(json.dumps(events_parsed, indent=4))
  318. await save_avatars(client, room)
  319. print("Successfully wrote all room events to disk.")
  320. async def main() -> None:
  321. try:
  322. client = await create_client()
  323. await client.sync(
  324. full_state=True,
  325. # Limit fetch of room events as they will be fetched later
  326. sync_filter={"room": {"timeline": {"limit": 1}}})
  327. for room_id, room in client.rooms.items():
  328. # Iterate over rooms to see if a room has been selected to
  329. # be automatically fetched
  330. if room_id in ARGS.room or any(re.match(pattern, room_id) for pattern in ARGS.roomregex):
  331. print(f"Selected room: {room_id}")
  332. await write_room_events(client, room)
  333. if ARGS.batch:
  334. # If the program is running in unattended batch mode,
  335. # then we can quit at this point
  336. raise SystemExit
  337. else:
  338. while True:
  339. room = await select_room(client)
  340. await write_room_events(client, room)
  341. except KeyboardInterrupt:
  342. sys.exit(1)
  343. finally:
  344. await client.logout()
  345. await client.close()
  346. if __name__ == "__main__":
  347. ARGS = parse_args()
  348. if ARGS.all_rooms:
  349. # Select all rooms by adding a regex pattern which matches every string
  350. ARGS.roomregex.append(".*")
  351. OUTPUT_DIR = mkdir(ARGS.folder)
  352. asyncio.get_event_loop().run_until_complete(main())