feat: the videos panel in the Site tab, captions optional (front 8.4)

Dropstar uploads the six videos themselves, so the panel moves from
Integrações to the Site tab, next to products and prices. A video can be
published without a VTT: the Site plays it without a captions track.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 14:50:18 -03:00
parent 2a6732eb37
commit 2f85a38562
6 changed files with 75 additions and 58 deletions

View File

@@ -92,8 +92,8 @@ def manage_videos(user=Depends(operator)):
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 or not body.captions_id):
raise HTTPException(422, 'Envie o vídeo e sua legenda VTT antes de publicar.')
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 {}
@@ -137,10 +137,11 @@ def published_videos():
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 AND v.captions_key IS NOT NULL''').fetchall()
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") for row in rows]}
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')

View File

@@ -165,7 +165,7 @@ try{
await waitFor(()=>kanban.eval('!document.getElementById("app").hidden'),'Kanban sign-in');
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
await kanban.click('[data-tab="integrations"]');
await kanban.click('[data-tab="site"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
'six video slots in Gestão');
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12);

View File

@@ -56,7 +56,22 @@ def run():
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'product': 'file', 'enabled': False})
assert not any(row['id'] == 'sala' for row in client.call('/site/videos')['videos'])
print('PASS: Gestão publishes a scanned video, signed media and same-origin VTT; hiding removes it from the Site')
# Captions are optional (front 8.4): the video alone is published. The
# published VTT copy stops being referenced, so keep it for cleanup.
with db.connect() as c:
old = c.execute("SELECT captions_key FROM dtf_local.site_videos WHERE id='sala'").fetchone()
if old and old['captions_key']:
keys.append(old['captions_key'])
operator.call('/operator/site-videos/sala', {'upload_id': video,
'product': 'file', 'enabled': True})
entry = next(row for row in client.call('/site/videos')['videos'] if row['id'] == 'sala')
assert entry['captions'] is None, entry
client.call('/site/videos/sala/captions', expected=404)
operator.call('/operator/site-videos/sala', {'upload_id': video,
'product': 'file', 'enabled': False})
assert not any(row['id'] == 'sala' for row in client.call('/site/videos')['videos'])
print('PASS: Gestão publishes a scanned video with signed media, with or without captions;'
' hiding removes it from the Site')
finally:
with db.connect() as c:
row = c.execute("DELETE FROM dtf_local.site_videos WHERE id='sala' RETURNING video_key,captions_key").fetchone()

View File

@@ -153,4 +153,51 @@ async function loadSiteAdmin(){
const data=await api('/site/products');
$('site-products').replaceChildren(...data.products.map(siteProductRow));
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
await loadSiteVideos();
}
async function loadSiteVideos(){
const host=$('site-videos-list'),panel=$('site-videos-panel');
panel.hidden=!may('manage');
if(panel.hidden)return;
const data=await api('/site-videos');
host.replaceChildren(...data.videos.map(video=>{
const row=node('div',undefined,'siteVideoRow');
const heading=node('div',undefined,'siteVideoHeading');
heading.append(node('b',video.title),node('span',video.enabled?'Publicado':'Rascunho','pill'+(video.enabled?' ok':'')));
const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm';
const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt';
const videoLabel=node('label',undefined,'siteVideoField');
videoLabel.append(node('span','Vídeo · '+(video.video_name||'nenhum arquivo')),videoInput);
const captionsLabel=node('label',undefined,'siteVideoField');
captionsLabel.append(node('span','Legenda (opcional) · '+(video.captions_name||'nenhuma legenda')),captionsInput);
const product=node('select');product.setAttribute('aria-label','Produto do vídeo '+video.title);
for(const [value,title] of [['','Só na categoria DTF'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]){
const option=node('option',title);option.value=value;product.append(option);
}
product.value=video.product||'';
const productLabel=node('label',undefined,'siteVideoField');productLabel.append(node('span','Vídeo flutuante'),product);
const enabled=node('input');enabled.type='checkbox';enabled.checked=video.enabled;
const publish=node('label',undefined,'siteVideoToggle');publish.append(enabled,node('span','Publicado no Site'));
const errorMessage=node('p',undefined,'siteVideoError');errorMessage.setAttribute('role','alert');
const save=button('Salvar vídeo',async()=>{
save.disabled=true;
errorMessage.textContent='';
try{
let uploadId=video.upload_id,captionsId=video.captions_id;
if(videoInput.files[0])uploadId=await dtfUpload(videoInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
product:product.value||null,enabled:enabled.checked});
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
await loadSiteVideos();
}catch(error){errorMessage.textContent=error.message;save.disabled=false;}
},'btn');
const fields=node('div',undefined,'siteVideoFields');
fields.append(videoLabel,captionsLabel,productLabel,publish,save,errorMessage);
row.append(heading,fields);return row;
}));
}

View File

@@ -163,6 +163,11 @@
<p class="phint">Cada preço vale a partir da data escolhida. Um preço que já começou não muda mais: o histórico fica abaixo. Só um preço agendado pode ser cancelado.</p>
<div id="site-prices"></div>
</section>
<section class="panel clip" id="site-videos-panel" hidden>
<div class="phead"><h2>Vídeos do Site</h2></div>
<p class="phint">Envie o vídeo em MP4 ou WebM (até 100 MB). A legenda VTT é opcional. Escolha o produto para o vídeo flutuante e publique quando estiver pronto.</p>
<div id="site-videos-list" class="siteVideoList"></div>
</section>
</section>
<section id="tab-users" class="page" hidden>
<section class="panel clip">
@@ -182,11 +187,6 @@
</section>
<section id="tab-integrations" class="page" hidden>
<div class="panel" id="integrations"></div>
<section class="panel clip" id="site-videos-panel" hidden>
<div class="phead"><h2>Vídeos do Site</h2></div>
<p class="phint">Envie MP4 ou WebM e legenda VTT. Escolha o produto para o vídeo flutuante e publique quando estiver pronto.</p>
<div id="site-videos-list" class="siteVideoList"></div>
</section>
<section class="panel clip" id="event-log">
<div class="phead"><h2>Envios ao Tiny</h2><div class="pfilters" id="event-filters"></div></div>
<div class="scrollbox log"><table class="table"><thead><tr><th scope="col">Quando</th><th scope="col">Pedido</th><th scope="col">Evento</th><th scope="col">Resultado</th></tr></thead><tbody id="events"></tbody></table></div>

View File

@@ -3853,53 +3853,7 @@ function renderEvents(){
// Integrações: the print room's folder for whoever produces, what is on and off
// for the managers, and the buttons, details and the Tiny log for the superadmin.
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();if(may('manage'))await loadSiteVideos();};
async function loadSiteVideos(){
const host=$('site-videos-list'),panel=$('site-videos-panel');
panel.hidden=!may('manage');
if(panel.hidden)return;
const data=await api('/site-videos');
host.replaceChildren(...data.videos.map(video=>{
const row=node('div',undefined,'siteVideoRow');
const heading=node('div',undefined,'siteVideoHeading');
heading.append(node('b',video.title),node('span',video.enabled?'Publicado':'Rascunho','pill'+(video.enabled?' ok':'')));
const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm';
const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt';
const videoLabel=node('label',undefined,'siteVideoField');
videoLabel.append(node('span','Vídeo · '+(video.video_name||'nenhum arquivo')),videoInput);
const captionsLabel=node('label',undefined,'siteVideoField');
captionsLabel.append(node('span','Legenda · '+(video.captions_name||'nenhuma legenda')),captionsInput);
const product=node('select');product.setAttribute('aria-label','Produto do vídeo '+video.title);
for(const [value,title] of [['','Só na categoria DTF'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]){
const option=node('option',title);option.value=value;product.append(option);
}
product.value=video.product||'';
const productLabel=node('label',undefined,'siteVideoField');productLabel.append(node('span','Vídeo flutuante'),product);
const enabled=node('input');enabled.type='checkbox';enabled.checked=video.enabled;
const publish=node('label',undefined,'siteVideoToggle');publish.append(enabled,node('span','Publicado no Site'));
const errorMessage=node('p',undefined,'siteVideoError');errorMessage.setAttribute('role','alert');
const save=button('Salvar vídeo',async()=>{
save.disabled=true;
errorMessage.textContent='';
try{
let uploadId=video.upload_id,captionsId=video.captions_id;
if(videoInput.files[0])uploadId=await dtfUpload(videoInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
product:product.value||null,enabled:enabled.checked});
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
await loadSiteVideos();
}catch(error){errorMessage.textContent=error.message;save.disabled=false;}
},'btn');
const fields=node('div',undefined,'siteVideoFields');
fields.append(videoLabel,captionsLabel,productLabel,publish,save,errorMessage);
row.append(heading,fields);return row;
}));
}
const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();};
// A row with only its name, state and summary, for whoever may not change it.
const integRow=o=>may('integrations')?integration(o):integration({name:o.name,state:o.state,tone:o.tone,summary:o.summary});
let mpCheck=null;