Add flags endpoint

This commit is contained in:
vvzvlad
2025-04-11 02:04:58 +03:00
parent b59992cb22
commit f42e159ba6
2 changed files with 38 additions and 2 deletions
+22 -2
View File
@@ -31,6 +31,7 @@ from post_parser import PostParser
from url_signer import verify_media_digest, generate_media_digest
from starlette.middleware.base import BaseHTTPMiddleware
import json_repair
from typing import List
class RequestLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
@@ -283,7 +284,7 @@ async def download_media_file(channel: str, post_id: int, file_unique_id: str) -
json.dump(media_files_updated, f, ensure_ascii=False, indent=2)
logger.info(f"Removed invalid entry for {channel}/{post_id}/{file_unique_id} from media_file_ids.json")
else:
logger.warning(f"Entry for {channel}/{post_id}/{file_unique_id} not found in media_file_ids.json for removal")
logger.warning(f"Entry for {channel}/{post_id}/{file_unique_id} not found in media_file_ids.json for removal")
except Exception as e:
logger.error(f"Failed to remove entry for {channel}/{post_id}/{file_unique_id} from media_file_ids.json: {str(e)}")
@@ -719,4 +720,23 @@ async def get_rss_feed(channel: str,
except Exception as e:
error_message = f"rss_generation_error: channel {channel}, error {str(e)}"
logger.error(error_message)
raise HTTPException(status_code=500, detail=error_message) from e
raise HTTPException(status_code=500, detail=error_message) from e
@app.get("/flags", response_model=List[str])
@app.get("/flags/{token}", response_model=List[str])
async def get_available_flags(token: str | None = None, request: Request = None):
"""Returns a list of all possible flags that can be assigned to posts."""
if Config["token"] and request and request.client.host not in ["127.0.0.1", "localhost"]:
if token != Config["token"]:
logger.error(f"Invalid token for flags endpoint: {token}, expected: {Config['token']}")
raise HTTPException(status_code=403, detail="Invalid token")
else:
logger.info(f"Valid token for flags endpoint: {token}")
try:
flags = PostParser.get_all_possible_flags()
return flags
except Exception as e:
error_message = f"Failed to get flags list: {str(e)}"
logger.error(error_message)
raise HTTPException(status_code=500, detail=error_message) from e
+16
View File
@@ -12,6 +12,7 @@ import re
import os
import json
import html
import inspect
from datetime import datetime
from typing import Union, Dict, Any, List
@@ -67,6 +68,21 @@ class PostParser:
def __init__(self, client):
self.client = client
@staticmethod
def get_all_possible_flags() -> List[str]:
"""Dynamically extracts all possible flag names from the _extract_flags method."""
try:
source_code = inspect.getsource(PostParser._extract_flags)
# Find all occurrences of flags.append("flag_name")
flags = re.findall(r'flags\.append\("([^"]+)"\)', source_code)
# Return unique flags
return sorted(list(set(flags)))
except Exception as e:
logger.error(f"flag_extraction_error: Could not extract flags dynamically: {str(e)}")
# Fallback to a manually defined list might be needed here in case of error,
# but for now, we return an empty list.
return []
def channel_name_prepare(self, channel: str):
if isinstance(channel, str) and channel.startswith('-100'): # Convert numeric channel ID to int
channel_id = int(channel)