Something went wrong. Try again.
a fork of EvalEx by ezylang with a handful of breaking changes
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import argparseimport asyncioimport jsonimport queueimport shutilimport threadingfrom collections.abc import Callablefrom pathlib import Pathfrom typing import Any
import envfrom database.connection import DatabasePoolfrom database.migrations import DatabaseMigratorfrom util.util import LOGGER, read_env, shutdown_hook
EXAMPLE_CONFIG = { "services": [ { "input": {"type": "bluesky-jetstream", "handle": "bsky.app"}, "outputs": [ { "type": "mastodon", "instance": "https://mastodon.social", "token": "env:MASTODON_TOKEN", } ], } ]}
def dump_example_config() -> None: env.SETTINGS_DIR.parent.mkdir(parents=True, exist_ok=True) with open(env.SETTINGS_DIR, "w") as f: json.dump(EXAMPLE_CONFIG, f, indent=2)
def flush_caches() -> None: from atproto.store import flush_caches as flush_atproto_caches from atproto.store import get_store
db_pool = DatabasePool(env.DATABASE_DIR) get_store(db_pool)
LOGGER.info("Flushing atproto caches...") sessions, identities = flush_atproto_caches() LOGGER.info("Flushed %d sessions and %d identities", sessions, identities) LOGGER.info("Cache flush complete!")
db_pool.close()
def main() -> None: parser = argparse.ArgumentParser( description="xpost: social media crossposting tool" ) parser.add_argument( "--flush-caches", action="store_true", help="Flush all caches (like sessions and identities)", ) args = parser.parse_args()
if args.flush_caches: flush_caches() return
def _test_binary(binary: str) -> bool: if "/" in binary or "\\" in binary: return Path(binary).exists() return shutil.which(binary) is not None
if not _test_binary(env.FFMPEG_PATH): LOGGER.error( "ffmpeg is required to crosspost media, but was not found!", env.FFMPEG_PATH ) return if not _test_binary(env.FFPROBE_PATH): LOGGER.error( "ffprobe is required to crosspost media, but was not found!", env.FFPROBE_PATH, ) return
if not env.DATA_DIR.exists(): env.DATA_DIR.mkdir(parents=True)
if not env.SETTINGS_DIR.exists(): LOGGER.info("First launch detected! Creating %s and exiting!", env.SETTINGS_DIR) dump_example_config() LOGGER.info("Example config written to %s", env.SETTINGS_DIR) LOGGER.info("Please edit the config file and run again!") return
migrator = DatabaseMigrator(env.DATABASE_DIR, env.MIGRATIONS_DIR) try: migrator.migrate() except Exception: LOGGER.exception("Failed to migrate database!") return finally: migrator.close()
db_pool = DatabasePool(env.DATABASE_DIR) import httpx
http_client = httpx.Client(timeout=httpx.Timeout(30))
LOGGER.info("Bootstrapping registries...") from registry import create_input_service, create_output_service from registry_bootstrap import bootstrap
bootstrap()
LOGGER.info("Loading settings...")
with open(env.SETTINGS_DIR) as f: settings = json.load(f) read_env(settings)
if "services" not in settings: raise KeyError("No 'services' specified in settings!")
service_pairs: list[tuple[Any, list[Any]]] = [] for svc in settings["services"]: if "input" not in svc: raise KeyError("Each service must have an 'input' field!") if "outputs" not in svc: raise KeyError("Each service must have an 'outputs' field!")
inp = create_input_service(db_pool, http_client, svc["input"]) outs = [ create_output_service(db_pool, http_client, data) for data in svc["outputs"] ] service_pairs.append((inp, outs))
LOGGER.info("Starting task worker...")
def worker(task_queue: queue.Queue[Callable[[], None] | None]): while True: task = task_queue.get() if task is None: break
try: task() except Exception: LOGGER.exception("Exception in worker thread!") finally: task_queue.task_done()
task_queue: queue.Queue[Callable[[], None] | None] = queue.Queue() thread = threading.Thread(target=worker, args=(task_queue,), daemon=True) thread.start()
for inp, outs in service_pairs: inp.outputs = outs inp.submitter = lambda c: task_queue.put(c)
inputs = [inp for inp, _ in service_pairs] LOGGER.info("Starting %d input service(s)...", len(inputs)) try: asyncio.run(_run_all_inputs(inputs)) except KeyboardInterrupt: LOGGER.info("Stopping...")
task_queue.join() task_queue.put(None) thread.join()
for shook in shutdown_hook: shook()
db_pool.close() http_client.close()
async def _run_all_inputs(inputs: list[Any]) -> None: tasks = [asyncio.create_task(inp.listen()) for inp in inputs] await asyncio.gather(*tasks, return_exceptions=True)
if __name__ == "__main__": main()