mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 17:36:18 -05:00
A directory containing files that have been tagged is maintained automatically by WROLPi.
This commit is contained in:
parent
35ec6d44fe
commit
0e99266379
11 changed files with 246 additions and 16 deletions
|
|
@ -203,6 +203,8 @@ function EditTagsModal() {
|
|||
const [tagName, setTagName] = React.useState('');
|
||||
const [tagColor, setTagColor] = React.useState(DEFAULT_TAG_COLOR);
|
||||
const textColor = contrastingColor(tagColor);
|
||||
const [tagNameError, setTagNameError] = React.useState(null);
|
||||
const disabled = !!!tagName || !!tagNameError;
|
||||
|
||||
const localOnClose = () => {
|
||||
setOpen(false);
|
||||
|
|
@ -237,6 +239,13 @@ function EditTagsModal() {
|
|||
setTagColor(DEFAULT_TAG_COLOR);
|
||||
}
|
||||
|
||||
const handleTagNameChange = (e, {value}) => {
|
||||
setTagName(value);
|
||||
// Tag names cannot contain these characters.
|
||||
const tagNameRegex = /[,<>:|"\\?*%!\n\r]/;
|
||||
setTagNameError(tagNameRegex.test(value) ? {content: 'Invalid Tag Name'} : null);
|
||||
}
|
||||
|
||||
const tableHeaders = [
|
||||
{key: 'delete', text: 'Delete', sortBy: null, width: 2},
|
||||
{key: 'edit', text: 'Edit', sortBy: null, width: 2},
|
||||
|
|
@ -264,7 +273,8 @@ function EditTagsModal() {
|
|||
label={<b>Tag Name</b>}
|
||||
placeholder='Unique name'
|
||||
value={tagName}
|
||||
onChange={(e, {value}) => setTagName(value)}
|
||||
error={tagNameError}
|
||||
onChange={handleTagNameChange}
|
||||
/>
|
||||
</Form>
|
||||
|
||||
|
|
@ -275,7 +285,7 @@ function EditTagsModal() {
|
|||
size='big'
|
||||
onClick={localSaveTag}
|
||||
style={{marginTop: '2em'}}
|
||||
disabled={!!!tagName}
|
||||
disabled={disabled}
|
||||
>Save</APIButton>
|
||||
|
||||
<Divider/>
|
||||
|
|
|
|||
|
|
@ -2,5 +2,5 @@
|
|||
Encoding=UTF-8
|
||||
Name=WROLPi Help
|
||||
Type=Link
|
||||
URL=https://127.0.0.1:8086
|
||||
URL=http://127.0.0.1:9086
|
||||
Icon=/opt/wrolpi-help/venv/lib/python3.11/site-packages/mkdocs/themes/mkdocs/img/favicon.ico
|
||||
|
|
|
|||
|
|
@ -113,6 +113,8 @@ def video_factory(test_session, test_directory):
|
|||
(test_directory / 'videos/NO CHANNEL').mkdir(exist_ok=True, parents=True)
|
||||
path = test_directory / f'videos/NO CHANNEL/{title}.mp4'
|
||||
|
||||
assert str(path).startswith(str(test_directory)), 'Video must be in the test directory'
|
||||
|
||||
# Create a real video file for mimetype.
|
||||
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', path)
|
||||
|
||||
|
|
|
|||
|
|
@ -339,10 +339,13 @@ class Video(ModelHelper, Base):
|
|||
raise UnknownVideo(f'Cannot find Video with id {id_}')
|
||||
return video
|
||||
|
||||
def add_tag(self, tag_id_or_name: int, session: Session = None) -> TagFile:
|
||||
def add_tag(self, tag_id_or_name: int | str, session: Session = None) -> TagFile:
|
||||
session = session or Session.object_session(self)
|
||||
tag = Tag.find_by_name(tag_id_or_name) if isinstance(tag_id_or_name, str) else Tag.find_by_id(tag_id_or_name)
|
||||
return self.file_group.add_tag(tag.id, session=session)
|
||||
return self.file_group.add_tag(tag_id_or_name, session=session)
|
||||
|
||||
def untag(self, tag_id_or_name: int | str, session: Session = None):
|
||||
session = session or Session.object_session(self)
|
||||
self.file_group.untag(tag_id_or_name, session)
|
||||
|
||||
async def get_ffprobe_json(self) -> dict:
|
||||
"""Return the ffprobe json object if previously stored.
|
||||
|
|
|
|||
|
|
@ -464,7 +464,7 @@ class WROLPiConfig(ConfigFile):
|
|||
hotspot_password='wrolpi hotspot',
|
||||
hotspot_ssid='WROLPi',
|
||||
ignore_outdated_zims=False,
|
||||
ignored_directories=['/media/wrolpi/config', ],
|
||||
ignored_directories=['config', 'tags'],
|
||||
map_directory='map',
|
||||
nav_color='violet',
|
||||
throttle_on_startup=False,
|
||||
|
|
@ -1871,3 +1871,8 @@ def is_valid_hex_color(hex_color: str) -> bool:
|
|||
# Regular expression to match valid HTML hex color codes
|
||||
hex_color_regex = re.compile(r'^#([A-F0-9]{6}|[A-F0-9]{3})$', re.IGNORECASE)
|
||||
return bool(hex_color_regex.match(hex_color))
|
||||
|
||||
|
||||
def is_hardlinked(path: pathlib.Path) -> bool:
|
||||
"""Returns True only if `path` has more than one link."""
|
||||
return path.stat().st_nlink > 1
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ from wrolpi.downloader import DownloadManager, DownloadResult, Download, Downloa
|
|||
downloads_manager_config_context
|
||||
from wrolpi.errors import UnrecoverableDownloadError
|
||||
from wrolpi.files.models import Directory, FileGroup
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.tags import Tag, upsert_tag
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
|
|
@ -511,10 +511,7 @@ def tag_factory(test_session):
|
|||
def factory(name: str = None) -> Tag:
|
||||
if not name:
|
||||
name = names.pop(0)
|
||||
tag = Tag(name=name, color=f'#{str(count) * 6}')
|
||||
test_session.add(tag)
|
||||
test_session.commit()
|
||||
test_session.flush([tag, ])
|
||||
tag = upsert_tag(name, f'#{str(count) * 6}')
|
||||
return tag
|
||||
|
||||
return factory
|
||||
|
|
|
|||
|
|
@ -466,6 +466,10 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime):
|
|||
def remove_files_in_ignored_directories(files: List[pathlib.Path]) -> List[pathlib.Path]:
|
||||
"""Return a new list which does not contain any file paths that are in ignored directories."""
|
||||
ignored_directories = list(map(str, get_wrolpi_config().ignored_directories))
|
||||
for idx, ignored_directory in enumerate(ignored_directories):
|
||||
ignored_directory = pathlib.Path(ignored_directory)
|
||||
if not ignored_directory.is_absolute():
|
||||
ignored_directories[idx] = str(get_media_directory() / ignored_directory)
|
||||
files = [i for i in files if not any(str(i).startswith(j) for j in ignored_directories)]
|
||||
return files
|
||||
|
||||
|
|
|
|||
|
|
@ -11,13 +11,13 @@ from sqlalchemy.orm import deferred, relationship, Session
|
|||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.common import Base, ModelHelper, tsvector, logger, recursive_map, get_media_directory, \
|
||||
get_relative_to_media_directory
|
||||
get_relative_to_media_directory, escape_file_name
|
||||
from wrolpi.dates import TZDateTime, now, from_timestamp, strptime_ms, strftime
|
||||
from wrolpi.db import optional_session
|
||||
from wrolpi.errors import FileGroupIsTagged, UnknownFile
|
||||
from wrolpi.files import indexers
|
||||
from wrolpi.media_path import MediaPathType
|
||||
from wrolpi.tags import Tag, TagFile
|
||||
from wrolpi.tags import Tag, TagFile, get_tags_directory
|
||||
from wrolpi.vars import PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -404,6 +404,17 @@ class FileGroup(ModelHelper, Base):
|
|||
|
||||
raise UnknownFile(f'Cannot model file with mimetype {self.mimetype}')
|
||||
|
||||
def get_tag_directory_paths_map(self) -> dict[pathlib.Path, str]:
|
||||
"""Return all links that should exist for this FileGroup in the Tags Directory."""
|
||||
if not self.tag_names:
|
||||
raise RuntimeError(f'Did not get any tag names for {self}')
|
||||
|
||||
tag_names = ', '.join(sorted(self.tag_names))
|
||||
files = dict()
|
||||
for file in self.my_paths():
|
||||
files[file] = f'{tag_names}/{file.name}'
|
||||
return files
|
||||
|
||||
|
||||
class Directory(ModelHelper, Base):
|
||||
"""A representation of a file directory in the media directory."""
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ async def test_delete_file_link(test_async_client, test_session, test_directory)
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_tagged(test_session, make_files_structure, tag_factory, video_bytes):
|
||||
async def test_delete_tagged(test_async_client, test_session, make_files_structure, tag_factory, video_bytes):
|
||||
"""Cannot delete a file that has been tagged."""
|
||||
tag = tag_factory()
|
||||
make_files_structure({'foo/bar.txt': 'asdf', 'foo/bar.mp4': video_bytes})
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ from sqlalchemy.orm import relationship, Session
|
|||
|
||||
from wrolpi import dates
|
||||
from wrolpi.common import ModelHelper, Base, logger, ConfigFile, get_media_directory, background_task, run_after, \
|
||||
register_refresh_cleanup, get_relative_to_media_directory, is_valid_hex_color
|
||||
register_refresh_cleanup, get_relative_to_media_directory, is_valid_hex_color, walk, escape_file_name
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.db import optional_session, get_db_curs
|
||||
from wrolpi.errors import UnknownTag, UsedTag, InvalidTag, FileGroupAlreadyTagged
|
||||
|
|
@ -18,6 +18,10 @@ from wrolpi.vars import PYTEST
|
|||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
def get_tags_directory() -> pathlib.Path:
|
||||
return get_media_directory() / 'tags'
|
||||
|
||||
|
||||
class TagFile(ModelHelper, Base):
|
||||
__tablename__ = 'tag_file'
|
||||
created_at: datetime = Column(TZDateTime, default=dates.now)
|
||||
|
|
@ -27,6 +31,9 @@ class TagFile(ModelHelper, Base):
|
|||
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), primary_key=True)
|
||||
file_group = relationship('FileGroup', back_populates='tag_files')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<TagFile tag={self.tag.name=} file_group={self.file_group.primary_path}>'
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_by_primary_keys(file_group_id: int, tag_id: int, session: Session = None) -> Optional['TagFile']:
|
||||
|
|
@ -90,6 +97,7 @@ class Tag(ModelHelper, Base):
|
|||
|
||||
# Save changes to config.
|
||||
save_tags_config(session)
|
||||
sync_tags_directory(session)
|
||||
return tag_file
|
||||
|
||||
@staticmethod
|
||||
|
|
@ -102,9 +110,11 @@ class Tag(ModelHelper, Base):
|
|||
if tag_file:
|
||||
session.delete(tag_file)
|
||||
session.commit()
|
||||
logger.debug(f'Deleted TagFile: {tag_file}')
|
||||
|
||||
# Save changes to config.
|
||||
save_tags_config(session)
|
||||
sync_tags_directory(session)
|
||||
else:
|
||||
logger.warning(f'Could not find TagFile for FileGroup.id={file_group_id}/Tag.id={tag_id_or_name}')
|
||||
|
||||
|
|
@ -261,6 +271,86 @@ def save_tags_config(session: Session = None):
|
|||
background_task(_())
|
||||
|
||||
|
||||
def _sync_tags_directory_tag_files(tags_directory: pathlib.Path, session: Session) -> List[pathlib.Path]:
|
||||
"""Create all links that should be in the Tags Directory. Return all links that should exist."""
|
||||
from wrolpi.files.models import FileGroup
|
||||
tag_files: List[Tuple[Tag, TagFile, FileGroup]] = session.query(Tag, TagFile, FileGroup) \
|
||||
.outerjoin(Tag, FileGroup).all()
|
||||
links = list()
|
||||
for tag, tag_file, file_group in tag_files:
|
||||
for file, link in file_group.get_tag_directory_paths_map().items():
|
||||
link = tags_directory / link
|
||||
if not link.is_file():
|
||||
link.parent.mkdir(parents=True, exist_ok=True)
|
||||
link.hardlink_to(file)
|
||||
links.append(link)
|
||||
|
||||
return links
|
||||
|
||||
|
||||
# Files that should never be deleted from the Tags Directory.
|
||||
IGNORED_TAG_DIRECTORY_FILES = {
|
||||
'README.txt',
|
||||
}
|
||||
|
||||
|
||||
def _delete_extra_tags_directory_paths(directory: pathlib.Path, links: List[pathlib.Path]):
|
||||
# Get all files that should exist.
|
||||
links = set(links)
|
||||
directory_paths = set(walk(directory))
|
||||
tags_directory_files = {i for i in directory_paths if i.is_file()}
|
||||
|
||||
# Get all directories that should exist.
|
||||
link_directories = {i.parent for i in links if i.is_file()}
|
||||
tags_directory_directories = {i for i in directory_paths if i.is_dir()}
|
||||
|
||||
# Delete any files that should not exist.
|
||||
ignored_files = {directory / i for i in IGNORED_TAG_DIRECTORY_FILES}
|
||||
extra_files = tags_directory_files - links - ignored_files
|
||||
for file in extra_files:
|
||||
if file.stat().st_nlink > 1:
|
||||
logger.debug(f'Deleting extra Tags Directory file: {file}')
|
||||
file.unlink()
|
||||
else:
|
||||
logger.warning(f'Refusing to delete Tag Directory file which does not have another link: {file}')
|
||||
|
||||
# Delete any directories that should not exist.
|
||||
extra_directories = tags_directory_directories - link_directories
|
||||
for directory in extra_directories:
|
||||
if next(directory.iterdir(), None):
|
||||
logger.warning(f'Refusing to delete extra Tags Directory directory which contains files: {directory}')
|
||||
else:
|
||||
logger.debug(f'Deleting extra Tags Directory directory: {directory}')
|
||||
directory.rmdir()
|
||||
|
||||
|
||||
def create_tags_directory(directory: pathlib.Path):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
readme = directory / 'README.txt'
|
||||
readme.write_text('''This directory exists to allow a secondary way to access your tagged files. Files are
|
||||
organized in a directory named after all the Tags they have been tagged with.
|
||||
|
||||
WARNING: This directory is controlled by WROLPi, any files you put in here will be automatically deleted!
|
||||
''')
|
||||
|
||||
|
||||
@optional_session
|
||||
def sync_tags_directory(session: Session = None):
|
||||
"""Synchronizes database Tags with the Tags directory (typically /media/wrolpi/tags). Removes any
|
||||
files that do not belong in the Tags Directory."""
|
||||
try:
|
||||
tags_directory = get_tags_directory()
|
||||
create_tags_directory(tags_directory)
|
||||
|
||||
links = _sync_tags_directory_tag_files(tags_directory, session)
|
||||
logger.debug(f'Tags Directory should contain {len(links)} links')
|
||||
_delete_extra_tags_directory_paths(tags_directory, links)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync DB with tags directory in media directory!', exc_info=e)
|
||||
raise
|
||||
|
||||
|
||||
def get_tags() -> List[dict]:
|
||||
with get_db_curs() as curs:
|
||||
curs.execute('''
|
||||
|
|
@ -283,6 +373,9 @@ def upsert_tag(name: str, color: str, tag_id: int = None, session: Session = Non
|
|||
if not is_valid_hex_color(color):
|
||||
raise InvalidTag('Tag color is invalid')
|
||||
|
||||
# Tag names are used in Tags Directory, so they must be valid file names.
|
||||
name = escape_file_name(name)
|
||||
|
||||
if tag_id:
|
||||
tag = session.query(Tag).filter_by(id=tag_id).one_or_none()
|
||||
if not tag:
|
||||
|
|
@ -302,6 +395,7 @@ def upsert_tag(name: str, color: str, tag_id: int = None, session: Session = Non
|
|||
raise InvalidTag(f'Name already taken') from e
|
||||
|
||||
save_tags_config()
|
||||
sync_tags_directory()
|
||||
|
||||
return tag
|
||||
|
||||
|
|
@ -321,6 +415,7 @@ def delete_tag(tag_id: int, session: Session = None):
|
|||
session.commit()
|
||||
|
||||
save_tags_config()
|
||||
sync_tags_directory()
|
||||
|
||||
|
||||
@register_refresh_cleanup
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import pytest
|
|||
import yaml
|
||||
|
||||
from wrolpi import tags
|
||||
from wrolpi.common import is_hardlinked, walk
|
||||
from wrolpi.errors import FileGroupIsTagged, InvalidTag, UnknownTag, FileGroupAlreadyTagged
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
|
@ -333,3 +334,105 @@ async def test_invalid_tag(test_async_client, test_session, test_directory):
|
|||
|
||||
with pytest.raises(UnknownTag):
|
||||
tags.delete_tag(1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tags_directory(test_async_client, test_session, test_directory, tag_factory, video_factory,
|
||||
example_pdf):
|
||||
readme = test_directory / 'tags/README.txt'
|
||||
|
||||
# Should be deleted on sync.
|
||||
(test_directory / 'tags/should be deleted').mkdir(parents=True)
|
||||
(test_directory / 'tags/cannot be deleted').mkdir(parents=True)
|
||||
(test_directory / 'tags/cannot be deleted/because of this file').touch()
|
||||
|
||||
tag1, tag2 = tag_factory('First Aid'), tag_factory('Special/name')
|
||||
vid1 = video_factory(with_video_file=test_directory / 'vid1.mp4', with_caption_file=True, with_info_json=True,
|
||||
with_poster_ext='jpg')
|
||||
vid2 = video_factory(with_video_file=test_directory / 'vid2.mp4', with_info_json=True)
|
||||
pdf = FileGroup.from_paths(test_session, example_pdf)
|
||||
assert 'vid1' in str(vid1.file_group.primary_path)
|
||||
assert 'vid2' in str(vid2.file_group.primary_path)
|
||||
assert 'pdf' in str(pdf.primary_path)
|
||||
assert readme.is_file() and readme.stat().st_size > 0
|
||||
|
||||
def assert_tag_links(paths: list[str]):
|
||||
for path in paths:
|
||||
path = test_directory / f'tags/{path}'
|
||||
if not path.is_file():
|
||||
raise AssertionError(f'Expected {path} to be a file')
|
||||
if not is_hardlinked(path):
|
||||
raise AssertionError(f'Expected {path} to be linked')
|
||||
|
||||
# Readme should always exist.
|
||||
assert readme.is_file() and readme.stat().st_size > 0
|
||||
|
||||
# Video1 tagged with First Aid and Special/name.
|
||||
vid1.add_tag(tag1.id)
|
||||
vid1.add_tag(tag2.id)
|
||||
# Video2 tagged with First Aid.
|
||||
vid2.add_tag(tag1.id)
|
||||
# PDF tagged with Special/name.
|
||||
pdf.add_tag(tag2.id)
|
||||
assert_tag_links([
|
||||
'First Aid, Special⧸name/vid1.en.vtt',
|
||||
'First Aid, Special⧸name/vid1.en.vtt',
|
||||
'First Aid, Special⧸name/vid1.info.json',
|
||||
'First Aid, Special⧸name/vid1.jpg',
|
||||
'First Aid, Special⧸name/vid1.mp4',
|
||||
'First Aid/vid2.info.json',
|
||||
'First Aid/vid2.mp4',
|
||||
'Special⧸name/pdf example.pdf',
|
||||
])
|
||||
|
||||
# Extra directories and files are deleted, if possible.
|
||||
assert len(list(walk(test_directory / 'tags'))) == 13
|
||||
assert not (test_directory / 'tags/should be deleted').exists()
|
||||
assert (test_directory / 'tags/cannot be deleted/because of this file').is_file()
|
||||
assert test_session.query(TagFile).count() == 4
|
||||
|
||||
# Video1 tagged with First Aid only.
|
||||
vid1.untag(tag2.id)
|
||||
assert_tag_links([
|
||||
'First Aid/vid1.en.vtt',
|
||||
'First Aid/vid1.en.vtt',
|
||||
'First Aid/vid1.info.json',
|
||||
'First Aid/vid1.jpg',
|
||||
'First Aid/vid1.mp4',
|
||||
'First Aid/vid2.info.json',
|
||||
'First Aid/vid2.mp4',
|
||||
'Special⧸name/pdf example.pdf',
|
||||
])
|
||||
assert len(list(walk(test_directory / 'tags'))) == 12
|
||||
assert not (test_directory / 'tags/First Aid, Special⧸name').exists()
|
||||
assert test_session.query(TagFile).count() == 3
|
||||
|
||||
# PDF no longer tagged.
|
||||
pdf.untag(tag2.id)
|
||||
assert_tag_links([
|
||||
'First Aid/vid1.en.vtt',
|
||||
'First Aid/vid1.en.vtt',
|
||||
'First Aid/vid1.info.json',
|
||||
'First Aid/vid1.jpg',
|
||||
'First Aid/vid1.mp4',
|
||||
'First Aid/vid2.info.json',
|
||||
'First Aid/vid2.mp4',
|
||||
])
|
||||
assert len(list(walk(test_directory / 'tags'))) == 10
|
||||
assert not (test_directory / 'tags/Special⧸name').exists()
|
||||
assert not (test_directory / 'tags/Special⧸name/pdf example.pdf').exists()
|
||||
assert test_session.query(TagFile).count() == 2
|
||||
|
||||
# No more tagged files.
|
||||
vid1.untag(tag1.id)
|
||||
vid2.untag(tag1.id)
|
||||
assert test_session.query(TagFile).count() == 0
|
||||
# Readme, and un-deletable file and directory exist.
|
||||
assert len(list(walk(test_directory / 'tags'))) == 3
|
||||
assert (test_directory / 'tags').is_dir()
|
||||
assert not (test_directory / 'tags/First Aid').exists(), \
|
||||
f'First Aid lingers and contains: {[i.name for i in (test_directory / "tags/First Aid").iterdir()]}'
|
||||
|
||||
# Only three FileGroups were created. Tags Directory files are ignored during refresh.
|
||||
await files_lib.refresh_files()
|
||||
assert test_session.query(FileGroup).count() == 3
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue