wrolpi/wrolpi/collections/types.py
lrnselfreliance 9a5d1f1630
Add ordered collections (playlists): polymorphic items + item API (#475)
* Add Playlists: ordered, mixed-type collections

A playlist (Collection kind='playlist') is a manually-curated, ordered list that
mixes item types. Squash of the playlists feature branch (24 commits).

Data model & API:
- CollectionItem is polymorphic via item_kind: 'file' (FileGroup), 'zim'
  (zim_id + zim_entry), or 'url' (link to anything the WROLPi browser opens,
  e.g. /map?lat=&lon=&z=). CHECK constraint enforces exactly one kind; per-kind
  unique constraints; migration a7b1c2d3e4f5.
- Endpoints: create playlist; add/remove/reorder items (idempotent adds: 201 new,
  200 existing); GET returns the ordered items. All mutations wrol_mode_check'd.

Config (source of truth):
- playlists.yaml (PlaylistsConfig) stores each playlist's metadata AND ordered
  items (file by relative path, zim by path+entry, url inline); round-trips a
  DB wipe. Supports backup import (DB_CONFIG_FILE_NAMES).
- The redundant generic CollectionsConfig (collections.yaml) is deleted:
  channels/domains own their configs, authors/subjects are re-derived.

On-disk sync (sync_playlists_directory switch):
- Each playlist materializes into the configurable Playlists Directory
  (playlists_destination, Settings UI input, excluded from indexing) with
  position-prefixed entries: NNNN_<file> hard links (copy fallback across
  filesystems) and NNNN_<title>.html stubs for zim/url items.
- Tagged playlists are namespaced like channels: <playlists>/<tag>/<name>;
  a tag change moves the directory and prunes the empty old tag dir.
- Deletion safety: managed files are only removed when they are our marked
  stubs or still have another hard link (st_nlink > 1) -- never a last copy.
  Stray loose files at the playlists root are removed; stub URLs are
  scheme-allowlisted (no javascript:/data:).

Frontend:
- /playlists list page (CollectionTable, name filter, New Playlist modal, Tag
  column) between Files and Zim in the nav.
- View-only detail page (Name link) and edit page (Edit button): themed table
  with model icons/colors + poster thumbnails, items link to their model page
  (video/archive/doc) or preview, up/down reorder, remove, add-URL form,
  single-tag selector; all editing disabled in WROL Mode.
- Reusable green "Add to Playlist" button on Video/Archive/Doc detail pages,
  the FilePreview toolbar, Zim search results, and Map pins (added as a /map
  URL item with a map-marker icon).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Playlist edit page parity: rename, custom directory, tag modal move suggestion

Match the ChannelEditPage/DomainEditPage UX on the playlist edit page:
Back/View buttons, an edit form (name, description, directory), and the
shared CollectionTagModal with the violet "Tag" button.  The tag modal now
suggests moving the playlist to its managed tag location
(playlists/<tag>/<name>); accepting the suggestion stores directory=None so
the sync keeps auto-managing the location.  Tag buttons on the Channel and
Domain edit pages are now violet to match.

Backend: update_collection learns rename (with per-kind validation and
duplicate checks) and playlist custom directories (cleanup of the abandoned
directory, config round-trip, commit-before-switch to avoid the background
sync racing pre-commit state).  tag_collection's duplicated untag/tag
branches are merged, and the per-kind config-save dispatch is consolidated
into _activate_config_save().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Deduplicate Collection error handling and Tag creation

Delete the duplicate UnknownCollection in wrolpi/collections/errors.py and
re-export the canonical one from wrolpi/errors.py, which carries
status_code=NOT_FOUND (the local copy inherited 500).  Replace the repeated
query/raise pattern in reorganize.py with Collection.find_by_id.

Add Tag.get_or_create_tag and use it for collection tagging; flush the new
Tag before returning so callers can read .id immediately -- previously
tagging a collection with a brand-new tag name set tag_id=None.  Regression
test included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 19:46:34 -06:00

143 lines
4 KiB
Python

"""
Collection Type Registry
This module provides a registry system for different collection types (domains, channels, etc.)
to register their own validators and behavior rules.
"""
from typing import Callable, Dict, Optional
from wrolpi.common import logger
logger = logger.getChild(__name__)
# Type alias for validator functions
ValidatorFunc = Callable[[str], bool]
class CollectionTypeRegistry:
"""
Registry for collection type validators and rules.
Allows different collection types to register their own validation logic,
making the system extensible for future collection types.
"""
def __init__(self):
self._validators: Dict[str, ValidatorFunc] = {}
self._descriptions: Dict[str, str] = {}
def register(self, kind: str, validator: ValidatorFunc, description: str = ""):
"""
Register a validator for a collection type.
Args:
kind: The collection kind (e.g., 'domain', 'channel')
validator: Function that takes a name and returns True if valid
description: Human-readable description of validation rules
"""
if kind in self._validators:
logger.warning(f"Overwriting existing validator for collection kind '{kind}'")
self._validators[kind] = validator
self._descriptions[kind] = description
logger.debug(f"Registered validator for collection kind '{kind}'")
def validate(self, kind: str, name: str) -> bool:
"""
Validate a collection name for a given type.
Args:
kind: The collection kind
name: The collection name to validate
Returns:
True if valid, False otherwise
If no validator is registered for the kind, returns True (permissive)
"""
if kind not in self._validators:
logger.debug(f"No validator registered for kind '{kind}', allowing any name")
return True
return self._validators[kind](name)
def get_description(self, kind: str) -> Optional[str]:
"""Get the validation description for a collection type."""
return self._descriptions.get(kind)
def is_registered(self, kind: str) -> bool:
"""Check if a validator is registered for a collection type."""
return kind in self._validators
# Global registry instance
collection_type_registry = CollectionTypeRegistry()
# Domain validator
def validate_domain_name(name: str) -> bool:
"""
Validate that a name is a valid domain format.
A valid domain must:
- Be a string
- Contain at least one "." (e.g., "example.com")
- Not start or end with "."
Examples:
Valid: "example.com", "sub.example.com", "a.b.c"
Invalid: "example", "example.", ".example", "."
Args:
name: The domain name to validate
Returns:
True if valid domain format, False otherwise
"""
if not isinstance(name, str) or not name:
return False
# Must contain at least one "."
if '.' not in name:
return False
# Should not start or end with "."
if name.startswith('.') or name.endswith('.'):
return False
return True
# Channel validator (permissive - allows any non-empty string)
def validate_channel_name(name: str) -> bool:
"""
Validate that a name is valid for a channel.
Channels are permissive and allow any non-empty string.
Args:
name: The channel name to validate
Returns:
True if valid (non-empty string), False otherwise
"""
return isinstance(name, str) and len(name.strip()) > 0
# Register built-in collection types
collection_type_registry.register(
'domain',
validate_domain_name,
'Domain must contain at least one "." and not start/end with "."'
)
collection_type_registry.register(
'channel',
validate_channel_name,
'Channel name must be a non-empty string'
)
collection_type_registry.register(
'playlist',
validate_channel_name, # Permissive: any non-empty name.
'Playlist name must be a non-empty string'
)