Skip to content

Commit

Permalink
fix(parsing/tgraph): unclosed session when exit
Browse files Browse the repository at this point in the history
Signed-off-by: Rongrong <i@rong.moe>
  • Loading branch information
Rongronggg9 committed May 21, 2022
1 parent 6a45a7e commit 87d988b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
13 changes: 8 additions & 5 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import uvloop

uvloop.install()
except ImportError: # uvloop do not support Windows
except ImportError: # uvloop does not support Windows
uvloop = None

from functools import partial
Expand Down Expand Up @@ -43,7 +43,10 @@ def init():
api_keys = {env.API_ID: env.API_HASH}

# pre tasks
pre_tasks.append(loop.create_task(db.init()))
pre_tasks.extend((
loop.create_task(db.init()),
loop.create_task(tgraph.init()),
))

if env.PORT:
# enable redirect server for Railway, Heroku, etc
Expand Down Expand Up @@ -232,12 +235,14 @@ async def pre():


async def post():
await db.close()
await asyncio.gather(db.close(), tgraph.close())


def main():
init()

loop.run_until_complete(pre())

logger.info(f"RSS-to-Telegram-Bot ({', '.join(env.VERSION.split())}) started!\n"
f"MANAGER: {env.MANAGER}\n"
f"T_PROXY (for Telegram): {env.TELEGRAM_PROXY or 'not set'}\n"
Expand All @@ -250,8 +255,6 @@ def main():
logger.warning('Bot manager privileged mode is enabled! '
'Use with caution and should be disabled in production!')

loop.run_until_complete(pre())

scheduler = AsyncIOScheduler(event_loop=loop)
scheduler.add_job(func=command.monitor.run_monitor_task,
trigger=CronTrigger(minute='*', second=env.CRON_SECOND, timezone='UTC'),
Expand Down
31 changes: 23 additions & 8 deletions src/parsing/tgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@

logger = log.getLogger('RSStT.tgraph')

apis: Optional[APIs] = None


async def init():
global apis
if env.TELEGRAPH_TOKEN:
apis = APIs(env.TELEGRAPH_TOKEN)
await apis.init()
if not apis.valid:
logger.error('Set up Telegraph failed, fallback to non-Telegraph mode.')
apis = None


async def close():
global apis
if apis:
await apis.close()
apis = None


class Telegraph(aiograph.Telegraph):
def __init__(self, token=None):
Expand Down Expand Up @@ -71,7 +90,6 @@ def __init__(self, tokens: Union[str, list[str]]):
self.tokens = tokens
self._accounts: list[Telegraph] = []
self._curr_id = 0
env.loop.run_until_complete(self.init())

async def init(self):
for token in self.tokens:
Expand All @@ -96,6 +114,10 @@ async def init(self):
except Exception as e:
logger.warning('Cannot set up one of Telegraph accounts: ' + str(e), exc_info=e)

async def close(self):
for account in self._accounts:
await account.close()

@property
def valid(self):
return bool(self._accounts)
Expand All @@ -113,13 +135,6 @@ def get_account(self) -> Telegraph:
return self._accounts[curr_id]


apis = None
if env.TELEGRAPH_TOKEN:
apis = APIs(env.TELEGRAPH_TOKEN)
if not apis.valid:
logger.error('Cannot set up Telegraph, fallback to non-Telegraph mode.')
apis = None

TELEGRAPH_ALLOWED_TAGS: Final = {
'a', 'aside', 'b', 'blockquote', 'br', 'code', 'em', 'figcaption', 'figure',
'h3', 'h4', 'hr', 'i', 'iframe', 'img', 'li', 'ol', 'p', 'pre', 's',
Expand Down

0 comments on commit 87d988b

Please sign in to comment.