"""Six DTF videos, managed by Gestão and published only after virus scanning.""" from typing import Literal from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Response from pydantic import Field from ..core import db from ..core.auth import audit, can, operator from ..core.models import StrictModel from ..runtime import operator_identity, storage, upload_row from ..scanning import require_clean from .uploads import begin_upload router = APIRouter() CATALOG = { 'subindo': 'Subindo a arte pelo celular', 'nota': 'O que é a nota da arte — e o que ela não é', 'png': 'Por que PNG com fundo transparente', 'avulsas': 'Montando artes avulsas e vendo a folha ao vivo', 'retirada': 'Retirada em Franca em 24 h', 'sala': 'A sala às 3 da manhã', } VIDEO_MAX = 500 * 1024 * 1024 CAPTIONS_MAX = 1024 * 1024 class VideoUpdate(StrictModel): upload_id: UUID | None = None captions_id: UUID | None = None product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None enabled: bool = False class VideoUploadStart(StrictModel): name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$') size: int = Field(gt=0, strict=True) def _kind(upload): name = upload['name'].lower() if name.endswith('.mp4') and upload['size'] <= VIDEO_MAX: return 'video/mp4', b'ftyp', 4 if name.endswith('.webm') and upload['size'] <= VIDEO_MAX: return 'video/webm', b'\x1a\x45\xdf\xa3', 0 if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX: return 'text/vtt', b'WEBVTT', 0 raise HTTPException(422, 'Use MP4/WebM de até 500 MB ou legenda VTT de até 1 MB.') def _checked_upload(c, uid, identity, expected): upload = upload_row(c, uid, identity, lock=True) if not upload['complete']: raise HTTPException(409, 'Espere o envio terminar.') require_clean(upload) mime, signature, offset = _kind(upload) if mime not in expected: raise HTTPException(422, 'Escolha um vídeo MP4/WebM e uma legenda VTT.') response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range='bytes=0-31') head = response['Body'].read() if not head[offset:].startswith(signature) and not (mime == 'text/vtt' and head.startswith(b'\xef\xbb\xbfWEBVTT')): raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.') return upload, mime @router.post('/api/operator/site-videos/uploads') def start_video_upload(body: VideoUploadStart, user=Depends(can('manage'))): _kind({'name': body.name, 'size': body.size}) return begin_upload(body, session_id=operator_identity(user)) @router.get('/api/operator/site-videos') def manage_videos(user=Depends(operator)): with db.connect() as c: rows = {row['id']: row for row in c.execute('''SELECT v.*, u.name AS video_name, t.name AS captions_name FROM dtf_local.site_videos v LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()} return {'videos': [dict(id=id, title=title, product=rows[id]['product'] if id in rows else None, upload_id=rows[id]['upload_id'] if id in rows else None, captions_id=rows[id]['captions_id'] if id in rows else None, video_name=rows[id]['video_name'] if id in rows else None, captions_name=rows[id]['captions_name'] if id in rows else None, enabled=rows[id]['enabled'] if id in rows else False) for id, title in CATALOG.items()]} @router.post('/api/operator/site-videos/{video_id}') def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))): if video_id not in CATALOG: raise HTTPException(404, 'Vídeo não encontrado.') if body.enabled and not body.upload_id: raise HTTPException(422, 'Envie o vídeo antes de publicar.') with db.connect() as c: previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE', (video_id,)).fetchone() or {} # One floating video per product page; checked before any copy, and # the refusal names the video that holds the product (DTF-WEB-G). if body.enabled and body.product: other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled', (video_id, body.product)).fetchone() if other: raise HTTPException(409, f'Este produto já tem o vídeo "{CATALOG.get(other["id"], other["id"])}" ' 'publicado. Tire esse do Site antes, ou escolha outro lugar.') identity = operator_identity(user) keys = [] for uid, expected, previous_id, previous_key in ( (body.upload_id, ('video/mp4','video/webm'), previous.get('upload_id'), previous.get('video_key')), (body.captions_id, ('text/vtt',), previous.get('captions_id'), previous.get('captions_key'))): if not uid: keys.append(None) elif uid == previous_id and previous_key: keys.append(previous_key) else: upload, mime = _checked_upload(c, uid, identity, expected) key = f'videos/{video_id}/{uid}{".vtt" if mime == "text/vtt" else ".webm" if mime == "video/webm" else ".mp4"}' storage.client.copy_object(Bucket=storage.bucket, CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']}, Key=key, ContentType=mime, MetadataDirective='REPLACE') keys.append(key) c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by) VALUES(%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id, video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key, product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''', (video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user)) ids = [uid for uid in (body.upload_id, body.captions_id) if uid] if ids: c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,)) audit('site_video_changed', video=video_id, operator=user, enabled=body.enabled) return {'ok': True} @router.get('/api/site/videos') def published_videos(): with db.connect() as c: rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name FROM dtf_local.site_videos v JOIN dtf_local.uploads u ON u.id=v.upload_id WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall() return {'videos': [dict(id=row['id'], product=row['product'], src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]), captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None) for row in rows]} @router.get('/api/site/videos/{video_id}/captions') def published_captions(video_id: str): if video_id not in CATALOG: raise HTTPException(404, 'Legenda não encontrada.') with db.connect() as c: row = c.execute('''SELECT captions_key FROM dtf_local.site_videos WHERE id=%s AND enabled AND video_key IS NOT NULL AND captions_key IS NOT NULL''', (video_id,)).fetchone() if not row: raise HTTPException(404, 'Legenda não encontrada.') obj = storage.client.get_object(Bucket=storage.bucket, Key=row['captions_key']) body = obj['Body'].read(CAPTIONS_MAX + 1) if len(body) > CAPTIONS_MAX: raise HTTPException(500, 'Legenda inválida.') return Response(body, media_type='text/vtt', headers={'Cache-Control': 'public, max-age=300'})