mastoposter-oss_images/mastoposter/__main__.py

127 lines
3.6 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
2023-01-26 13:44:30 +03:00
from logging import (
INFO,
Formatter,
Logger,
StreamHandler,
getLevelName,
getLogger,
)
2022-11-01 13:04:31 +03:00
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
def init_logger(loglevel: int = INFO):
2022-11-01 13:04:31 +03:00
stdout_handler = StreamHandler(stdout)
stdout_handler.setLevel(loglevel)
2022-11-01 13:04:31 +03:00
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)
2023-01-26 13:44:30 +03:00
for log in logger.manager.loggerDict.values():
if isinstance(log, Logger):
log.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):
2022-11-01 14:33:47 +03:00
logger.info("New status: %s", status.uri)
logger.debug("Got status: %r", status)
2022-08-24 08:09:41 +03:00
if status.account.id != user:
logger.info(
"Skipping status %s (account.id=%r != %r)",
status.uri,
status.account.id,
user,
)
2022-08-24 08:09:41 +03:00
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):
conf = ConfigParser(interpolation=ExtendedInterpolation())
2022-08-24 08:09:41 +03:00
conf.read(config_path)
2022-11-02 20:11:38 +03:00
init_logger(getLevelName(conf["main"].get("loglevel", "INFO")))
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
2022-11-01 14:33:47 +03:00
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])