mastoposter-oss_images/mastoposter/__main__.py

109 lines
3.1 KiB
Python
Raw Normal View History

2022-08-24 08:09:41 +03:00
#!/usr/bin/env python3
from asyncio import run
from configparser import ConfigParser, ExtendedInterpolation
2022-11-01 13:04:31 +03:00
from logging import DEBUG, Formatter, StreamHandler, getLogger
from sys import stdout
from mastoposter import execute_integrations, load_integrations_from
from mastoposter.integrations import FilteredIntegration
2022-08-24 08:28:18 +03:00
from mastoposter.sources import websocket_source
2022-08-26 14:32:55 +03:00
from typing import AsyncGenerator, Callable, List
from mastoposter.types import Account, Status
from httpx import Client
from mastoposter.utils import normalize_config
WSOCK_TEMPLATE = "wss://{instance}/api/v1/streaming"
VERIFY_CREDS_TEMPLATE = "https://{instance}/api/v1/accounts/verify_credentials"
2022-08-24 08:09:41 +03:00
logger = getLogger()
2022-08-24 08:09:41 +03:00
2022-11-01 13:37:47 +03:00
def init_logger(loglevel: int = DEBUG):
2022-11-01 13:04:31 +03:00
stdout_handler = StreamHandler(stdout)
stdout_handler.setLevel(DEBUG)
formatter = Formatter("[%(asctime)s][%(levelname)5s:%(name)s] %(message)s")
stdout_handler.setFormatter(formatter)
logger.addHandler(stdout_handler)
2022-11-01 13:37:47 +03:00
logger.setLevel(loglevel)
2022-11-01 13:04:31 +03:00
2022-08-24 08:09:41 +03:00
async def listen(
source: Callable[..., AsyncGenerator[Status, None]],
drains: List[FilteredIntegration],
2022-08-24 08:09:41 +03:00
user: str,
/,
**kwargs,
):
logger.info("Starting listening...")
2022-08-24 08:09:41 +03:00
async for status in source(**kwargs):
logger.debug("Got status: %r", status)
2022-08-24 08:09:41 +03:00
if status.account.id != user:
continue
# TODO: add option/filter to handle that
if status.visibility in ("direct",):
logger.info(
"Skipping post %s (status.visibility=%r)",
status.uri,
status.visibility,
)
2022-08-24 08:09:41 +03:00
continue
# TODO: find a better way to handle threads
2022-08-24 08:09:41 +03:00
if (
status.in_reply_to_account_id is not None
and status.in_reply_to_account_id != user
):
logger.info(
"Skipping post %s because it's a reply to another person",
status.uri,
)
2022-08-24 08:09:41 +03:00
continue
await execute_integrations(status, drains)
2022-08-24 08:09:41 +03:00
def main(config_path: str):
2022-11-01 13:04:31 +03:00
init_logger()
conf = ConfigParser(interpolation=ExtendedInterpolation())
2022-08-24 08:09:41 +03:00
conf.read(config_path)
normalize_config(conf)
modules: List[FilteredIntegration] = load_integrations_from(conf)
2022-08-24 08:09:41 +03:00
logger.info("Loaded %d integrations", len(modules))
user_id: str = conf["main"]["user"]
if user_id == "auto":
logger.info("config.main.user is set to auto, getting user ID")
with Client() as c:
rq = c.get(
VERIFY_CREDS_TEMPLATE.format(**conf["main"]),
params={"access_token": conf["main"]["token"]},
)
account = Account.from_dict(rq.json())
user_id = account.id
logger.info("account.id=%s", user_id)
2022-08-24 08:09:41 +03:00
url = "wss://{}/api/v1/streaming".format(conf["main"]["instance"])
2022-08-24 08:09:41 +03:00
run(
listen(
websocket_source,
modules,
user_id,
2022-08-24 08:09:41 +03:00
url=url,
reconnect=conf["main"].getboolean("auto_reconnect", False),
2022-08-24 08:09:41 +03:00
list=conf["main"]["list"],
access_token=conf["main"]["token"],
)
)
if __name__ == "__main__":
from sys import argv
main(argv[1])