78 lines
1.9 KiB
Python
78 lines
1.9 KiB
Python
import os
|
|
import random
|
|
from pathlib import Path
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
from typing import List
|
|
|
|
app = FastAPI()
|
|
|
|
# CORS middleware
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
VIDEOS_DIR = Path(os.getenv("VIDEOS_DIR", "/videos"))
|
|
VIDEO_EXTENSIONS = {".mp4", ".webm", ".ogg", ".mov", ".avi", ".mkv"}
|
|
|
|
# Mount videos directory
|
|
if VIDEOS_DIR.exists():
|
|
app.mount("/videos", StaticFiles(directory=VIDEOS_DIR), name="videos")
|
|
|
|
|
|
def get_video_files() -> List[str]:
|
|
"""Get all video files from the videos directory."""
|
|
if not VIDEOS_DIR.exists():
|
|
return []
|
|
|
|
videos = [
|
|
f.name for f in VIDEOS_DIR.iterdir()
|
|
if f.is_file() and f.suffix.lower() in VIDEO_EXTENSIONS
|
|
]
|
|
return videos
|
|
|
|
|
|
@app.get("/api/health")
|
|
def health_check():
|
|
"""Health check endpoint."""
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/api/videos")
|
|
def get_videos(limit: int = 10):
|
|
"""Get a list of random videos."""
|
|
try:
|
|
videos = get_video_files()
|
|
|
|
if not videos:
|
|
return []
|
|
|
|
# Shuffle and get random videos
|
|
random.shuffle(videos)
|
|
selected = videos[:min(limit, len(videos))]
|
|
|
|
video_data = [
|
|
{
|
|
"id": f"{int(random.random() * 1e10)}-{i}",
|
|
"filename": video,
|
|
"url": f"/videos/{video}",
|
|
"title": Path(video).stem.replace("-", " ").replace("_", " "),
|
|
}
|
|
for i, video in enumerate(selected)
|
|
]
|
|
|
|
return video_data
|
|
except Exception as e:
|
|
print(f"Error reading videos: {e}")
|
|
return {"error": "Failed to load videos"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=3001)
|