fixed file naming thingy

This commit is contained in:
2025-11-06 21:53:32 +13:00
parent 6d9a078656
commit 8f8e2c744d
9 changed files with 541 additions and 15 deletions
+209 -5
View File
@@ -14,6 +14,7 @@ from .database import get_db
from .models import ScheduledTask, TaskExecutionHistory
from .scheduler import schedule_task, unschedule_task, calculate_next_run
from .task_queue import task_queue
from .auth import get_oauth_manager
logger = logging.getLogger(__name__)
@@ -34,6 +35,8 @@ class ScheduledTaskCreate(BaseModel):
run_time: str = Field(..., pattern="^([01]?[0-9]|2[0-3]):[0-5][0-9]$") # HH:MM format
timezone: str = Field(default="UTC")
auth_state: Optional[str] = None
upvoted: bool = False
saved: bool = False
class ScheduledTaskUpdate(BaseModel):
@@ -67,7 +70,10 @@ class ScheduledTaskResponse(BaseModel):
updated_at: str
last_run_at: Optional[str]
next_run_at: Optional[str]
auth_state: Optional[str]
upvoted: bool
saved: bool
class Config:
from_attributes = True
@@ -124,7 +130,9 @@ async def create_scheduled_task(task_data: ScheduledTaskCreate, db: Session = De
schedule_frequency="daily",
run_time=run_time_obj,
timezone=task_data.timezone,
auth_state=task_data.auth_state
auth_state=task_data.auth_state,
upvoted=task_data.upvoted,
saved=task_data.saved
)
# Calculate next run time
@@ -162,6 +170,10 @@ async def list_scheduled_tasks(db: Session = Depends(get_db)):
tasks = db.query(ScheduledTask).order_by(ScheduledTask.created_at.desc()).all()
return [task.to_dict() for task in tasks]
except Exception as e:
if "no such column" in str(e):
logger.warning(f"Database schema is outdated: {e}")
# Return empty list if schema is outdated
return []
logger.error(f"Failed to list scheduled tasks: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
@@ -444,7 +456,7 @@ async def get_queue_status():
"""Get current task queue status"""
try:
status = task_queue.get_queue_status()
# Get details of current task if any
current_task_info = None
if status['current_task']:
@@ -459,16 +471,208 @@ async def get_queue_status():
}
finally:
db.close()
return {
'queue_size': status['queue_size'],
'is_processing': status['is_processing'],
'current_task': current_task_info
}
except Exception as e:
logger.error(f"Failed to get queue status: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to get queue status"
)
@router.post("/create-likes", response_model=ScheduledTaskResponse, status_code=status.HTTP_201_CREATED)
async def create_likes_task(
limit: int = 25,
sort: str = "hot",
download_mode: str = "download",
run_now: bool = False,
run_time: str = "02:00",
timezone: str = "UTC",
auth_state: str = None,
db: Session = Depends(get_db)
):
"""
Create a scheduled task to download the user's liked posts.
"""
try:
# Get current username from auth
if not auth_state:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Authentication required"
)
oauth_manager = get_oauth_manager()
auth_status = oauth_manager.get_auth_status(auth_state)
if not auth_status["authenticated"]:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication"
)
username = auth_status["username"]
task_name = f"{username} - Liked posts"
# Validate timezone
try:
pytz.timezone(timezone)
except pytz.exceptions.UnknownTimeZoneError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid timezone: {timezone}"
)
# Parse run_time
hour, minute = map(int, run_time.split(':'))
run_time_obj = time_type(hour=hour, minute=minute)
# Create task
task = ScheduledTask(
name=task_name,
enabled=True,
source_type="user",
source_name=username,
download_mode=download_mode,
limit=limit,
sort=sort,
time_filter="day",
no_dupes=True,
simple_check=False,
schedule_frequency="daily",
run_time=run_time_obj,
timezone=timezone,
auth_state=auth_state,
upvoted=True,
saved=False
)
# Calculate next run time
task.next_run_at = calculate_next_run(task)
# Save to database
db.add(task)
db.commit()
db.refresh(task)
# Schedule the task
schedule_task(task)
# If run_now is True, queue it immediately
if run_now:
await task_queue.add_task(task.id, priority=1)
logger.info(f"Created likes task {task.id}: {task.name}")
return task.to_dict()
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to create likes task: {e}", exc_info=True)
db.rollback()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to create likes task: {str(e)}"
)
@router.post("/create-saved", response_model=ScheduledTaskResponse, status_code=status.HTTP_201_CREATED)
async def create_saved_task(
limit: int = 25,
sort: str = "hot",
download_mode: str = "download",
run_now: bool = False,
run_time: str = "02:00",
timezone: str = "UTC",
auth_state: str = None,
db: Session = Depends(get_db)
):
"""
Create a scheduled task to download the user's saved posts.
"""
try:
# Get current username from auth
if not auth_state:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Authentication required"
)
oauth_manager = get_oauth_manager()
auth_status = oauth_manager.get_auth_status(auth_state)
if not auth_status["authenticated"]:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication"
)
username = auth_status["username"]
task_name = f"{username} - Saved posts"
# Validate timezone
try:
pytz.timezone(timezone)
except pytz.exceptions.UnknownTimeZoneError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid timezone: {timezone}"
)
# Parse run_time
hour, minute = map(int, run_time.split(':'))
run_time_obj = time_type(hour=hour, minute=minute)
# Create task
task = ScheduledTask(
name=task_name,
enabled=True,
source_type="user",
source_name=username,
download_mode=download_mode,
limit=limit,
sort=sort,
time_filter="day",
no_dupes=True,
simple_check=False,
schedule_frequency="daily",
run_time=run_time_obj,
timezone=timezone,
auth_state=auth_state,
upvoted=False,
saved=True
)
# Calculate next run time
task.next_run_at = calculate_next_run(task)
# Save to database
db.add(task)
db.commit()
db.refresh(task)
# Schedule the task
schedule_task(task)
# If run_now is True, queue it immediately
if run_now:
await task_queue.add_task(task.id, priority=1)
logger.info(f"Created saved task {task.id}: {task.name}")
return task.to_dict()
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to create saved task: {e}", exc_info=True)
db.rollback()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to create saved task: {str(e)}"
)