This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

1import asyncio 2import json 3import logging 4import os 5import re 6import sys 7from pathlib import Path 8 9import aiohttp 10from aiohttp import web 11from nio import ( 12 AsyncClient, 13 AsyncClientConfig, 14 InviteMemberEvent, 15 LoginResponse, 16 MatrixRoom, 17 RoomMessageText, 18) 19 20logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") 21log = logging.getLogger("archiver-bot") 22 23IMDB_RE = re.compile(r"https?://(?:www\.)?imdb\.com/(?:[a-z]{2}/)?title/(tt\d+)") 24TMDB_MOVIE_RE = re.compile(r"https?://(?:www\.)?themoviedb\.org/movie/(\d+)") 25TMDB_TV_RE = re.compile(r"https?://(?:www\.)?themoviedb\.org/tv/(\d+)") 26 27JELLYSEERR_URL = os.environ.get("JELLYSEERR_URL", "http://localhost:5055") 28JELLYSEERR_API_KEY = os.environ["JELLYSEERR_API_KEY"] 29RADARR_API_KEY = os.environ.get("RADARR_API_KEY", "") 30SONARR_API_KEY = os.environ.get("SONARR_API_KEY", "") 31MATRIX_HOMESERVER = os.environ["MATRIX_HOMESERVER"] 32MATRIX_ACCESS_TOKEN = os.environ["MATRIX_ACCESS_TOKEN"] 33MATRIX_USER_ID = os.environ.get("MATRIX_USER_ID", "@archiver:lassul.us") 34MATRIX_DEVICE_ID = os.environ.get("MATRIX_DEVICE_ID", "ARCHIVER") 35STORE_PATH = os.environ.get("STORE_PATH", "/var/lib/archiver-bot") 36WEBHOOK_PORT = int(os.environ.get("WEBHOOK_PORT", "8099")) 37FLAX_URL = os.environ.get("FLAX_URL", "https://flax.lassul.us") 38FLIX_URL = os.environ.get("FLIX_URL", "https://flix.lassul.us") 39JELLYFIN_URL = os.environ.get("JELLYFIN_URL", "http://localhost:8096") 40JELLYFIN_API_KEY = os.environ.get("JELLYFIN_API_KEY", "") 41IPFS_GATEWAY_URL = os.environ.get("IPFS_GATEWAY_URL", "https://ipfs.lassul.us") 42MEDIA_PATH_PREFIX = os.environ.get("MEDIA_PATH_PREFIX", "/var/download/") 43IPFS_BIN = os.environ.get("IPFS_BIN", "ipfs") 44 45# Persistent tracking of requested media -> rooms 46TRACKING_FILE = Path(STORE_PATH) / "tracked_requests.json" 47 48 49def load_tracked() -> dict: 50 """Load tracked requests from disk. Keys are 'movie:TMDBID' or 'tv:TMDBID', values are lists of room_ids.""" 51 try: 52 return json.loads(TRACKING_FILE.read_text()) 53 except Exception: 54 return {} 55 56 57def save_tracked(tracked: dict): 58 """Save tracked requests to disk.""" 59 TRACKING_FILE.write_text(json.dumps(tracked)) 60 61 62def track_request(media_type: str, tmdb_id: int, room_id: str): 63 """Track that a room requested this media.""" 64 tracked = load_tracked() 65 key = f"{media_type}:{tmdb_id}" 66 rooms = tracked.get(key, []) 67 if room_id not in rooms: 68 rooms.append(room_id) 69 tracked[key] = rooms 70 save_tracked(tracked) 71 72 73def pop_tracked(media_type: str, tmdb_id: int) -> list[str]: 74 """Get and remove tracked rooms for this media.""" 75 tracked = load_tracked() 76 key = f"{media_type}:{tmdb_id}" 77 rooms = tracked.pop(key, []) 78 save_tracked(tracked) 79 return rooms 80 81 82def make_flax_link(path: str) -> str: 83 """Turn a local path like /var/download/movies/Title (Year)/file.mp4 into a flax.lassul.us URL.""" 84 from urllib.parse import quote 85 relative = path 86 if relative.startswith(MEDIA_PATH_PREFIX): 87 relative = relative[len(MEDIA_PATH_PREFIX):] 88 return f"{FLAX_URL}/{quote(relative)}" 89 90 91async def compute_cid(path: str) -> str | None: 92 """Compute the IPFS CID for a file using ipfs add --only-hash --raw-leaves.""" 93 try: 94 ipfs_path = "/tmp/ipfs-hash-repo" 95 if not os.path.exists(os.path.join(ipfs_path, "config")): 96 init_proc = await asyncio.create_subprocess_exec( 97 IPFS_BIN, "init", 98 stdout=asyncio.subprocess.PIPE, 99 stderr=asyncio.subprocess.PIPE, 100 env={**os.environ, "IPFS_PATH": ipfs_path}, 101 ) 102 await init_proc.communicate() 103 env = {**os.environ, "IPFS_PATH": ipfs_path} 104 proc = await asyncio.create_subprocess_exec( 105 IPFS_BIN, "add", "--only-hash", "--raw-leaves", "--quieter", path, 106 stdout=asyncio.subprocess.PIPE, 107 stderr=asyncio.subprocess.PIPE, 108 env=env, 109 ) 110 try: 111 stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=120) 112 except asyncio.TimeoutError: 113 proc.kill() 114 await proc.communicate() 115 log.warning(f"ipfs add --only-hash timed out for {path}") 116 return None 117 if proc.returncode == 0: 118 cid = stdout.decode().strip() 119 if cid: 120 return cid 121 else: 122 log.warning(f"ipfs add --only-hash failed for {path}: {stderr.decode().strip()}") 123 except Exception as e: 124 log.warning(f"Failed to compute CID for {path}: {e}") 125 return None 126 127 128async def trigger_jellyfin_scan(session: aiohttp.ClientSession): 129 """Trigger a Jellyfin library scan and Jellyseerr sync.""" 130 try: 131 async with session.post( 132 f"{JELLYFIN_URL}/Library/Refresh", 133 headers={"X-Emby-Token": JELLYFIN_API_KEY}, 134 ) as resp: 135 log.info(f"Triggered Jellyfin library scan: {resp.status}") 136 # also trigger Jellyseerr sync so it picks up the new jellyfinMediaId 137 await jellyseerr_request(session, "/settings/jellyfin/sync", method="POST") 138 log.info("Triggered Jellyseerr sync") 139 except Exception as e: 140 log.warning(f"Failed to trigger library scan: {e}") 141 142 143async def lookup_jellyfin_id(session: aiohttp.ClientSession, media_type: str, tmdb_id: int) -> str | None: 144 """Look up Jellyfin item ID via Jellyseerr's mediaInfo or Jellyfin API.""" 145 # Try Jellyseerr first — it tracks the Jellyfin media ID 146 # Try Jellyseerr first 147 try: 148 endpoint = f"/movie/{tmdb_id}" if media_type == "movie" else f"/tv/{tmdb_id}" 149 details = await jellyseerr_request(session, endpoint) 150 media_info = details.get("mediaInfo") 151 if media_info: 152 jf_id = media_info.get("jellyfinMediaId") 153 if jf_id: 154 log.info(f"Jellyfin ID from Jellyseerr for {media_type}:{tmdb_id} = {jf_id}") 155 return jf_id 156 except Exception as e: 157 log.warning(f"Jellyseerr Jellyfin ID lookup failed for {media_type}:{tmdb_id}: {e}") 158 159 # Fallback: query Jellyfin directly, searching by provider ID 160 if JELLYFIN_API_KEY: 161 try: 162 item_type = "Movie" if media_type == "movie" else "Series" 163 async with session.get( 164 f"{JELLYFIN_URL}/Items", 165 params={ 166 "IncludeItemTypes": item_type, 167 "Recursive": "true", 168 "Fields": "ProviderIds", 169 }, 170 headers={"X-Emby-Token": JELLYFIN_API_KEY}, 171 ) as resp: 172 data = await resp.json() 173 for item in data.get("Items", []): 174 provider_ids = item.get("ProviderIds", {}) 175 if str(provider_ids.get("Tmdb")) == str(tmdb_id): 176 jf_id = item.get("Id") 177 log.info(f"Jellyfin ID from Jellyfin API for {media_type}:{tmdb_id} = {jf_id}") 178 return jf_id 179 except Exception as e: 180 log.warning(f"Jellyfin API lookup failed for {media_type}:{tmdb_id}: {e}") 181 182 log.info(f"No Jellyfin ID found for {media_type}:{tmdb_id}") 183 return None 184 185 186async def make_media_links(path: str, is_dir: bool = False, jellyfin_id: str | None = None) -> tuple[str, str]: 187 """Generate plain and HTML text with all available links for a media path.""" 188 from urllib.parse import quote 189 190 lines_plain = [] 191 lines_html = [] 192 193 # Flax link (direct file download) 194 flax = make_flax_link(path) 195 lines_plain.append(f"📁 Download: {flax}") 196 lines_html.append(f'📁 Download: <a href="{flax}">{flax}</a>') 197 198 # Jellyfin link (streaming) 199 if jellyfin_id: 200 flix_link = f"{FLIX_URL}/web/#/details?id={jellyfin_id}" 201 else: 202 flix_link = FLIX_URL 203 lines_plain.append(f"🎬 Stream: {flix_link}") 204 lines_html.append(f'🎬 Stream: <a href="{flix_link}">{flix_link}</a>') 205 206 # IPFS link (compute CID for the file) 207 if not is_dir: 208 cid = await compute_cid(path) 209 if cid: 210 ipfs_link = f"{IPFS_GATEWAY_URL}/ipfs/{cid}" 211 lines_plain.append(f"🌐 IPFS: {ipfs_link}") 212 lines_html.append(f'🌐 IPFS: <a href="{ipfs_link}">{ipfs_link}</a>') 213 lines_plain.append(f" ipfs get {cid}") 214 lines_html.append(f" <code>ipfs get {cid}</code>") 215 216 return ("\n".join(lines_plain), "<br>".join(lines_html)) 217 218 219async def jellyseerr_request(session: aiohttp.ClientSession, path: str, **kwargs) -> dict: 220 """Make an authenticated request to Jellyseerr.""" 221 headers = { 222 "X-Api-Key": JELLYSEERR_API_KEY, 223 "Content-Type": "application/json", 224 "Accept": "application/json", 225 } 226 method = kwargs.pop("method", "GET") 227 url = f"{JELLYSEERR_URL}/api/v1{path}" 228 async with session.request(method, url, headers=headers, **kwargs) as resp: 229 return await resp.json() 230 231 232async def find_by_imdb(session: aiohttp.ClientSession, imdb_id: str) -> dict | None: 233 """Look up a movie or TV show by IMDb ID via Radarr/Sonarr, returning Jellyseerr-compatible data.""" 234 235 # Try Radarr (movies) first 236 try: 237 async with session.get( 238 f"http://localhost:7878/api/v3/movie/lookup?term=imdb:{imdb_id}", 239 headers={"X-Api-Key": RADARR_API_KEY}, 240 ) as resp: 241 results = await resp.json() 242 if results and len(results) > 0: 243 tmdb_id = results[0].get("tmdbId") 244 title = results[0].get("title", "Unknown") 245 year = str(results[0].get("year", "")) 246 if tmdb_id: 247 log.info(f"Radarr resolved {imdb_id} -> TMDB {tmdb_id} ({title})") 248 return { 249 "id": tmdb_id, 250 "mediaType": "movie", 251 "title": title, 252 "releaseDate": f"{year}-01-01" if year else "", 253 } 254 except Exception as e: 255 log.warning(f"Radarr lookup failed: {e}") 256 257 # Try Sonarr (TV shows) 258 try: 259 async with session.get( 260 f"http://localhost:8989/api/v3/series/lookup?term=imdb:{imdb_id}", 261 headers={"X-Api-Key": SONARR_API_KEY}, 262 ) as resp: 263 results = await resp.json() 264 if results and len(results) > 0: 265 tmdb_id = results[0].get("tmdbId", 0) 266 title = results[0].get("title", "Unknown") 267 year = str(results[0].get("year", "")) 268 if tmdb_id: 269 log.info(f"Sonarr resolved {imdb_id} -> TMDB {tmdb_id} ({title})") 270 return { 271 "id": tmdb_id, 272 "mediaType": "tv", 273 "name": title, 274 "firstAirDate": f"{year}-01-01" if year else "", 275 } 276 except Exception as e: 277 log.warning(f"Sonarr lookup failed: {e}") 278 279 return None 280 281 282async def lookup_media_path(session: aiohttp.ClientSession, media_type: str, tmdb_id: int) -> str | None: 283 """Look up the path for a movie file or show folder from Radarr/Sonarr by TMDB ID.""" 284 try: 285 if media_type == "movie": 286 async with session.get( 287 f"http://localhost:7878/api/v3/movie?tmdbId={tmdb_id}", 288 headers={"X-Api-Key": RADARR_API_KEY}, 289 ) as resp: 290 results = await resp.json() 291 if results and len(results) > 0: 292 # Return direct file path if available, otherwise folder 293 movie_file = results[0].get("movieFile", {}) 294 if movie_file and movie_file.get("path"): 295 return movie_file["path"] 296 return results[0].get("path") or results[0].get("folderName") 297 else: 298 async with session.get( 299 f"http://localhost:8989/api/v3/series?tvdbId={tmdb_id}", 300 headers={"X-Api-Key": SONARR_API_KEY}, 301 ) as resp: 302 results = await resp.json() 303 if results and len(results) > 0: 304 return results[0].get("path") 305 except Exception as e: 306 log.warning(f"Media path lookup failed for {media_type}:{tmdb_id}: {e}") 307 return None 308 309 310async def request_media(session: aiohttp.ClientSession, media: dict, room_id: str) -> tuple[str, str]: 311 """Request a movie or TV show via Jellyseerr. Returns (plain, html) status message.""" 312 media_type = media["mediaType"] 313 media_id = media["id"] 314 title = media.get("title") or media.get("name") or "Unknown" 315 year = (media.get("releaseDate") or media.get("firstAirDate") or "")[:4] 316 display = f"{title} ({year})" if year else title 317 318 # Check if already available or requested 319 existing = media.get("mediaInfo") 320 if existing: 321 status = existing.get("status") 322 # status 5 = available, 4 = partially available, 3 = processing, 2 = pending 323 if status == 5: 324 path = await lookup_media_path(session, media_type, media_id) 325 if path: 326 is_dir = media_type == "tv" 327 jf_id = await lookup_jellyfin_id(session, media_type, media_id) 328 links_plain, links_html = await make_media_links(path, is_dir=is_dir, jellyfin_id=jf_id) 329 return (f"✅ {display} is already available!\n{links_plain}", f"✅ <b>{display}</b> is already available!<br>{links_html}") 330 return (f"✅ {display} is already available!", f"✅ <b>{display}</b> is already available!") 331 elif status in (2, 3, 4): 332 track_request(media_type, media_id, room_id) 333 return (f"⏳ {display} has already been requested and is being processed.", f"⏳ <b>{display}</b> has already been requested and is being processed.") 334 335 payload = {"mediaType": media_type, "mediaId": media_id} 336 if media_type == "tv": 337 payload["seasons"] = "all" 338 339 # Check if Radarr/Sonarr already has the file before requesting 340 existing_path = await lookup_media_path(session, media_type, media_id) 341 if existing_path: 342 is_dir = media_type == "tv" 343 jf_id = await lookup_jellyfin_id(session, media_type, media_id) 344 links_plain, links_html = await make_media_links(existing_path, is_dir=is_dir, jellyfin_id=jf_id) 345 # Still send the request to Jellyseerr so it's tracked there too 346 await jellyseerr_request(session, "/request", method="POST", json=payload) 347 return (f"✅ {display} is already available!\n{links_plain}", f"✅ <b>{display}</b> is already available!<br>{links_html}") 348 349 result = await jellyseerr_request(session, "/request", method="POST", json=payload) 350 351 if "id" in result: 352 track_request(media_type, media_id, room_id) 353 return (f"🎬 Successfully requested {display}! I'll notify you when it's downloaded.", f"🎬 Successfully requested <b>{display}</b>! I'll notify you when it's downloaded.") 354 else: 355 error = result.get("message", json.dumps(result)) 356 return (f"❌ Failed to request {display}: {error}", f"❌ Failed to request <b>{display}</b>: {error}") 357 358 359async def trust_room_devices(client: AsyncClient, room_id: str): 360 """Trust all devices of all members in a room.""" 361 if not client.olm: 362 return 363 room = client.rooms.get(room_id) 364 if not room: 365 return 366 for user_id in room.users: 367 for device in client.device_store.active_user_devices(user_id): 368 if not client.olm.is_device_verified(device): 369 client.verify_device(device) 370 log.info(f"Verified device {device.device_id} of {user_id}") 371 372 373async def send_notice(client: AsyncClient, room_id: str, plain: str, html: str): 374 """Send a notice message to a room.""" 375 await trust_room_devices(client, room_id) 376 await client.room_send( 377 room_id, 378 "m.room.message", 379 {"msgtype": "m.notice", "body": plain, "format": "org.matrix.custom.html", "formatted_body": html}, 380 ) 381 382 383async def on_message(client: AsyncClient, room: MatrixRoom, event: RoomMessageText, http: aiohttp.ClientSession): 384 """Handle messages in rooms, looking for IMDb/TMDB links.""" 385 # Ignore our own messages 386 if event.sender == client.user_id: 387 return 388 389 body = event.body 390 log.info(f"Message from {event.sender} in {room.display_name}: {body[:100]}") 391 392 # Help command 393 if body.strip().lower() in ("help", "!help"): 394 plain = ( 395 "Archiver Bot\n\n" 396 "Send me an IMDb or TMDB link and I'll request the movie/show on Jellyseerr.\n" 397 "I'll notify you when the download is complete.\n\n" 398 "Examples:\n" 399 " https://www.imdb.com/title/tt0133093/\n" 400 " https://www.themoviedb.org/movie/603\n" 401 " https://www.themoviedb.org/tv/1399" 402 ) 403 html = ( 404 "<b>Archiver Bot</b><br><br>" 405 "Send me an IMDb or TMDB link and I'll request the movie/show on Jellyseerr.<br>" 406 "I'll notify you when the download is complete.<br><br>" 407 "Examples:<br>" 408 "<code>https://www.imdb.com/title/tt0133093/</code><br>" 409 "<code>https://www.themoviedb.org/movie/603</code><br>" 410 "<code>https://www.themoviedb.org/tv/1399</code>" 411 ) 412 await send_notice(client, room.room_id, plain, html) 413 return 414 415 # Collect all media references from the message 416 results = [] 417 418 for imdb_id in set(IMDB_RE.findall(body)): 419 log.info(f"Found IMDb link {imdb_id} in {room.display_name} from {event.sender}") 420 media = await find_by_imdb(http, imdb_id) 421 if media is None: 422 results.append((f"❓ Could not find anything for {imdb_id}.", f"❓ Could not find anything for <code>{imdb_id}</code>.")) 423 else: 424 results.append(await request_media(http, media, room.room_id)) 425 426 for tmdb_id in set(TMDB_MOVIE_RE.findall(body)): 427 log.info(f"Found TMDB movie link {tmdb_id} in {room.display_name} from {event.sender}") 428 media = {"id": int(tmdb_id), "mediaType": "movie"} 429 try: 430 details = await jellyseerr_request(http, f"/movie/{tmdb_id}") 431 media["title"] = details.get("title", "Unknown") 432 media["releaseDate"] = details.get("releaseDate", "") 433 media["mediaInfo"] = details.get("mediaInfo") 434 except Exception as e: 435 log.warning(f"Failed to fetch TMDB movie {tmdb_id}: {e}") 436 results.append(await request_media(http, media, room.room_id)) 437 438 for tmdb_id in set(TMDB_TV_RE.findall(body)): 439 log.info(f"Found TMDB TV link {tmdb_id} in {room.display_name} from {event.sender}") 440 media = {"id": int(tmdb_id), "mediaType": "tv"} 441 try: 442 details = await jellyseerr_request(http, f"/tv/{tmdb_id}") 443 media["name"] = details.get("name", "Unknown") 444 media["firstAirDate"] = details.get("firstAirDate", "") 445 media["mediaInfo"] = details.get("mediaInfo") 446 except Exception as e: 447 log.warning(f"Failed to fetch TMDB TV {tmdb_id}: {e}") 448 results.append(await request_media(http, media, room.room_id)) 449 450 for plain, html in results: 451 await send_notice(client, room.room_id, plain, html) 452 453 454async def on_invite(client: AsyncClient, room: MatrixRoom, event: InviteMemberEvent): 455 """Auto-join rooms when invited.""" 456 log.info(f"Invite event in {room.room_id}: state_key={event.state_key}, sender={event.sender}, membership={event.membership}, our_id={client.user_id}") 457 if event.state_key != client.user_id: 458 return 459 log.info(f"Joining {room.room_id} (invited by {event.sender})...") 460 result = await client.join(room.room_id) 461 log.info(f"Join result for {room.room_id}: {result}") 462 463 464async def handle_radarr_webhook(request): 465 """Handle Radarr webhook for download completion.""" 466 try: 467 data = await request.json() 468 event_type = data.get("eventType", "") 469 log.info(f"Radarr webhook: {event_type}") 470 471 if event_type in ("Download", "MovieFileDelete"): 472 movie = data.get("movie", {}) 473 tmdb_id = movie.get("tmdbId") 474 title = movie.get("title", "Unknown") 475 year = movie.get("year", "") 476 display = f"{title} ({year})" if year else title 477 # Prefer the actual movie file path, fall back to folder 478 movie_file = data.get("movieFile", {}) 479 file_path = movie_file.get("path") or movie.get("folderPath", "") 480 481 if event_type == "Download" and tmdb_id: 482 rooms = pop_tracked("movie", tmdb_id) 483 if rooms: 484 client = request.app["matrix_client"] 485 http = request.app["http_session"] 486 # trigger library scan so Jellyfin picks up the new file 487 await trigger_jellyfin_scan(http) 488 await asyncio.sleep(10) 489 jf_id = await lookup_jellyfin_id(http, "movie", tmdb_id) 490 links_plain, links_html = await make_media_links(file_path, jellyfin_id=jf_id) 491 plain = f"✅ {display} has been downloaded and is now available!\n{links_plain}" 492 html = f"✅ <b>{display}</b> has been downloaded and is now available!<br>{links_html}" 493 for room_id in rooms: 494 try: 495 await send_notice(client, room_id, plain, html) 496 except Exception as e: 497 log.warning(f"Failed to notify room {room_id}: {e}") 498 except Exception as e: 499 log.exception(f"Error handling Radarr webhook: {e}") 500 501 return web.Response(text="ok") 502 503 504async def handle_sonarr_webhook(request): 505 """Handle Sonarr webhook for download completion.""" 506 try: 507 data = await request.json() 508 event_type = data.get("eventType", "") 509 log.info(f"Sonarr webhook: {event_type}") 510 511 if event_type in ("Download", "EpisodeFileDelete"): 512 series = data.get("series", {}) 513 tmdb_id = series.get("tmdbId") 514 title = series.get("title", "Unknown") 515 year = series.get("year", "") 516 display = f"{title} ({year})" if year else title 517 518 episodes = data.get("episodes", []) 519 ep_info = "" 520 if episodes: 521 ep_nums = [f"S{ep.get('seasonNumber', 0):02d}E{ep.get('episodeNumber', 0):02d}" for ep in episodes] 522 ep_info = f" ({', '.join(ep_nums)})" 523 524 if event_type == "Download" and tmdb_id: 525 rooms = pop_tracked("tv", tmdb_id) 526 if rooms: 527 client = request.app["matrix_client"] 528 http = request.app["http_session"] 529 folder_path = series.get("path", "") 530 # trigger library scan so Jellyfin picks up the new file 531 await trigger_jellyfin_scan(http) 532 await asyncio.sleep(10) 533 jf_id = await lookup_jellyfin_id(http, "tv", tmdb_id) 534 links_plain, links_html = await make_media_links(folder_path, is_dir=True, jellyfin_id=jf_id) 535 plain = f"✅ {display}{ep_info} has been downloaded and is now available!\n{links_plain}" 536 html = f"✅ <b>{display}</b>{ep_info} has been downloaded and is now available!<br>{links_html}" 537 for room_id in rooms: 538 try: 539 await send_notice(client, room_id, plain, html) 540 except Exception as e: 541 log.warning(f"Failed to notify room {room_id}: {e}") 542 except Exception as e: 543 log.exception(f"Error handling Sonarr webhook: {e}") 544 545 return web.Response(text="ok") 546 547 548async def run(): 549 """Main bot loop.""" 550 client_config = AsyncClientConfig( 551 store_sync_tokens=True, 552 encryption_enabled=True, 553 ) 554 client = AsyncClient( 555 MATRIX_HOMESERVER, 556 MATRIX_USER_ID, 557 device_id=MATRIX_DEVICE_ID, 558 store_path=STORE_PATH, 559 config=client_config, 560 ) 561 client.access_token = MATRIX_ACCESS_TOKEN 562 client.user_id = MATRIX_USER_ID 563 client.load_store() 564 log.info(f"Crypto store loaded, olm={client.olm is not None}") 565 566 http = aiohttp.ClientSession() 567 568 # Do an initial sync BEFORE registering callbacks to skip old messages 569 log.info("Performing initial sync...") 570 resp = await client.sync(timeout=10000, full_state=True) 571 if hasattr(resp, "next_batch"): 572 log.info(f"Initial sync complete, next_batch: {resp.next_batch}") 573 else: 574 log.error(f"Initial sync failed: {resp}") 575 await http.close() 576 await client.close() 577 sys.exit(1) 578 579 # E2EE setup 580 if client.olm: 581 try: 582 log.info("Uploading device keys...") 583 key_upload = await client.keys_upload() 584 log.info(f"Key upload result: {key_upload}") 585 except Exception as e: 586 log.info(f"Key upload skipped: {e}") 587 588 # Trust all known device keys so we can decrypt messages 589 for user_id in client.device_store.users: 590 for device in client.device_store.active_user_devices(user_id): 591 if not client.olm.is_device_verified(device): 592 client.verify_device(device) 593 log.info(f"Verified device {device.device_id} of {user_id}") 594 else: 595 log.warning("Olm not available after sync — E2EE will not work") 596 597 # Register event callbacks only after initial sync 598 client.add_event_callback(lambda room, event: on_message(client, room, event, http), RoomMessageText) 599 client.add_event_callback(lambda room, event: on_invite(client, room, event), InviteMemberEvent) 600 601 # Start webhook server for Radarr/Sonarr notifications 602 app = web.Application() 603 app["matrix_client"] = client 604 app["http_session"] = http 605 app.router.add_post("/webhook/radarr", handle_radarr_webhook) 606 app.router.add_post("/webhook/sonarr", handle_sonarr_webhook) 607 runner = web.AppRunner(app) 608 await runner.setup() 609 site = web.TCPSite(runner, "127.0.0.1", WEBHOOK_PORT) 610 await site.start() 611 log.info(f"Webhook server listening on 127.0.0.1:{WEBHOOK_PORT}") 612 613 log.info(f"Bot {MATRIX_USER_ID} is running!") 614 615 try: 616 await client.sync_forever(timeout=30000, full_state=True) 617 except Exception: 618 log.exception("sync_forever crashed") 619 finally: 620 await runner.cleanup() 621 await http.close() 622 await client.close() 623 624 625def main(): 626 asyncio.run(run())