BIG refactoring
This commit is contained in:
+65
-125
@@ -1,173 +1,113 @@
|
||||
import logging
|
||||
import json
|
||||
import re
|
||||
import os
|
||||
import mimetypes
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, HTTPException, Response, BackgroundTasks
|
||||
from fastapi.responses import HTMLResponse, FileResponse, PlainTextResponse
|
||||
from telegram_client import TelegramClient
|
||||
from config import get_settings
|
||||
import mimetypes
|
||||
import os
|
||||
from rss_generator import generate_channel_rss
|
||||
from pyrogram import errors
|
||||
from feedgen.feed import FeedGenerator
|
||||
from post_parser import PostParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
client = TelegramClient()
|
||||
settings = get_settings()
|
||||
Config = get_settings()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
# Startup
|
||||
await client.start()
|
||||
yield
|
||||
# Shutdown
|
||||
await client.stop()
|
||||
|
||||
app = FastAPI(
|
||||
title="PyroTg Bridge",
|
||||
lifespan=lifespan
|
||||
)
|
||||
app = FastAPI( title="Pyrogram Bridge", lifespan=lifespan)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run( "api_server:app", host=settings["api_host"], port=settings["api_port"], reload=False)
|
||||
uvicorn.run("api_server:app", host=Config["api_host"], port=Config["api_port"], reload=True)
|
||||
|
||||
@app.get("/html/{channel}/{post_id}", response_class=HTMLResponse)
|
||||
@app.get("/post/html/{channel}/{post_id}", response_class=HTMLResponse)
|
||||
async def get_post_html(channel: str, post_id: int):
|
||||
try:
|
||||
post = await client.get_post(channel, post_id)
|
||||
if post.get("error"):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=post["details"]
|
||||
)
|
||||
if "error" in post:
|
||||
raise HTTPException(status_code=404, detail=post["details"])
|
||||
return post["html"]
|
||||
parser = PostParser(client.client)
|
||||
html_content = await parser.get_post(channel, post_id, 'html')
|
||||
if not html_content:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return html_content
|
||||
except Exception as e:
|
||||
logger.error(f"HTML endpoint error: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
error_message = f"Failed to get HTML post for channel {channel}, post_id {post_id}: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=500, detail=error_message) from e
|
||||
|
||||
|
||||
@app.get("/json/{channel}/{post_id}")
|
||||
@app.get("/post/json/{channel}/{post_id}")
|
||||
async def get_post(channel: str, post_id: int):
|
||||
try:
|
||||
data = await client.get_post(channel, post_id)
|
||||
if data.get("error"):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=data
|
||||
)
|
||||
return Response(
|
||||
content=json.dumps(data),
|
||||
media_type="application/json"
|
||||
)
|
||||
parser = PostParser(client.client)
|
||||
json_content = await parser.get_post(channel, post_id, 'json')
|
||||
if not json_content:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return json_content
|
||||
except Exception as e:
|
||||
logger.error(f"API error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail={
|
||||
"error": "post_retrieval_error",
|
||||
"message": str(e)
|
||||
}
|
||||
) from e
|
||||
error_message = f"Failed to get JSON post for channel {channel}, post_id {post_id}: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=500, detail=error_message) from e
|
||||
|
||||
@app.get("/status")
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "ok",
|
||||
"connected": client.client.is_connected
|
||||
}
|
||||
try:
|
||||
me = await client.client.get_me()
|
||||
return {
|
||||
"status": "ok",
|
||||
"tg_connected": client.client.is_connected,
|
||||
"tg_name": me.username,
|
||||
"tg_id": me.id,
|
||||
"tg_phone": me.phone_number,
|
||||
"tg_first_name": me.first_name,
|
||||
"tg_last_name": me.last_name,
|
||||
}
|
||||
except Exception as e:
|
||||
error_message = f"Failed to get health check: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=500, detail=error_message) from e
|
||||
|
||||
@app.get("/media/{file_id}")
|
||||
async def get_media(
|
||||
file_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
response: Response
|
||||
):
|
||||
async def get_media(file_id: str, background_tasks: BackgroundTasks):
|
||||
try:
|
||||
file_path = await client.download_media_file(file_id)
|
||||
file_path = await client.download_media_file(file_id)
|
||||
logger.info(f"Downloaded media file {file_id} to {file_path}")
|
||||
if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="Temporary file not found")
|
||||
|
||||
# Additional safety checks
|
||||
if not os.path.exists(file_path):
|
||||
raise HTTPException(status_code=404, detail="Temporary file not found")
|
||||
media_type, _ = mimetypes.guess_type(file_path) # Determine media type from file extension
|
||||
if not media_type: media_type = "application/octet-stream"
|
||||
|
||||
# Determine media type from file extension
|
||||
media_type, _ = mimetypes.guess_type(file_path)
|
||||
if not media_type:
|
||||
media_type = "application/octet-stream"
|
||||
|
||||
# Add cleanup task
|
||||
background_tasks.add_task(lambda: os.remove(file_path) if os.path.exists(file_path) else None)
|
||||
|
||||
return FileResponse(
|
||||
path=file_path,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Content-Disposition": f"inline; filename={os.path.basename(file_path)}"
|
||||
}
|
||||
)
|
||||
|
||||
headers = { "Content-Disposition": f"inline; filename={os.path.basename(file_path)}" }
|
||||
return FileResponse( path=file_path, media_type=media_type, headers=headers)
|
||||
except HTTPException:
|
||||
# Пробрасываем уже сформированные HTTPException как есть
|
||||
raise
|
||||
except errors.RPCError as e:
|
||||
logger.error(f"Media request RPC error {file_id}: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=404, detail="File not found in Telegram")
|
||||
raise HTTPException(status_code=404, detail="File not found in Telegram") from e
|
||||
except Exception as e:
|
||||
logger.error(f"Media request failed {file_id}: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Internal server error: {str(e)}"
|
||||
)
|
||||
error_message = f"Failed to get media for file_id {file_id}: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=500, detail=error_message) from e
|
||||
|
||||
@app.get("/rss/{channel}", response_class=PlainTextResponse)
|
||||
async def get_rss_feed(channel: str):
|
||||
@app.get("/rss/{channel}", response_class=Response)
|
||||
async def get_rss_feed(channel: str, limit: int = 20):
|
||||
try:
|
||||
# Get last 20 posts
|
||||
posts = await client.get_channel_posts(channel, limit=20)
|
||||
|
||||
# Create FeedGenerator
|
||||
fg = FeedGenerator()
|
||||
channel_title = posts[0].get('channel_title', channel) if posts else channel
|
||||
channel_icon = posts[0].get('channel_icon', '') if posts else ''
|
||||
|
||||
fg.title(channel_title)
|
||||
fg.link(href=f"https://t.me/{channel}", rel='alternate')
|
||||
fg.description(f'Telegram channel {channel} RSS feed')
|
||||
fg.language('ru-ru')
|
||||
|
||||
if channel_icon:
|
||||
fg.logo(f"{settings['pyrogram_bridge_url']}/media/{channel_icon}")
|
||||
fg.icon(f"{settings['pyrogram_bridge_url']}/media/{channel_icon}")
|
||||
|
||||
# Add channel metadata
|
||||
fg.id(f"{settings['pyrogram_bridge_url']}/rss/{channel}")
|
||||
fg.link(href=f"{settings['pyrogram_bridge_url']}/rss/{channel}", rel='self', type='application/rss+xml')
|
||||
|
||||
# Add posts
|
||||
for post in posts:
|
||||
fe = fg.add_entry()
|
||||
fe.id(f"{settings['pyrogram_bridge_url']}/html/{channel}/{post['id']}")
|
||||
fe.title(post['title'])
|
||||
fe.link(href=f"https://t.me/{channel}/{post['id']}")
|
||||
fe.pubDate(post['date'].astimezone(tz=None))
|
||||
fe.description(f"<![CDATA[{post['html']}]]>")
|
||||
fe.content(content=post['html'], type='CDATA')
|
||||
|
||||
# Add media enclosures
|
||||
for media in post.get('media', []):
|
||||
if media.get('url'):
|
||||
fe.enclosure(
|
||||
url=f"{settings['pyrogram_bridge_url']}/media/{media['url']}",
|
||||
type=media.get('type', 'image/jpeg'),
|
||||
length=str(media.get('size', 0))
|
||||
)
|
||||
|
||||
# Generate RSS
|
||||
rss = fg.rss_str(pretty=True)
|
||||
return Response(content=rss, media_type="application/xml")
|
||||
|
||||
rss_content = await generate_channel_rss(channel, client=client.client, limit=limit)
|
||||
return Response(content=rss_content, media_type="application/xml")
|
||||
except ValueError as e:
|
||||
error_message = f"Invalid parameters for RSS feed generation: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=400, detail=error_message) from e
|
||||
except Exception as e:
|
||||
logger.error(f"RSS generation error: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="RSS feed generation failed")
|
||||
error_message = f"Failed to generate RSS feed for channel {channel}: {str(e)}"
|
||||
logger.error(error_message)
|
||||
raise HTTPException(status_code=500, detail=error_message) from e
|
||||
|
||||
Reference in New Issue
Block a user