add wildcard route

This commit is contained in:
odysseusmax 2020-09-10 16:16:16 +05:30
parent 3284d83efb
commit fcf5b580c6
4 changed files with 62 additions and 51 deletions

View File

@ -1,53 +1,12 @@
import asyncio
import pathlib
import logging import logging
import aiohttp_jinja2 from .main import Indexer
import jinja2 from .config import debug
from aiohttp import web
from .telegram import Client
from .routes import setup_routes
from .views import Views
from .config import host, port, session_string, api_id, api_hash, debug
TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates'
client = Client(session_string, api_id, api_hash)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
logging.getLogger("telethon").setLevel(logging.INFO if debug else logging.ERROR) logging.getLogger("telethon").setLevel(logging.INFO if debug else logging.ERROR)
logging.getLogger("aiohttp").setLevel(logging.INFO if debug else logging.ERROR) logging.getLogger("aiohttp").setLevel(logging.INFO if debug else logging.ERROR)
log = logging.getLogger("tg-index")
def setup_jinja(app): Indexer().run()
loader = jinja2.FileSystemLoader(str(TEMPLATES_ROOT))
aiohttp_jinja2.setup(app, loader=loader)
async def start():
await client.start()
log.debug("telegram client started!")
async def stop(app):
await client.disconnect()
log.debug("telegram client disconnected!")
async def init():
server = web.Application()
await start()
await setup_routes(server, Views(client))
setup_jinja(server)
server.on_cleanup.append(stop)
return server
def main():
loop = asyncio.get_event_loop()
app = loop.run_until_complete(init())
web.run_app(app, host=host, port=port)
main()

47
app/main.py Normal file
View File

@ -0,0 +1,47 @@
import asyncio
import pathlib
import logging
import aiohttp_jinja2
import jinja2
from aiohttp import web
from .telegram import Client
from .routes import setup_routes
from .views import Views
from .config import host, port, session_string, api_id, api_hash, debug
log = logging.getLogger(__name__)
class Indexer:
TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates'
def __init__(self):
self.server = web.Application()
self.loop = asyncio.get_event_loop()
self.tg_client = Client(session_string, api_id, api_hash)
async def startup(self):
await self.tg_client.start()
log.debug("telegram client started!")
await setup_routes(self.server, Views(self.tg_client))
loader = jinja2.FileSystemLoader(str(self.TEMPLATES_ROOT))
aiohttp_jinja2.setup(self.server, loader=loader)
self.server.on_cleanup.append(self.cleanup)
async def cleanup(self, *args):
await self.tg_client.disconnect()
log.debug("telegram client disconnected!")
def run(self):
self.loop.run_until_complete(self.startup())
web.run_app(self.server, host=host, port=port)

View File

@ -58,7 +58,7 @@ async def setup_routes(app, handler):
if not alias_id: if not alias_id:
continue continue
p = f"/{alias_id}" p = r"/{chat:" + alias_id + "}"
p_api = '/api' + p p_api = '/api' + p
r = [ r = [
web.get(p, h.index), web.get(p, h.index),
@ -76,7 +76,7 @@ async def setup_routes(app, handler):
for chat_id in include_chats: for chat_id in include_chats:
chat = await client.get_entity(chat_id) chat = await client.get_entity(chat_id)
alias_id = generate_alias_id(chat) alias_id = generate_alias_id(chat)
p = f"/{alias_id}" p = r"/{chat:" + alias_id + "}"
p_api = '/api' + p p_api = '/api' + p
r = [ r = [
web.get(p, h.index), web.get(p, h.index),
@ -90,4 +90,5 @@ async def setup_routes(app, handler):
] ]
routes += r routes += r
log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}") log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}")
routes.append(web.view(r'/{wildcard:.*}', h.wildcard))
app.add_routes(routes) app.add_routes(routes)

View File

@ -33,6 +33,10 @@ class Views:
return {'chats':chats} return {'chats':chats}
async def wildcard(self, req):
raise web.HTTPFound('/')
@aiohttp_jinja2.template('home.html') @aiohttp_jinja2.template('home.html')
async def home(self, req): async def home(self, req):
if len(chat_ids) == 1: if len(chat_ids) == 1:
@ -57,7 +61,7 @@ class Views:
async def _index(self, req, api=False): async def _index(self, req, api=False):
alias_pos = 2 if api else 1 alias_pos = 2 if api else 1
alias_id = req.rel_url.path.split('/')[alias_pos] alias_id = req.match_info['chat'] #req.rel_url.path.split('/')[alias_pos]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id'] chat_id = chat['chat_id']
chat_name = chat['title'] chat_name = chat['title']
@ -164,7 +168,7 @@ class Views:
async def _info(self, req, api=False): async def _info(self, req, api=False):
file_id = int(req.match_info["id"]) file_id = int(req.match_info["id"])
alias_pos = 2 if api else 1 alias_pos = 2 if api else 1
alias_id = req.rel_url.path.split('/')[alias_pos] alias_id = req.match_info['chat'] #req.rel_url.path.split('/')[alias_pos]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id'] chat_id = chat['chat_id']
try: try:
@ -245,7 +249,7 @@ class Views:
async def logo(self, req): async def logo(self, req):
alias_id = req.rel_url.path.split('/')[1] alias_id = req.match_info['chat'] # req.rel_url.path.split('/')[1]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id'] chat_id = chat['chat_id']
chat_name = "Image not available" chat_name = "Image not available"
@ -298,7 +302,7 @@ class Views:
async def thumbnail_get(self, req): async def thumbnail_get(self, req):
file_id = int(req.match_info["id"]) file_id = int(req.match_info["id"])
alias_id = req.rel_url.path.split('/')[1] alias_id = req.match_info['chat'] #req.rel_url.path.split('/')[1]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id'] chat_id = chat['chat_id']
try: try:
@ -355,7 +359,7 @@ class Views:
async def handle_request(self, req, head=False): async def handle_request(self, req, head=False):
file_id = int(req.match_info["id"]) file_id = int(req.match_info["id"])
alias_id = req.rel_url.path.split('/')[1] alias_id = req.match_info['chat'] # req.rel_url.path.split('/')[1]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id'] chat_id = chat['chat_id']