diff --git a/app/api/site_videos.py b/app/api/site_videos.py index 678620d..b1d7033 100644 --- a/app/api/site_videos.py +++ b/app/api/site_videos.py @@ -24,15 +24,32 @@ CATALOG = { } VIDEO_MAX = 500 * 1024 * 1024 CAPTIONS_MAX = 1024 * 1024 +PRODUCTS = ('file', 'avulsa', 'uvfile', 'uv') +PRODUCT_NAMES = { + 'file': 'Arquivo por metro', + 'avulsa': 'Artes avulsas', + 'uvfile': 'Arquivo por metro · UV', + 'uv': 'Artes avulsas · UV', +} class VideoUpdate(StrictModel): upload_id: UUID | None = None captions_id: UUID | None = None product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None + products: list[Literal['file', 'avulsa', 'uvfile', 'uv']] = Field(default_factory=list, max_length=4) enabled: bool = False +def _products(body): + """The chosen products, unique and in catalog order; the old single + `product` still works and means one product.""" + chosen = set(body.products) + if not chosen and body.product: + chosen.add(body.product) + return [product for product in PRODUCTS if product in chosen] + + class VideoUploadStart(StrictModel): name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$') size: int = Field(gt=0, strict=True) @@ -78,14 +95,19 @@ def manage_videos(user=Depends(operator)): 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()]} + videos = [] + for id, title in CATALOG.items(): + row = rows.get(id) + products = list(row['products'] or []) if row else [] + videos.append(dict(id=id, title=title, + product=products[0] if products else None, + products=products, + upload_id=row['upload_id'] if row else None, + captions_id=row['captions_id'] if row else None, + video_name=row['video_name'] if row else None, + captions_name=row['captions_name'] if row else None, + enabled=row['enabled'] if row else False)) + return {'videos': videos} @router.post('/api/operator/site-videos/{video_id}') @@ -94,17 +116,20 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))): 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.') + products = _products(body) 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() + # the refusal names the video and the product it holds (DTF-WEB-G). + if body.enabled and products: + other = c.execute('''SELECT id,products FROM dtf_local.site_videos + WHERE id<>%s AND enabled AND products && %s''', (video_id, products)).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.') + common = next(product for product in products if product in other['products']) + raise HTTPException(409, f'O produto "{PRODUCT_NAMES[common]}" já tem o vídeo ' + f'"{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 ( @@ -121,12 +146,14 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))): 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) + c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,products,enabled,updated_by) + VALUES(%s,%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)) + product=EXCLUDED.product,products=EXCLUDED.products,enabled=EXCLUDED.enabled, + updated_by=EXCLUDED.updated_by,updated_at=now()''', + (video_id, body.upload_id, body.captions_id, keys[0], keys[1], + products[0] if products else None, products, 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,)) @@ -137,14 +164,18 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))): @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 + rows = c.execute('''SELECT v.id,v.products,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]} + videos = [] + for row in rows: + products = list(row['products'] or []) + videos.append(dict(id=row['id'], product=products[0] if products else None, + products=products, + 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)) + return {'videos': videos} @router.get('/api/site/videos/{video_id}/captions') diff --git a/app/migrations/202611301600_site-video-products.sql b/app/migrations/202611301600_site-video-products.sql new file mode 100644 index 0000000..1b27db3 --- /dev/null +++ b/app/migrations/202611301600_site-video-products.sql @@ -0,0 +1,8 @@ +-- Round 5, D7: the same video can appear on more than one product page. The +-- old single `product` column stays for compatibility; the code reads +-- `products`. One floating video per product is still enforced in the API. +ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS products text[] NOT NULL DEFAULT '{}'; +UPDATE dtf_local.site_videos SET products=ARRAY[product] WHERE product IS NOT NULL AND products='{}'; +ALTER TABLE dtf_local.site_videos DROP CONSTRAINT IF EXISTS site_videos_products_check; +ALTER TABLE dtf_local.site_videos ADD CONSTRAINT site_videos_products_check + CHECK (products <@ ARRAY['file','avulsa','uvfile','uv']::text[]); diff --git a/tests/site_video_test.py b/tests/site_video_test.py index 5a98daa..98165bf 100644 --- a/tests/site_video_test.py +++ b/tests/site_video_test.py @@ -47,9 +47,22 @@ def run(): published = client.call('/site/videos')['videos'] entry = next(row for row in published if row['id'] == 'sala') assert entry['product'] == 'file' + assert entry['products'] == ['file'], entry assert entry['captions'] == '/api/site/videos/sala/captions' + # The same video can appear on more than one product; duplicates are + # dropped and the order follows the product catalog. + operator.call('/operator/site-videos/sala', {'upload_id': video, + 'captions_id': captions, 'products': ['uv', 'file', 'uv'], 'enabled': True}) + entry = next(row for row in client.call('/site/videos')['videos'] if row['id'] == 'sala') + assert entry['products'] == ['file', 'uv'], entry + assert entry['product'] == 'file', entry # One floating video per product: a second one is refused before any - # copy, naming the video that holds the product (DTF-WEB-G). + # copy, naming the video and the product in conflict (DTF-WEB-G). + refused = operator.call('/operator/site-videos/png', {'upload_id': video, + 'products': ['uv'], 'enabled': True}, expected=409) + assert 'A sala às 3 da manhã' in refused['detail'], refused + assert 'Artes avulsas · UV' in refused['detail'], refused + # The old single `product` still works and is refused the same way. refused = operator.call('/operator/site-videos/png', {'upload_id': video, 'product': 'file', 'enabled': True}, expected=409) assert 'A sala às 3 da manhã' in refused['detail'], refused diff --git a/web/index.html b/web/index.html index ee72f01..a481f38 100644 --- a/web/index.html +++ b/web/index.html @@ -753,15 +753,6 @@ h2 em{font-style:normal;color:var(--laranja)}
4
Acompanhe

Em Minha conta, com aviso no WhatsApp quando ficar pronto.

- -
-
-
Vídeos

A DTF por dentro

-

O que acontece com a sua arte, do envio à retirada.

-
-
-
-