mastoposter-oss_images/mastoposter/__main__.py

141 lines
4.4 KiB
Python
Raw Normal View History

2022-08-24 08:09:41 +03:00
#!/usr/bin/env python3
"""
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
2022-08-24 08:09:41 +03:00
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,
)
2023-05-08 17:04:32 +03:00
from sys import argv, 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
2023-03-07 10:26:45 +03:00
from httpx import Client, HTTPTransport
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
2023-05-08 17:04:32 +03:00
def main(config_path: str = argv[1]):
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)
2023-03-07 10:26:45 +03:00
retries: int = conf["main"].getint("http-retries", 5)
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")
2023-03-07 10:26:45 +03:00
with Client(transport=HTTPTransport(retries=retries)) 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),
2023-03-07 10:26:45 +03:00
reconnect_delay=conf["main"].getfloat("reconnect_delay", 1.0),
2022-08-24 08:09:41 +03:00
list=conf["main"]["list"],
access_token=conf["main"]["token"],
)
)
if __name__ == "__main__":
2023-05-08 17:04:32 +03:00
main()