Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions backend/app/database/folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,91 @@ def db_get_direct_child_folders(parent_folder_id: str) -> List[Tuple[str, str]]:
conn.close()


def db_get_all_subfolders() -> List[FolderIdPath]:
"""
Get all folders that have a parent folder.
Returns list of tuples (folder_id, folder_path).
"""
conn = sqlite3.connect(DATABASE_PATH)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
cursor = conn.cursor()

try:
cursor.execute(
"""
SELECT folder_id, folder_path FROM folders
WHERE parent_folder_id IS NOT NULL
"""
)
return cursor.fetchall()
finally:
conn.close()


def db_get_media_sizes_under_path(folder_path: FolderPath) -> Dict[str, Optional[int]]:
"""
Get every image and video stored at any depth below folder_path.
Returns a dict mapping each path to its recorded file size, or None if unknown.
"""
prefix = folder_path + os.sep
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()

try:
cursor.execute(
"""
SELECT path, CASE WHEN json_valid(metadata)
THEN json_extract(metadata, '$.file_size') END
FROM images WHERE substr(path, 1, ?) = ?
UNION ALL
SELECT path, CASE WHEN json_valid(metadata)
THEN json_extract(metadata, '$.file_size') END
FROM videos WHERE substr(path, 1, ?) = ?
""",
(len(prefix), prefix, len(prefix), prefix),
)
return dict(cursor.fetchall())
finally:
conn.close()


def db_relocate_folder_tree(
folder_id: FolderId,
old_path: FolderPath,
new_path: FolderPath,
parent_folder_id: FolderId,
) -> None:
"""
Point a folder, its subfolders and their images and videos at new_path,
keeping every row and its id.
"""
old_prefix = old_path + os.sep
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()

try:
for table, column in (
("folders", "folder_path"),
("images", "path"),
("videos", "path"),
):
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
cursor.execute(
f"UPDATE {table} SET {column} = ? || substr({column}, ?) "
f"WHERE {column} = ? OR substr({column}, 1, ?) = ?",
(new_path, len(old_path) + 1, old_path, len(old_prefix), old_prefix),
)
Comment thread
harshvardhanrp marked this conversation as resolved.
Resolved
cursor.execute(
"UPDATE folders SET parent_folder_id = ? WHERE folder_id = ?",
(parent_folder_id, folder_id),
)
conn.commit()
except sqlite3.Error as e:
logger.error(f"Error relocating folder tree: {e}")
conn.rollback()
raise
finally:
conn.close()


def db_set_tagging_completed(completed: bool) -> int:
"""
Mark every AI-tagged folder as finished tagging, or back to pending.
Expand Down
69 changes: 69 additions & 0 deletions backend/app/database/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,75 @@ def db_get_image_sync_state_by_folder_ids(
conn.close()


def db_get_images_by_file_keys(
keys: Set[Tuple[int, int]],
) -> List[Tuple[ImageId, ImagePath, Optional[str], Tuple[int, int]]]:
"""
Get the images whose recorded (file_size, file_mtime) is one of keys.

Returns:
List of tuples containing (image_id, image_path, thumbnail_path, key)
"""
if not keys:
return []

conn = _connect()
cursor = conn.cursor()

try:
cursor.execute(
"""
SELECT id, path, thumbnailPath,
json_extract(metadata, '$.file_size'),
json_extract(metadata, '$.file_mtime')
FROM images
WHERE json_valid(metadata)
"""
)
return [
(image_id, path, thumbnail_path, (size, mtime))
for image_id, path, thumbnail_path, size, mtime in cursor.fetchall()
if (size, mtime) in keys
]
except sqlite3.Error as e:
logger.error(f"Error getting images by file keys: {e}")
return []
finally:
conn.close()


def db_relocate_images(image_records: List[ImageRecord]) -> bool:
"""
Update the path, folder and metadata of existing images, matched by id.

Returns:
True if the update was successful, False otherwise
"""
if not image_records:
return True

conn = _connect()
cursor = conn.cursor()

try:
cursor.executemany(
"""
UPDATE images
SET path = :path, folder_id = :folder_id, metadata = :metadata
WHERE id = :id
""",
image_records,
)
conn.commit()
return True
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except sqlite3.Error as e:
logger.error(f"Error relocating images: {e}")
conn.rollback()
return False
finally:
conn.close()


def db_delete_images_by_ids(image_ids: List[ImageId]) -> bool:
"""
Delete multiple images from the database by their IDs.
Expand Down
71 changes: 70 additions & 1 deletion backend/app/database/videos.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Standard library imports
import sqlite3
from typing import Any, List, Mapping, Optional, Tuple, TypedDict, Union
from typing import Any, List, Mapping, Optional, Set, Tuple, TypedDict, Union
import json

from datetime import datetime
Expand Down Expand Up @@ -309,6 +309,75 @@ def db_get_videos_by_folder_ids(
conn.close()


def db_get_videos_by_file_keys(
keys: Set[Tuple[int, str]],
) -> List[Tuple[VideoId, VideoPath, Optional[str], Tuple[int, str]]]:
"""
Get the videos whose recorded (file_size, file_modified) is one of keys.

Returns:
List of tuples containing (video_id, video_path, thumbnail_path, key)
"""
if not keys:
return []

conn = _connect()
cursor = conn.cursor()

try:
cursor.execute(
"""
SELECT id, path, thumbnailPath,
json_extract(metadata, '$.file_size'),
json_extract(metadata, '$.file_modified')
FROM videos
WHERE json_valid(metadata)
"""
)
return [
(video_id, path, thumbnail_path, (size, modified))
for video_id, path, thumbnail_path, size, modified in cursor.fetchall()
if (size, modified) in keys
]
except sqlite3.Error as e:
logger.error(f"Error getting videos by file keys: {e}")
return []
finally:
conn.close()


def db_relocate_videos(video_records: List[VideoRecord]) -> bool:
"""
Update the path, folder and metadata of existing videos, matched by id.

Returns:
True if the update was successful, False otherwise
"""
if not video_records:
return True

conn = _connect()
cursor = conn.cursor()

try:
cursor.executemany(
"""
UPDATE videos
SET path = :path, folder_id = :folder_id, metadata = :metadata
WHERE id = :id
""",
video_records,
)
conn.commit()
return True
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except sqlite3.Error as e:
logger.error(f"Error relocating videos: {e}")
conn.rollback()
return False
finally:
conn.close()


def db_delete_videos_by_ids(video_ids: List[VideoId]) -> bool:
"""
Delete multiple videos from the database by their IDs.
Expand Down
11 changes: 11 additions & 0 deletions backend/app/routes/folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
folder_util_add_multiple_folder_trees,
folder_util_delete_obsolete_folders,
folder_util_get_filesystem_direct_child_folders,
folder_util_relocate_moved_folders,
)
from app.utils.images import (
image_util_process_folder_images,
Expand Down Expand Up @@ -519,6 +520,16 @@ def sync_folder(request: SyncFolderRequest, app_state: State = Depends(get_state
filesystem_folder_set = set(filesystem_folders)
db_folder_paths = {folder_path for folder_id, folder_path in db_child_folders}

# Renamed or moved folders keep their rows, and with them their albums,
# favourites and faces, instead of being deleted and added again
if folder_util_relocate_moved_folders(
filesystem_folder_set - db_folder_paths, request.folder_id
):
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
db_child_folders = db_get_direct_child_folders(request.folder_id)
db_folder_paths = {
folder_path for folder_id, folder_path in db_child_folders
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

folders_to_delete = db_folder_paths - filesystem_folder_set
folders_to_add = filesystem_folder_set - db_folder_paths

Expand Down
70 changes: 69 additions & 1 deletion backend/app/utils/folders.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import uuid
import os
from typing import List, Tuple
from collections import Counter
from typing import Dict, List, Optional, Tuple

from fastapi import HTTPException, status
from app.database.folders import (
db_insert_folders_batch,
db_update_parent_ids_for_subtree,
db_delete_folders_batch,
db_get_all_subfolders,
db_get_media_sizes_under_path,
db_relocate_folder_tree,
)
from app.schemas.folders import ErrorResponse
from app.logging.setup_logging import get_logger
Expand Down Expand Up @@ -176,3 +180,67 @@ def folder_util_add_multiple_folder_trees(
logger.error(f"Error adding folder {folder_path}: {e}")

return added_count, added_folders


def _file_has_size(path: str, size: Optional[int]) -> bool:
try:
return os.path.isfile(path) and (size is None or os.path.getsize(path) == size)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except OSError:
return False


def folder_util_relocate_moved_folders(
folders_to_add: set, parent_folder_id: str
) -> int:
"""
Point subfolders that no longer exist at the new folder they were moved to.

A missing folder matches a new one when every image and video stored under
it is there at the same relative path and size. Only one-to-one matches are
relocated; anything else is left to be deleted and added as usual.

Args:
folders_to_add: Set of folder paths found on disk but not in the database
parent_folder_id: ID of the folder they were found in

Returns:
Number of folders relocated
"""
if not folders_to_add:
return 0

missing_folders = {
folder_path: folder_id
for folder_id, folder_path in db_get_all_subfolders()
if not os.path.isdir(folder_path)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

matches: Dict[str, List[str]] = {}
for old_path in missing_folders:
# Subfolders of a missing folder move with it
if os.path.dirname(old_path) in missing_folders:
continue
media = db_get_media_sizes_under_path(old_path)
if not media:
continue
matches[old_path] = [
new_path
for new_path in folders_to_add
if all(
_file_has_size(
os.path.join(new_path, os.path.relpath(path, old_path)), size
)
for path, size in media.items()
)
]

match_counts = Counter(path for found in matches.values() for path in found)
relocated_count = 0
for old_path, found in matches.items():
if len(found) == 1 and match_counts[found[0]] == 1:
db_relocate_folder_tree(
missing_folders[old_path], old_path, found[0], parent_folder_id
)
relocated_count += 1

return relocated_count
Loading
Loading