feat(signage): gallery widget (pictures and videos one after another, from a list or a media folder); media folders on the Media page
Folders are only a grouping in the database (media_folders, media.folder_id, Alembic 0046): made, renamed, deleted (files stay) on the Media page, a file filed from its details, uploads go into the folder shown, the picker filters by folder. The gallery widget: its own pictures/videos in order or a folder as it is now, seconds each, fade / slide / zoom, cover / contain. Plan 6R.16, F-114. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -126,6 +126,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"menu_tablet.order_not_found": (404, "This order was not found."),
|
||||
"menu_tablet.order_answered": (409, "This order was already answered."),
|
||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||
"media.folder_unknown": (404, "That folder isn't in the media library any more."),
|
||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||
"reservation.table_unknown": (404, "Table {table_id} not found."),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in
|
||||
the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder.
|
||||
|
||||
Revision ID: 0046_media_folders
|
||||
Revises: 0045_signage_shapes
|
||||
Create Date: 2026-11-22 16:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
revision = '0046_media_folders'
|
||||
down_revision = '0045_signage_shapes'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'media_folders',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_media_folders_id', 'media_folders', ['id'])
|
||||
with op.batch_alter_table('media') as b:
|
||||
b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True))
|
||||
b.create_index('ix_media_folder_id', ['folder_id'])
|
||||
b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('media') as b:
|
||||
b.drop_constraint('fk_media_folder', type_='foreignkey')
|
||||
b.drop_index('ix_media_folder_id')
|
||||
b.drop_column('folder_id')
|
||||
op.drop_index('ix_media_folders_id', 'media_folders')
|
||||
op.drop_table('media_folders')
|
||||
@@ -39,9 +39,21 @@ class Media(Base):
|
||||
# or no video tool on this server). `progress` 0-100 while working.
|
||||
processing = Column(String, nullable=True)
|
||||
progress = Column(Integer, nullable=True)
|
||||
# its folder on the Media page (6R.16): only a grouping, the file stays where it is
|
||||
folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
|
||||
uploader = relationship("User", lazy="joined")
|
||||
|
||||
@property
|
||||
def uploaded_by_name(self):
|
||||
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
|
||||
|
||||
|
||||
class MediaFolder(Base):
|
||||
"""A folder of the media library (6R.16): a name and a place in the list; its files point at it."""
|
||||
__tablename__ = "media_folders"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
position = Column(Integer, nullable=False, default=0, server_default='0')
|
||||
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||
|
||||
@@ -157,7 +157,7 @@ def identity_out(db) -> dict:
|
||||
|
||||
def _uses(db, media_id: int) -> list:
|
||||
logos = stored(db).logos
|
||||
return [{"id": 0, "name": f"identity.{k}"} for k in LOGOS if getattr(logos, k) == media_id]
|
||||
return [{"id": 0, "name": k} for k in LOGOS if getattr(logos, k) == media_id]
|
||||
|
||||
|
||||
def _register():
|
||||
|
||||
@@ -29,7 +29,7 @@ from core.access.deps import public, require_any
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
from datetime import datetime
|
||||
from models.media import Media
|
||||
from models.media import Media, MediaFolder
|
||||
from services import media as store
|
||||
from services import video
|
||||
|
||||
@@ -57,6 +57,7 @@ class MediaOut(BaseModel):
|
||||
builtin: bool = False
|
||||
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
|
||||
progress: Optional[int] = None
|
||||
folder_id: Optional[int] = None # 6R.16
|
||||
urls: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -75,17 +76,53 @@ class MediaPage(BaseModel):
|
||||
|
||||
|
||||
class RenameBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
name: Optional[str] = Field(default=None, min_length=1, max_length=120)
|
||||
folder_id: Optional[int] = None # 6R.16: its folder (None: none)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _strip(cls, v):
|
||||
if v is None:
|
||||
return v
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("empty")
|
||||
return v
|
||||
|
||||
|
||||
class FolderBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _strip(cls, v):
|
||||
v = " ".join(v.split())
|
||||
if not v:
|
||||
raise ValueError("empty")
|
||||
return v
|
||||
|
||||
|
||||
class MoveBody(BaseModel):
|
||||
ids: List[int] = Field(min_length=1, max_length=500)
|
||||
folder_id: Optional[int] = None
|
||||
|
||||
|
||||
def _folder(db: Session, folder_id: Optional[int]) -> Optional[MediaFolder]:
|
||||
if folder_id is None:
|
||||
return None
|
||||
f = db.get(MediaFolder, folder_id)
|
||||
if f is None:
|
||||
raise XeniaError("media.folder_unknown", folder_id=folder_id)
|
||||
return f
|
||||
|
||||
|
||||
def _folders_out(db: Session) -> list:
|
||||
from sqlalchemy import func
|
||||
counts = dict(db.query(Media.folder_id, func.count(Media.id)).group_by(Media.folder_id).all())
|
||||
rows = db.query(MediaFolder).order_by(MediaFolder.position, MediaFolder.name).all()
|
||||
return [{"id": f.id, "name": f.name, "count": counts.get(f.id, 0)} for f in rows]
|
||||
|
||||
|
||||
def _out(item: Media, cls=MediaOut, **extra):
|
||||
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
|
||||
|
||||
@@ -105,9 +142,14 @@ def _name_from(filename: str | None) -> str:
|
||||
|
||||
@router.get("", response_model=MediaPage)
|
||||
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
|
||||
collection: Optional[Literal["builtin", "own"]] = None, limit: int = 100, offset: int = 0,
|
||||
collection: Optional[Literal["builtin", "own"]] = None, folder: Optional[str] = None, limit: int = 100, offset: int = 0,
|
||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""`folder`: a folder's id, or "none" for the files in no folder (6R.16)."""
|
||||
query = db.query(Media)
|
||||
if folder == "none":
|
||||
query = query.filter(Media.folder_id.is_(None))
|
||||
elif folder and folder.isdigit():
|
||||
query = query.filter(Media.folder_id == int(folder))
|
||||
if kind:
|
||||
query = query.filter(Media.kind == kind)
|
||||
if q and q.strip():
|
||||
@@ -122,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str
|
||||
|
||||
@router.post("", response_model=UploadOut, status_code=201)
|
||||
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
|
||||
folder_id: Optional[int] = Form(None),
|
||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
# The type comes from the bytes; the browser's content type only picks the size limit.
|
||||
declared = (file.content_type or "").lower()
|
||||
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
|
||||
tmp, sha, size = store.receive(file.file, limit)
|
||||
folder = _folder(db, folder_id)
|
||||
existing = db.query(Media).filter(Media.sha256 == sha).first()
|
||||
if existing is not None:
|
||||
store._remove(tmp)
|
||||
@@ -134,7 +178,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
||||
return _out(existing, UploadOut, existing=True)
|
||||
info = store.ingest(tmp, sha, size)
|
||||
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id,
|
||||
folder_id=folder.id if folder else None, **info)
|
||||
if item.kind == "video":
|
||||
video.queued(item) # its still frame and playable version, in the background
|
||||
try:
|
||||
@@ -195,6 +240,50 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict):
|
||||
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
|
||||
|
||||
|
||||
# ── folders (6R.16): only a grouping; files keep their place on disk ─────────────
|
||||
|
||||
@router.get("/folders")
|
||||
def list_folders(db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
return {"folders": _folders_out(db), "none": db.query(Media).filter(Media.folder_id.is_(None)).count()}
|
||||
|
||||
|
||||
@router.post("/folders", status_code=201)
|
||||
def create_folder(body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
last = db.query(MediaFolder).count()
|
||||
f = MediaFolder(name=body.name, position=last)
|
||||
db.add(f)
|
||||
db.commit()
|
||||
db.refresh(f)
|
||||
return {"id": f.id, "name": f.name, "count": 0}
|
||||
|
||||
|
||||
@router.patch("/folders/{folder_id}")
|
||||
def rename_folder(folder_id: int, body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
f = _folder(db, folder_id)
|
||||
f.name = body.name
|
||||
db.commit()
|
||||
return next(x for x in _folders_out(db) if x["id"] == f.id)
|
||||
|
||||
|
||||
@router.delete("/folders/{folder_id}", status_code=204)
|
||||
def delete_folder(folder_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""The folder goes; its files stay in the library, in no folder."""
|
||||
f = _folder(db, folder_id)
|
||||
db.query(Media).filter(Media.folder_id == f.id).update({Media.folder_id: None})
|
||||
db.delete(f)
|
||||
db.commit()
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/move")
|
||||
def move_media(body: MoveBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""Several files into a folder (or out of any: folder_id null)."""
|
||||
folder = _folder(db, body.folder_id)
|
||||
n = db.query(Media).filter(Media.id.in_(body.ids)).update({Media.folder_id: folder.id if folder else None}, synchronize_session=False)
|
||||
db.commit()
|
||||
return {"moved": n}
|
||||
|
||||
|
||||
@router.get("/{media_id}", response_model=MediaDetail)
|
||||
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
item = _get(db, media_id)
|
||||
@@ -204,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require
|
||||
@router.patch("/{media_id}", response_model=MediaOut)
|
||||
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
item = _get(db, media_id)
|
||||
if item.builtin:
|
||||
raise XeniaError("media.builtin")
|
||||
item.name = body.name
|
||||
if "name" in body.model_fields_set and body.name is not None:
|
||||
if item.builtin:
|
||||
raise XeniaError("media.builtin")
|
||||
item.name = body.name
|
||||
if "folder_id" in body.model_fields_set:
|
||||
item.folder_id = _folder(db, body.folder_id).id if body.folder_id is not None else None # built-in pictures may be filed too
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return _out(item)
|
||||
|
||||
@@ -86,7 +86,7 @@ class Background(_Strict):
|
||||
|
||||
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack",
|
||||
"shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15
|
||||
"reviews"] # 6R.19
|
||||
"reviews", "gallery"] # 6R.19, 6R.16
|
||||
WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM"
|
||||
ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"]
|
||||
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
|
||||
@@ -316,6 +316,13 @@ class Widget(_Strict):
|
||||
reviews_min: int = Field(default=4, ge=1, le=5) # only reviews with at least these stars
|
||||
reviews_stars: bool = True
|
||||
reviews_name: bool = True
|
||||
# a gallery (6R.16): pictures and videos one after another, from its own list or a media folder
|
||||
gallery_source: Literal["pictures", "folder"] = "pictures"
|
||||
media_ids: List[int] = Field(default_factory=list, max_length=100)
|
||||
gallery_folder: Optional[int] = None
|
||||
gallery_seconds: int = Field(default=5, ge=3, le=120)
|
||||
gallery_transition: Literal["fade", "slide", "zoom", "none"] = "fade"
|
||||
gallery_fit: Literal["cover", "contain"] = "cover"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _place(self):
|
||||
@@ -661,6 +668,10 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
|
||||
out[path] = {"link": _qr_link(w)}
|
||||
elif w.get("kind") == "menu":
|
||||
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
|
||||
elif w.get("kind") == "gallery" and w.get("gallery_source") == "folder":
|
||||
ids = gallery_folder_ids(db, w.get("gallery_folder")) # 6R.16: the folder as it is now
|
||||
out[path] = {"gallery": ids}
|
||||
mids += ids
|
||||
elif depth == 0:
|
||||
s = db.get(SignageSavedSlide, sid)
|
||||
if s is None:
|
||||
@@ -675,6 +686,14 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
|
||||
return out, mids
|
||||
|
||||
|
||||
def gallery_folder_ids(db, folder_id) -> list[int]:
|
||||
"""A media folder's files for a gallery (6R.16), newest last as uploaded; none for a folder that's gone."""
|
||||
from models.media import Media
|
||||
if not folder_id:
|
||||
return []
|
||||
return [m.id for m in db.query(Media).filter(Media.folder_id == folder_id).order_by(Media.created_at, Media.id).limit(200)]
|
||||
|
||||
|
||||
def _content(db, kind: str, raw: dict | None) -> dict:
|
||||
"""The content as stored: typed for its kind, every media id an existing file of the right kind."""
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Media folders (6R.16): made, renamed, deleted (files stay), files moved and uploaded into one,
|
||||
the list filtered; a gallery widget showing a folder gets its files (and the screen their addresses)."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
|
||||
|
||||
def test_folders(client, owner_h, media_dir):
|
||||
f = client.post("/api/media/folders", headers=owner_h, json={"name": " Summer menu "}).json()
|
||||
assert f["name"] == "Summer menu" and f["count"] == 0
|
||||
a = up(client, owner_h, jpeg(300, 200)).json()
|
||||
b = up(client, owner_h, jpeg(300, 200, (9, 9, 9))).json()
|
||||
assert client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"], b["id"]], "folder_id": f["id"]}).json()["moved"] == 2
|
||||
got = client.get("/api/media/folders", headers=owner_h).json()
|
||||
assert got["folders"] == [{"id": f["id"], "name": "Summer menu", "count": 2}]
|
||||
listed = client.get(f"/api/media?folder={f['id']}", headers=owner_h).json()
|
||||
assert {i["id"] for i in listed["items"]} == {a["id"], b["id"]} and listed["items"][0]["folder_id"] == f["id"]
|
||||
assert all(i["folder_id"] is None for i in client.get("/api/media?folder=none", headers=owner_h).json()["items"])
|
||||
r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"folder_id": None})
|
||||
assert r.status_code == 200 and r.json()["folder_id"] is None and r.json()["name"] == a["name"]
|
||||
assert client.patch(f"/api/media/folders/{f['id']}", headers=owner_h, json={"name": "Winter"}).json()["name"] == "Winter"
|
||||
# an upload straight into a folder
|
||||
c = client.post("/api/media", headers=owner_h, files={"file": ("x.jpg", jpeg(100, 100, (1, 2, 3)), "image/jpeg")}, data={"folder_id": str(f["id"])}).json()
|
||||
assert c["folder_id"] == f["id"]
|
||||
assert err(client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"]], "folder_id": 9999})) == "media.folder_unknown"
|
||||
assert client.delete(f"/api/media/folders/{f['id']}", headers=owner_h).status_code == 204
|
||||
assert client.get(f"/api/media/{b['id']}", headers=owner_h).json()["folder_id"] is None # the file stays
|
||||
|
||||
|
||||
def test_a_gallery_of_a_folder(client, owner_h, screens, media_dir):
|
||||
f = client.post("/api/media/folders", headers=owner_h, json={"name": "Dishes"}).json()
|
||||
pics = [up(client, owner_h, jpeg(400, 300, (i * 40, 10, 10))).json() for i in range(3)]
|
||||
client.post("/api/media/move", headers=owner_h, json={"ids": [p["id"] for p in pics], "folder_id": f["id"]})
|
||||
p = playlist(client, owner_h)
|
||||
slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||
{"kind": "gallery", "position": "custom", "box": {"x": 0, "y": 0, "w": 50, "h": 50}, "gallery_source": "folder", "gallery_folder": f["id"], "gallery_seconds": 4},
|
||||
{"kind": "gallery", "position": "top-left", "media_ids": [pics[0]["id"]], "gallery_transition": "slide"}]})
|
||||
client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
pl = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"]
|
||||
s = pl["slides"][0]
|
||||
assert s["extras"]["0"]["gallery"] == [x["id"] for x in pics]
|
||||
assert all(str(x["id"]) in pl["media"] for x in pics)
|
||||
# the pictures in a gallery's own list are protected
|
||||
assert err(client.delete(f"/api/media/{pics[0]['id']}", headers=owner_h)) == "media.in_use"
|
||||
Reference in New Issue
Block a user