diff --git a/src/iSponsorBlockTV/main.py b/src/iSponsorBlockTV/main.py index bb8f1a2..09a8a66 100644 --- a/src/iSponsorBlockTV/main.py +++ b/src/iSponsorBlockTV/main.py @@ -131,7 +131,6 @@ class DeviceListener: await asyncio.create_task(self.api_helper.mark_viewed_segments(uuids)) await asyncio.create_task(self.lounge_controller.seek_to(position)) - # Stops the connection to the device async def cancel(self): self.cancelled = True try: @@ -140,10 +139,14 @@ class DeviceListener: pass -async def finish(devices): - for i in devices: - await i.cancel() +async def finish(devices, web_session, tcp_connector): + for device in devices: + await device.cancel() + await web_session.close() + await tcp_connector.close() +def handle_signal(signum, frame): + raise KeyboardInterrupt() def main(config, debug): loop = asyncio.get_event_loop_policy().get_event_loop() @@ -160,11 +163,15 @@ def main(config, debug): devices.append(device) tasks.append(loop.create_task(device.loop())) tasks.append(loop.create_task(device.refresh_auth_loop())) - signal(SIGINT, lambda s, f: loop.stop()) - signal(SIGTERM, lambda s, f: loop.stop()) - loop.run_forever() - print("Cancelling tasks and exiting...") - loop.run_until_complete(finish(devices)) - loop.run_until_complete(web_session.close()) - loop.run_until_complete(tcp_connector.close()) - loop.close() + signal(SIGTERM, handle_signal) + signal(SIGINT, handle_signal) + try: + loop.run_forever() + except KeyboardInterrupt: + print("Cancelling tasks and exiting...") + for task in tasks: + task.cancel() + loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) + loop.run_until_complete(finish(devices, web_session, tcp_connector)) + finally: + loop.close()