2020-09-10 12:46:16 +02:00
|
|
|
import asyncio
|
|
|
|
import pathlib
|
|
|
|
import logging
|
|
|
|
|
|
|
|
import aiohttp_jinja2
|
|
|
|
import jinja2
|
|
|
|
from aiohttp import web
|
2021-06-13 13:01:23 +02:00
|
|
|
from aiohttp_session import session_middleware
|
|
|
|
from aiohttp_session.cookie_storage import EncryptedCookieStorage
|
2020-09-10 12:46:16 +02:00
|
|
|
|
|
|
|
from .telegram import Client
|
|
|
|
from .routes import setup_routes
|
2021-05-22 16:00:08 +02:00
|
|
|
from .views import Views, middleware_factory
|
|
|
|
from .config import (
|
|
|
|
host,
|
|
|
|
port,
|
|
|
|
session_string,
|
|
|
|
api_id,
|
|
|
|
api_hash,
|
|
|
|
authenticated,
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
SESSION_COOKIE_LIFETIME,
|
|
|
|
SECRET_KEY,
|
|
|
|
)
|
2020-09-10 12:46:16 +02:00
|
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class Indexer:
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2021-05-22 16:00:08 +02:00
|
|
|
TEMPLATES_ROOT = pathlib.Path(__file__).parent / "templates"
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
def __init__(self):
|
2021-05-22 16:00:08 +02:00
|
|
|
self.server = web.Application(
|
|
|
|
middlewares=[
|
2021-06-13 13:01:23 +02:00
|
|
|
session_middleware(
|
|
|
|
EncryptedCookieStorage(
|
|
|
|
secret_key=SECRET_KEY.encode(),
|
|
|
|
max_age=60 * SESSION_COOKIE_LIFETIME,
|
|
|
|
cookie_name="TG_INDEX_SESSION"
|
|
|
|
)
|
|
|
|
),
|
2021-05-22 16:00:08 +02:00
|
|
|
middleware_factory(),
|
|
|
|
]
|
|
|
|
)
|
2020-09-10 12:46:16 +02:00
|
|
|
self.loop = asyncio.get_event_loop()
|
|
|
|
self.tg_client = Client(session_string, api_id, api_hash)
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2021-05-22 16:00:08 +02:00
|
|
|
self.server["is_authenticated"] = authenticated
|
|
|
|
self.server["username"] = username
|
|
|
|
self.server["password"] = password
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
async def startup(self):
|
|
|
|
await self.tg_client.start()
|
|
|
|
log.debug("telegram client started!")
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
await setup_routes(self.server, Views(self.tg_client))
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
loader = jinja2.FileSystemLoader(str(self.TEMPLATES_ROOT))
|
|
|
|
aiohttp_jinja2.setup(self.server, loader=loader)
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
self.server.on_cleanup.append(self.cleanup)
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
async def cleanup(self, *args):
|
|
|
|
await self.tg_client.disconnect()
|
|
|
|
log.debug("telegram client disconnected!")
|
2020-09-19 13:31:57 +02:00
|
|
|
|
2020-09-10 12:46:16 +02:00
|
|
|
def run(self):
|
|
|
|
self.loop.run_until_complete(self.startup())
|
|
|
|
web.run_app(self.server, host=host, port=port)
|