import asyncio from aiohttp import web from damination import DaminationAPI routes = web.RouteTableDef() toonat = DaminationAPI() app = web.Application() @routes.get('/get_subscriber/{widget_id}') async def get_widgets(request): widget_id = request.match_info['widget_id'] subscribers = toonat.get_subscribers(widget_id) if subscribers: return web.json_response(subscribers) else: return web.Response(text=f"no subscribers") @routes.get('/subscribe/{widget_id}') async def subscribe(request): """ 주어진 widget_id와 url로 구독을 추가합니다. """ widget_id = request.match_info['widget_id'] url = request.query['url'] success = toonat.add_subscriber(widget_id, url) if success: return web.Response(text=f"Subscribed to widget ID {widget_id} with URL {url}.") else: return web.Response(text=f"Already subscribed to widget ID {widget_id} with URL {url}.") @routes.get('/unsubscribe/{widget_id}') async def unsubscribe(request): """ 주어진 widget_id와 url로 구독을 취소합니다. """ widget_id = request.match_info['widget_id'] url = request.query['url'] success = toonat.remove_subscriber(widget_id, url) if success: return web.Response(text=f"Unsubscribed from widget ID {widget_id} with URL {url}.") else: return web.Response(text=f"Not subscribed to widget ID {widget_id} with URL {url}.") @routes.get('/get_widgets') async def get_widgets(request): """ 현재 설정된 모든 위젯 ID 목록을 반환하는 웹 API 엔드포인트입니다. """ widget_ids = toonat.get_widget_ids() if widget_ids: return web.json_response(widget_ids) else: return web.Response(text=f"no widget_ids") @routes.get('/add_widget') async def add_widget(request): """ 주어진 widget_id를 위젯 ID 목록에 추가하고 알림을 가져오는 작업을 시작하는 웹 API 엔드포인트입니다. widget_id: 추가할 위젯 ID """ widget_id = request.query['widget_id'] await toonat.add_widget_and_start_fetching_notifications(widget_id) return web.Response(text=f"Widget ID {widget_id} added and fetching started.") @routes.get('/remove_widget') async def remove_widget(request): """ 주어진 widget_id를 위젯 ID 목록에서 제거하고 알림을 가져오는 작업을 중단하는 웹 API 엔드포인트입니다. widget_id: 제거할 위젯 ID """ widget_id = request.query['widget_id'] await toonat.remove_widget_and_stop_fetching_notifications(widget_id) return web.Response(text=f"Widget ID {widget_id} removed and fetching stopped.") @routes.get('/status') async def status(request): """ 서버 상태를 확인하는 웹 API 엔드포인트입니다. 이 엔드포인트는 서버가 정상적으로 작동 중임을 확인하는 데 사용됩니다. """ return web.HTTPOk() async def web_server(app): """ aiohttp 웹 서버를 설정하고 시작하는 비동기 함수입니다. """ app.add_routes(routes) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, '0.0.0.0', 80) await site.start() async def main(): # DaminationAPI를 실행합니다. api_task = asyncio.create_task(toonat.run()) # 웹 서버를 실행합니다. web_server_task = asyncio.create_task(web_server(app)) await api_task await web_server_task if __name__ == "__main__": if not toonat.WIDGET_IDS: print("No widget ID found in settings.ini.") print("Please enter the widget ID via web endpoint (http://localhost/add_widget/YOUR_WIDGET_ID)") asyncio.run(main())