luoxu-analytics-plugin/__init__.py

46 lines
1.3 KiB
Python
Raw Normal View History

2023-09-14 13:24:36 +00:00
import logging
from aiohttp import web
from telethon import TelegramClient
from telethon.errors import ChannelPrivateError
from .group_data import get_group_data
logger = logging.getLogger('luoxu_plugins.analytics')
class GroupAnalyticsHandler:
2023-09-14 14:21:47 +00:00
def __init__(self, client, db):
2023-09-14 13:24:36 +00:00
self.client = client
2023-09-14 14:21:47 +00:00
self.db = db
2023-09-14 13:24:36 +00:00
async def get(self, request: web.Request):
2023-09-14 13:37:38 +00:00
if cid_str := request.query.get('cid'):
2023-09-14 13:24:36 +00:00
try:
uid = int(cid_str)
await self.client.get_entity(uid)
except (ValueError, ChannelPrivateError):
raise web.HTTPForbidden(headers={
'Cache-Control': 'public, max-age=86400',
})
2023-09-14 14:21:47 +00:00
return web.json_response(await get_group_data(uid, self.client, self.db))
2023-09-14 13:24:36 +00:00
else:
raise web.HTTPNotFound
async def register(indexer, client: TelegramClient):
2023-09-14 13:32:22 +00:00
port: int = int(indexer.config['plugin']['analytics']['port'])
2023-09-14 13:24:36 +00:00
2023-09-14 14:21:47 +00:00
handler = GroupAnalyticsHandler(client, indexer.dbstore)
2023-09-14 13:24:36 +00:00
app = web.Application()
app.router.add_get('/api/group_analytics', handler.get)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(
runner,
2024-02-14 14:16:13 +00:00
indexer.config['web']['listen_host'], port,
2023-09-14 13:24:36 +00:00
)
await site.start()