]> git.treefish.org Git - mtxbot.git/blob - src/mtxbot.py
Fix presence shutdown
[mtxbot.git] / src / mtxbot.py
1 #!/usr/bin/env python3
2
3 import asyncio
4 import aiofiles
5 import json
6 import logging
7 import nio
8 import os
9 import signal
10 import stat
11 import time
12
13 import sys
14 assert sys.version_info >= (3, 5)
15
16 from presence import Presence
17
18 def handleInterrupt(sig, frame):
19     global stop
20     if os.getpid() == mainPid:
21         logging.info( "Got stop signal." )
22         stop = True
23         for presence in presences:
24             presence.stop()
25
26 async def main():
27     client = nio.AsyncClient(config['server']['url'], config['server']['user'])
28
29     try:
30         await client.login(config['server']['password'])
31
32         presence_tasks = []
33         for presence in presences:
34             presence_tasks.append( asyncio.create_task(presence.run(client)) )
35
36         done, pending = await asyncio.wait( presence_tasks,
37                                             return_when = asyncio.FIRST_EXCEPTION )
38
39         for presence in presences:
40             presence.stop()
41
42         for task in done:
43             try:
44                 task.result()
45             except Exception as e:
46                 logging.error( "Error running task: %s" % str(e) )
47
48     finally:
49         logging.info("Closing client...")
50         await client.close()
51
52 logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s',
53                     level=logging.INFO,
54                     datefmt='%m/%d/%Y %H:%M:%S')
55
56 mainPid = os.getpid()
57 signal.signal(signal.SIGINT, handleInterrupt)
58 signal.signal(signal.SIGTERM, handleInterrupt)
59
60 stop = False
61
62 if len(sys.argv) != 2:
63     print("Usage: %s <config json>" % sys.argv[0])
64     sys.exit(1)
65
66 with open(sys.argv[1]) as configFile:
67     config = json.load(configFile)
68
69 fifo_dir = os.getenv('MTXBOT_FIFO_DIR', '/run/mtxbot')
70
71 while not stop:
72     presences = []
73     for entry in os.listdir(fifo_dir):
74         fullpath = "%s/%s" % (fifo_dir, entry)
75         if stat.S_ISFIFO(os.stat(fullpath).st_mode):
76             logging.info("Creating presence for %s..." % entry)
77             presences.append( Presence(entry, fullpath) )
78     if len(presences) == 0:
79         logging.error("No fifos could be found!")
80         break
81     asyncio.run(main())
82     if not stop:
83         logging.warning("Main loop exited!")
84         logging.info("Restarting after grace period...")
85         time.sleep(3.0)