diff --git a/app/damination.py b/app/damination.py index 2bfd89a..6992dde 100644 --- a/app/damination.py +++ b/app/damination.py @@ -79,17 +79,20 @@ class DaminationAPI(): self.connections = {} self.processing_tasks = [] - async def init_widget(self): + async def initialize_widgets(self): + widgets = config.get("widget", "ids").split(",") if config.has_option("widget", "ids"): - for widget in config.get("widget", "ids").split(","): - await self.add_widget_id_and_start_fetching(widget) + for widget in widgets: + await self.add_widget_and_start_fetching_notifications(widget) + + logger.info(f"initialize wigets : {widgets}") async def process_notification(self): while True: - donate = await self.pop_from_queue() + donate = await self.pop_notification_from_queue() if donate is not None: for widget_id, value in donate.items(): - await self.notify_subscribers(widget_id, value) + await self.send_notifications_to_subscribers(widget_id, value) else: break @@ -152,7 +155,7 @@ class DaminationAPI(): logger.error(e) - async def fetch_alerts(self, queue, widget_id: str): + async def fetch_notifications(self, queue, widget_id: str): """ 주어진 widget_id에 대한 알림을 가져와 queue에 저장합니다. 연결이 끊어지면 최대 MAX_RETRIES 횟수만큼 재시도합니다. @@ -188,7 +191,7 @@ class DaminationAPI(): await queue.put({widget_id: json.loads(reformed_data.json().encode('utf-8').decode('unicode_escape'))}) - except asyncio.CancelledError: # 추가: 취소 예외 처리 + except asyncio.CancelledError: logger.info(f"Widget {widget_id} fetching task was cancelled.") break @@ -216,7 +219,7 @@ class DaminationAPI(): return payload - async def add_widget_id_and_start_fetching(self, widget_id: str) -> bool: + async def add_widget_and_start_fetching_notifications(self, widget_id: str) -> bool: """ 주어진 widget_id를 위젯 ID 목록에 추가하고 알림을 가져오는 작업을 시작합니다. widget_id: 추가할 위젯 ID @@ -224,7 +227,7 @@ class DaminationAPI(): if widget_id not in self.WIDGET_IDS: self.add_widget_id(widget_id) - task = asyncio.create_task(self.fetch_alerts(self.queue, widget_id)) + task = asyncio.create_task(self.fetch_notifications(self.queue, widget_id)) self.fetch_tasks.append(task) return True @@ -232,7 +235,7 @@ class DaminationAPI(): logger.warning(f"Widget ID {widget_id} already exists in the list.") return False - async def remove_widget_id_and_stop_fetching(self, widget_id: str): + async def remove_widget_and_stop_fetching_notifications(self, widget_id: str): """ 주어진 widget_id를 위젯 ID 목록에서 제거하고 알림을 가져오는 작업을 중단합니다. widget_id: 제거할 위젯 ID @@ -247,7 +250,7 @@ class DaminationAPI(): logger.warning(f"Widget ID {widget_id} not found.") - async def pop_from_queue(self): + async def pop_notification_from_queue(self): """ queue에서 가장 먼저 저장된 항목을 꺼내어 반환합니다. queue가 비어있는 경우 None을 반환합니다. @@ -274,18 +277,18 @@ class DaminationAPI(): else: return [] - async def notify_subscribers(self, widget_id: str, donate): + async def send_notifications_to_subscribers(self, widget_id: str, donate): """ 주어진 widget_id에 해당하는 모든 구독자들에게 알림을 전송합니다. widget_id: 알림을 보낼 구독자들의 위젯 ID donate: 전송할 알림 데이터 """ subscribers = self.get_subscribers(widget_id) - tasks = [asyncio.create_task(self.send_webhook(await self.get_connection(subscriber_url), subscriber_url, donate)) for subscriber_url in subscribers] # 변경: self.get_connection() 사용 + tasks = [asyncio.create_task(self.send_notification_webhook(await self.get_connection(subscriber_url), subscriber_url, donate)) for subscriber_url in subscribers] await asyncio.gather(*tasks) - async def send_webhook(self, session, subscriber_url, donate): + async def send_notification_webhook(self, session, subscriber_url, donate): payload = { "text": f"**{donate['content']['name']}({donate['content']['account']})**\n{donate}", "data": donate @@ -298,7 +301,7 @@ class DaminationAPI(): logger.error(f"Failed to send notification to {subscriber_url} with status code {response.status}.") async def run(self): - await self.init_widget() + await self.initialize_widgets() while True: if not self.queue.empty(): diff --git a/app/main.py b/app/main.py index 78367ee..c03a0e5 100644 --- a/app/main.py +++ b/app/main.py @@ -1,4 +1,3 @@ - import asyncio from aiohttp import web from damination import DaminationAPI @@ -9,6 +8,11 @@ toonat = DaminationAPI() app = web.Application() +@routes.get('/get_subscriber') +async def get_widgets(request): + subscribers = toonat.get_subscribers() + return web.json_response(subscribers) + @routes.get('/subscribe/{widget_id}/{url}') async def subscribe(request): widget_id = request.match_info['widget_id'] @@ -29,19 +33,6 @@ async def unsubscribe(request): else: return web.Response(text=f"Not subscribed to widget ID {widget_id} with URL {url}.") -@routes.get('/init_widget_id') -async def init_widget_id(request): - if not toonat.WIDGET_IDS: - widget_id = request.query.get("widget_id") - if widget_id: - toonat.WIDGET_IDS.append(widget_id) - return web.Response(text=f"Widget ID {widget_id} added.") - else: - return web.Response(text="Invalid widget ID. Please try again.") - else: - return web.Response(text="Widget ID already exists.") - - @routes.get('/get_widgets') async def get_widgets(request): """ @@ -58,11 +49,8 @@ async def add_widget(request): widget_id: 추가할 위젯 ID """ widget_id = request.match_info['widget_id'] - result = await toonat.add_widget_id_and_start_fetching(widget_id) - if result: - return web.Response(text=f"Widget ID {widget_id} added and fetching started.") - else: - return web.Response(text=f"Widget ID {widget_id} already exists in the list.") + 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/{widget_id}') async def remove_widget(request): @@ -71,7 +59,7 @@ async def remove_widget(request): widget_id: 제거할 위젯 ID """ widget_id = request.match_info['widget_id'] - await toonat.remove_widget_id_and_stop_fetching(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') @@ -101,7 +89,6 @@ async def main(): # 웹 서버를 실행합니다. web_server_task = asyncio.create_task(web_server(app)) - # 두 작업을 병렬로 실행하지 않고 순서대로 처리합니다. await api_task await web_server_task @@ -110,6 +97,6 @@ async def main(): 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/init_widget_id?widget_id=YOUR_WIDGET_ID)") + print("Please enter the widget ID via web endpoint (http://localhost/add_widget/YOUR_WIDGET_ID)") asyncio.run(main())