Spaces:
Running
Running
File size: 7,073 Bytes
0eeeed2 0f591cf 0eeeed2 3533fb9 91bc8a2 0eeeed2 3533fb9 0eeeed2 0f591cf 8ad8368 0f591cf 0eeeed2 0f591cf 3533fb9 0f591cf 0eeeed2 0f591cf 3533fb9 0f591cf 3533fb9 0f591cf 3533fb9 0f591cf 3533fb9 0eeeed2 3533fb9 0f591cf 3533fb9 0f591cf 0eeeed2 0f591cf 3533fb9 0f591cf 3533fb9 0f591cf 0eeeed2 0f591cf 0eeeed2 0f591cf 0eeeed2 0f591cf 0eeeed2 0f591cf 0eeeed2 3533fb9 0eeeed2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | from fastapi import APIRouter, Depends, Response, Query, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.core import config
from app.core.storage import storage
import re
import json
import xml.etree.ElementTree as ET
router = APIRouter()
BASE_URL = config.FRONTEND_URL.rstrip('/')
# Register namespace prefixes so ET serialises them correctly
_NS_SITEMAP = 'http://www.sitemaps.org/schemas/sitemap/0.9'
_NS_VIDEO = 'http://www.google.com/schemas/sitemap-video/1.1'
ET.register_namespace('', _NS_SITEMAP)
ET.register_namespace('video', _NS_VIDEO)
_VIDEOS_SQL = text("""
SELECT id, title, description, video_url, thumbnail_url, tags,
duration, created_at, owner_id, status
FROM videos
WHERE status = :status
""")
def _resolve_url(url):
"""Inline CDN resolver — avoids loading the full Video ORM (which may have columns not yet migrated)."""
return storage.resolve_cdn_url(url)
def _to_xml(root):
"""Serialize an ElementTree root to bytes with XML declaration."""
return ET.tostring(root, encoding='unicode', xml_declaration=True).encode('utf-8')
def _video_el(tag):
"""Build a Clark-notation tag name in the video namespace."""
return f'{{{_NS_VIDEO}}}{tag}'
@router.get("/sitemap.xml")
async def get_sitemap(db: Session = Depends(get_db)):
"""Generates a standard XML sitemap for general pages + video watch pages."""
urlset = ET.Element("urlset")
pages = [
{"path": "", "priority": "1.0"},
{"path": "/home", "priority": "0.9"},
{"path": "/flash", "priority": "0.9"},
{"path": "/challenges", "priority": "0.8"},
{"path": "/about", "priority": "0.7"},
{"path": "/partner", "priority": "0.7"},
{"path": "/privacy", "priority": "0.5"},
{"path": "/terms", "priority": "0.5"},
]
for page in pages:
url_el = ET.SubElement(urlset, "url")
ET.SubElement(url_el, "loc").text = f"{BASE_URL}{page['path']}"
ET.SubElement(url_el, "changefreq").text = "daily"
ET.SubElement(url_el, "priority").text = page["priority"]
rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
for row in rows:
if not row.created_at:
continue
url_el = ET.SubElement(urlset, "url")
ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{row.id}"
ET.SubElement(url_el, "lastmod").text = row.created_at.strftime("%Y-%m-%d")
ET.SubElement(url_el, "changefreq").text = "weekly"
ET.SubElement(url_el, "priority").text = "0.6"
return Response(content=_to_xml(urlset), media_type="application/xml")
@router.get("/video-sitemap.xml")
async def get_video_sitemap(db: Session = Depends(get_db)):
"""Generates a Google Video Sitemap for video indexing."""
urlset = ET.Element("urlset")
rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
for row in rows:
if not row.created_at or not row.video_url:
continue
thumbnail = _resolve_url(row.thumbnail_url) if row.thumbnail_url else ""
if not thumbnail:
continue
url_el = ET.SubElement(urlset, "url")
ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{row.id}"
video_el = ET.SubElement(url_el, _video_el("video"))
ET.SubElement(video_el, _video_el("thumbnail_loc")).text = thumbnail
ET.SubElement(video_el, _video_el("title")).text = row.title or ""
ET.SubElement(video_el, _video_el("description")).text = (
row.description or f"Watch {row.title} on Monteeq."
)
ET.SubElement(video_el, _video_el("player_loc")).text = f"{BASE_URL}/watch/{row.id}"
dur = int(row.duration or 0)
hours, remainder = divmod(dur, 3600)
minutes, seconds = divmod(remainder, 60)
ET.SubElement(video_el, _video_el("duration")).text = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
pub_date = row.created_at.strftime("%Y-%m-%d")
ET.SubElement(video_el, _video_el("publication_date")).text = pub_date
if row.tags:
for tag in [t.strip() for t in row.tags.split(",") if t.strip()][:32]:
ET.SubElement(video_el, _video_el("tag")).text = tag
return Response(content=_to_xml(urlset), media_type="application/xml")
_VIDEO_BY_ID_SQL = text("""
SELECT v.id, v.title, v.description, v.thumbnail_url, v.duration,
v.created_at, v.status,
u.username, u.profile_pic
FROM videos v
LEFT JOIN users u ON v.owner_id = u.id
WHERE v.id = :vid OR v.public_id = :pub_id
LIMIT 1
""")
def _parse_video_id(url: str):
"""Extract the video ID from a Monteeq watch URL."""
patterns = [
r'/watch/(\d+)',
r'/watch/([a-zA-Z0-9_-]+)',
r'/embed/(\d+)',
r'/embed/([a-zA-Z0-9_-]+)',
]
for pat in patterns:
m = re.search(pat, url)
if m:
return m.group(1)
return None
@router.get("/oembed")
def oembed(
url: str = Query(..., description="URL of the video"),
format: str = Query("json", description="Response format: json or xml"),
maxwidth: int = Query(None, description="Maximum width"),
maxheight: int = Query(None, description="Maximum height"),
db: Session = Depends(get_db),
):
video_id = _parse_video_id(url)
if not video_id:
raise HTTPException(status_code=400, detail="Invalid video URL")
vid_int = int(video_id) if video_id.isdigit() else None
row = db.execute(_VIDEO_BY_ID_SQL, {"vid": vid_int, "pub_id": video_id}).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Video not found")
width = maxwidth or 640
height = maxheight or 360
watch_url = f"{BASE_URL}/watch/{row.id}"
embed_url = f"{BASE_URL}/embed/{row.id}"
thumbnail = _resolve_url(row.thumbnail_url) if row.thumbnail_url else ""
result = {
"type": "video",
"version": "1.0",
"provider_name": "Monteeq",
"provider_url": BASE_URL,
"title": row.title or "",
"author_name": row.username or "",
"author_url": f"{BASE_URL}/profile/{row.username}" if row.username else "",
"thumbnail_url": thumbnail,
"thumbnail_width": 1280,
"thumbnail_height": 720,
"width": width,
"height": height,
"html": f'<iframe src="{embed_url}" width="{width}" height="{height}" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>',
}
if format == "xml":
xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<oembed>\n'
for k, v in result.items():
xml_str += f" <{k}>{v}</{k}>\n"
xml_str += "</oembed>"
return Response(content=xml_str.encode("utf-8"), media_type="text/xml")
return JSONResponse(
content=result,
headers={
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
},
)
|