Patch: Various feature additions (#625)

- Add admin config for self-settings options visibility. Remove delivery
preferences or notifications from the view.
- Add option to use Booklore's Bookdrop API destination instead of a
specific library
- Add download path options for all torrent clients
This commit is contained in:
Alex authored and GitHub committed 2026-02-20 09:53:47 +00:00
1 parent 8ff2d776ae
commit 554f5fcbe7
21 files changed
+1410 -484

No files matched your search

File diff suppressed because it is too large. Load diff
+27 -2
View File
@@ -868,6 +868,25 @@ def download_settings():
required=True,
show_when={"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
),
SelectField(
key="BOOKLORE_DESTINATION",
label="Upload Destination",
description="Choose whether uploads go directly to a specific library path or to Bookdrop for review.",
options=[
{
"value": "library",
"label": "Specific Library",
"description": "Upload directly into the selected library path.",
},
{
"value": "bookdrop",
"label": "Bookdrop",
"description": "Upload into Bookdrop and review metadata before importing to a library.",
},
],
default="library",
show_when={"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
),
SelectField(
key="BOOKLORE_LIBRARY_ID",
label="Library",
@@ -875,7 +894,10 @@ def download_settings():
options=get_booklore_library_options,
required=True,
user_overridable=True,
show_when={"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
show_when=[
{"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
{"field": "BOOKLORE_DESTINATION", "value": "library"},
],
),
SelectField(
key="BOOKLORE_PATH_ID",
@@ -885,7 +907,10 @@ def download_settings():
required=True,
filter_by_field="BOOKLORE_LIBRARY_ID",
user_overridable=True,
show_when={"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
show_when=[
{"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
{"field": "BOOKLORE_DESTINATION", "value": "library"},
],
),
ActionButton(
key="test_booklore",
+59
View File
@@ -9,6 +9,7 @@ from shelfmark.core.settings_registry import (
CheckboxField,
CustomComponentField,
HeadingField,
MultiSelectField,
NumberField,
SelectField,
TableField,
@@ -49,6 +50,21 @@ _REQUEST_MATRIX_MODE_OPTIONS = [
option for option in _REQUEST_DEFAULT_MODE_OPTIONS if option["value"] != "request_book"
]
_SELF_SETTINGS_SECTION_OPTIONS = [
{
"value": "delivery",
"label": "Delivery Preferences",
"description": "Show personal delivery output and destination settings.",
},
{
"value": "notifications",
"label": "Notifications",
"description": "Show personal notification route settings.",
},
]
_SELF_SETTINGS_SECTION_VALUES = {option["value"] for option in _SELF_SETTINGS_SECTION_OPTIONS}
_SELF_SETTINGS_SECTION_DEFAULTS = [option["value"] for option in _SELF_SETTINGS_SECTION_OPTIONS]
_USERS_HEADING_DESCRIPTION_BY_AUTH_MODE = {
"builtin": (
"Create and manage user accounts directly. Passwords are stored locally and users sign in "
@@ -133,6 +149,38 @@ def _get_request_policy_rule_columns():
def _on_save_users(values):
"""Validate users/request-policy settings before persistence."""
if "VISIBLE_SELF_SETTINGS_SECTIONS" in values:
raw_sections = values["VISIBLE_SELF_SETTINGS_SECTIONS"]
if raw_sections is None:
candidate_sections: list[str] = []
elif isinstance(raw_sections, str):
candidate_sections = [s.strip() for s in raw_sections.split(",") if s.strip()]
elif isinstance(raw_sections, (list, tuple, set)):
candidate_sections = [str(section).strip() for section in raw_sections if str(section).strip()]
else:
return {
"error": True,
"message": "VISIBLE_SELF_SETTINGS_SECTIONS must be a list of section identifiers",
"values": values,
}
normalized_sections: list[str] = []
for section in candidate_sections:
if section not in _SELF_SETTINGS_SECTION_VALUES:
allowed = ", ".join(sorted(_SELF_SETTINGS_SECTION_VALUES))
return {
"error": True,
"message": (
"VISIBLE_SELF_SETTINGS_SECTIONS contains an unsupported section "
f"'{section}'. Supported values: {allowed}"
),
"values": values,
}
if section not in normalized_sections:
normalized_sections.append(section)
values["VISIBLE_SELF_SETTINGS_SECTIONS"] = normalized_sections
if "REQUEST_POLICY_DEFAULT_EBOOK" in values:
if parse_policy_mode(values["REQUEST_POLICY_DEFAULT_EBOOK"]) is None:
return {
@@ -179,6 +227,17 @@ def users_settings():
key="users_management",
component="users_management",
),
MultiSelectField(
key="VISIBLE_SELF_SETTINGS_SECTIONS",
label="Visible Self-Settings Sections",
description=(
"Choose which personal settings sections are shown in My Account for non-admin users."
),
options=_SELF_SETTINGS_SECTION_OPTIONS,
default=_SELF_SETTINGS_SECTION_DEFAULTS,
variant="dropdown",
env_supported=False,
),
HeadingField(
key="requests_heading",
title="Requests",
+77 -19
View File
@@ -31,6 +31,14 @@ from shelfmark.core.user_db import UserDB
logger = setup_logger(__name__)
MIN_PASSWORD_LENGTH = 4
_VISIBLE_SELF_SETTINGS_SECTIONS_KEY = "VISIBLE_SELF_SETTINGS_SECTIONS"
_SELF_SETTINGS_SECTION_DELIVERY = "delivery"
_SELF_SETTINGS_SECTION_NOTIFICATIONS = "notifications"
_VALID_SELF_SETTINGS_SECTIONS = (
_SELF_SETTINGS_SECTION_DELIVERY,
_SELF_SETTINGS_SECTION_NOTIFICATIONS,
)
_DEFAULT_VISIBLE_SELF_SETTINGS_SECTIONS = list(_VALID_SELF_SETTINGS_SECTIONS)
def _get_auth_mode() -> str:
@@ -108,6 +116,53 @@ def _serialize_self_user(user: Mapping[str, Any], auth_mode: str) -> dict[str, A
return payload
def _normalize_visible_self_settings_sections(raw_sections: Any) -> list[str]:
"""Normalize users.VISIBLE_SELF_SETTINGS_SECTIONS to a safe ordered list."""
if raw_sections is None:
return list(_DEFAULT_VISIBLE_SELF_SETTINGS_SECTIONS)
if isinstance(raw_sections, str):
candidate_sections = [s.strip() for s in raw_sections.split(",") if s.strip()]
elif isinstance(raw_sections, (list, tuple, set)):
candidate_sections = [str(section).strip() for section in raw_sections if str(section).strip()]
else:
return list(_DEFAULT_VISIBLE_SELF_SETTINGS_SECTIONS)
normalized_sections: list[str] = []
for section in candidate_sections:
if section in _VALID_SELF_SETTINGS_SECTIONS and section not in normalized_sections:
normalized_sections.append(section)
if not normalized_sections and candidate_sections:
# Invalid non-empty config should fail-safe to showing defaults.
return list(_DEFAULT_VISIBLE_SELF_SETTINGS_SECTIONS)
return normalized_sections
def _get_visible_self_settings_sections() -> list[str]:
users_config = load_config_file("users")
raw_sections = users_config.get(_VISIBLE_SELF_SETTINGS_SECTIONS_KEY)
return _normalize_visible_self_settings_sections(raw_sections)
def _get_allowed_self_settings_keys(visible_sections: list[str]) -> set[str]:
allowed_keys: set[str] = set()
visible_sections_set = set(visible_sections)
if _SELF_SETTINGS_SECTION_DELIVERY in visible_sections_set:
allowed_keys |= {
key for key, _field in _get_ordered_user_overridable_fields("downloads")
}
if _SELF_SETTINGS_SECTION_NOTIFICATIONS in visible_sections_set:
allowed_keys |= {
key for key, _field in _get_ordered_user_overridable_fields("notifications")
}
return allowed_keys
def register_self_user_routes(app: Flask, user_db: UserDB) -> None:
"""Register self-service user endpoints."""
@@ -121,22 +176,27 @@ def register_self_user_routes(app: Flask, user_db: UserDB) -> None:
auth_mode = _get_auth_mode()
serialized_user = _serialize_self_user(user, auth_mode)
serialized_user["settings"] = user_db.get_user_settings(user_id)
visible_self_settings_sections = _get_visible_self_settings_sections()
try:
delivery_preferences = _build_user_preferences_payload(user_db, user_id, "downloads")
except ValueError:
return jsonify({"error": "Downloads settings tab not found"}), 500
except Exception as exc:
logger.warning(f"Failed to build user delivery preferences for user_id={user_id}: {exc}")
delivery_preferences = None
delivery_preferences = None
if _SELF_SETTINGS_SECTION_DELIVERY in visible_self_settings_sections:
try:
delivery_preferences = _build_user_preferences_payload(user_db, user_id, "downloads")
except ValueError:
return jsonify({"error": "Downloads settings tab not found"}), 500
except Exception as exc:
logger.warning(f"Failed to build user delivery preferences for user_id={user_id}: {exc}")
delivery_preferences = None
try:
notification_preferences = _build_user_preferences_payload(user_db, user_id, "notifications")
except ValueError:
return jsonify({"error": "Notifications settings tab not found"}), 500
except Exception as exc:
logger.warning(f"Failed to build user notification preferences for user_id={user_id}: {exc}")
notification_preferences = None
notification_preferences = None
if _SELF_SETTINGS_SECTION_NOTIFICATIONS in visible_self_settings_sections:
try:
notification_preferences = _build_user_preferences_payload(user_db, user_id, "notifications")
except ValueError:
return jsonify({"error": "Notifications settings tab not found"}), 500
except Exception as exc:
logger.warning(f"Failed to build user notification preferences for user_id={user_id}: {exc}")
notification_preferences = None
user_overridable_keys = sorted(
set(delivery_preferences.get("keys", []) if delivery_preferences else [])
@@ -149,6 +209,7 @@ def register_self_user_routes(app: Flask, user_db: UserDB) -> None:
"deliveryPreferences": delivery_preferences,
"notificationPreferences": notification_preferences,
"userOverridableKeys": user_overridable_keys,
"visibleUserSettingsSections": visible_self_settings_sections,
}
)
@@ -251,11 +312,8 @@ def register_self_user_routes(app: Flask, user_db: UserDB) -> None:
if not isinstance(settings_payload, dict):
return jsonify({"error": "Settings must be an object"}), 400
allowed_user_settings_keys = {
key for key, _field in _get_ordered_user_overridable_fields("downloads")
} | {
key for key, _field in _get_ordered_user_overridable_fields("notifications")
}
visible_self_settings_sections = _get_visible_self_settings_sections()
allowed_user_settings_keys = _get_allowed_self_settings_keys(visible_self_settings_sections)
disallowed_keys = sorted(
key for key in settings_payload if key not in allowed_user_settings_keys
)
+3
View File
@@ -97,6 +97,7 @@ class DelugeClient(DownloadClient):
self._rpc_id = 0
self._category = str(config.get("DELUGE_CATEGORY", "books") or "books")
self._download_dir = str(config.get("DELUGE_DOWNLOAD_DIR", "") or "")
def _next_rpc_id(self) -> int:
self._rpc_id += 1
@@ -232,6 +233,8 @@ class DelugeClient(DownloadClient):
raise Exception("Failed to fetch torrent file")
options: dict[str, Any] = {}
if self._download_dir:
options["download_location"] = self._download_dir
if torrent_info.is_magnet:
magnet_url = torrent_info.magnet_url or url
@@ -139,6 +139,7 @@ class QBittorrentClient(DownloadClient):
password=config.get("QBITTORRENT_PASSWORD", ""),
)
self._category = config.get("QBITTORRENT_CATEGORY", "books")
self._download_dir = config.get("QBITTORRENT_DOWNLOAD_DIR", "")
self._tags = _normalize_tags(config.get("QBITTORRENT_TAG", []))
@@ -306,6 +307,8 @@ class QBittorrentClient(DownloadClient):
"category": category,
"rename": name,
}
if self._download_dir:
add_kwargs["save_path"] = self._download_dir
if tags:
add_kwargs["tags"] = ",".join(tags)
+21
View File
@@ -390,6 +390,13 @@ def prowlarr_clients_settings():
default="",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "qbittorrent"},
),
TextField(
key="QBITTORRENT_DOWNLOAD_DIR",
label="Download Directory",
description="Server-side directory where torrents are downloaded (optional, uses qBittorrent default if not specified)",
placeholder="/downloads",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "qbittorrent"},
),
TagListField(
key="QBITTORRENT_TAG",
label="Tags",
@@ -444,6 +451,13 @@ def prowlarr_clients_settings():
default="",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "transmission"},
),
TextField(
key="TRANSMISSION_DOWNLOAD_DIR",
label="Download Directory",
description="Server-side directory where torrents are downloaded (optional, uses Transmission default if not specified)",
placeholder="/downloads",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "transmission"},
),
# --- Deluge Settings ---
TextField(
@@ -492,6 +506,13 @@ def prowlarr_clients_settings():
default="",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "deluge"},
),
TextField(
key="DELUGE_DOWNLOAD_DIR",
label="Download Directory",
description="Server-side directory where torrents are downloaded (optional, uses Deluge default if not specified)",
placeholder="/downloads",
show_when={"field": "PROWLARR_TORRENT_CLIENT", "value": "deluge"},
),
# --- rTorrent Settings ---
TextField(
+9 -2
View File
@@ -71,6 +71,7 @@ class TransmissionClient(DownloadClient):
except Exception:
pass
self._category = config.get("TRANSMISSION_CATEGORY", "books")
self._download_dir = config.get("TRANSMISSION_DOWNLOAD_DIR", "")
@staticmethod
def is_configured() -> bool:
@@ -115,18 +116,24 @@ class TransmissionClient(DownloadClient):
resolved_category = category or self._category or ""
torrent_info = extract_torrent_info(url, expected_hash=expected_hash)
add_kwargs = {}
if resolved_category:
add_kwargs["labels"] = [resolved_category]
if self._download_dir:
add_kwargs["download_dir"] = self._download_dir
if torrent_info.torrent_data:
torrent = self._client.add_torrent(
torrent=torrent_info.torrent_data,
labels=[resolved_category] if resolved_category else None,
**add_kwargs,
)
else:
# Use magnet URL if available, otherwise original URL
add_url = torrent_info.magnet_url or url
torrent = self._client.add_torrent(
torrent=add_url,
labels=[resolved_category] if resolved_category else None,
**add_kwargs,
)
torrent_hash = torrent.hashString.lower()
+59 -22
View File
@@ -18,6 +18,8 @@ from shelfmark.download.staging import STAGE_MOVE, STAGE_NONE, build_staging_dir
logger = setup_logger(__name__)
BOOKLORE_OUTPUT_MODE = "booklore"
BOOKLORE_DESTINATION_LIBRARY = "library"
BOOKLORE_DESTINATION_BOOKDROP = "bookdrop"
BOOKLORE_SUPPORTED_EXTENSIONS = {".azw", ".azw3", ".cb7", ".cbr", ".cbz", ".epub", ".fb2", ".mobi", ".pdf"}
BOOKLORE_SUPPORTED_FORMATS_LABEL = ", ".join(
ext.lstrip(".").upper() for ext in sorted(BOOKLORE_SUPPORTED_EXTENSIONS)
@@ -36,6 +38,7 @@ class BookloreConfig:
library_id: int
path_id: int
verify_tls: bool = True
upload_to_bookdrop: bool = False
refresh_after_upload: bool = False
@@ -48,6 +51,13 @@ def _parse_int(value: Any, label: str) -> int:
raise BookloreError(f"{label} must be a number") from exc
def _parse_destination(value: Any) -> str:
normalized = str(value or "").strip().lower()
if normalized == BOOKLORE_DESTINATION_BOOKDROP:
return BOOKLORE_DESTINATION_BOOKDROP
return BOOKLORE_DESTINATION_LIBRARY
def build_booklore_config(
values: Mapping[str, Any],
user_id: Optional[int] = None,
@@ -63,24 +73,32 @@ def build_booklore_config(
if not password:
raise BookloreError("Booklore password is required")
# Resolve library/path through config so user override precedence is centralized.
if user_id is not None:
library_id_val = core_config.config.get(
"BOOKLORE_LIBRARY_ID",
values.get("BOOKLORE_LIBRARY_ID"),
user_id=user_id,
)
path_id_val = core_config.config.get(
"BOOKLORE_PATH_ID",
values.get("BOOKLORE_PATH_ID"),
user_id=user_id,
)
else:
library_id_val = values.get("BOOKLORE_LIBRARY_ID")
path_id_val = values.get("BOOKLORE_PATH_ID")
destination = _parse_destination(
values.get("BOOKLORE_DESTINATION", BOOKLORE_DESTINATION_LIBRARY)
)
upload_to_bookdrop = destination == BOOKLORE_DESTINATION_BOOKDROP
library_id = _parse_int(library_id_val, "Booklore library ID")
path_id = _parse_int(path_id_val, "Booklore path ID")
# Resolve library/path through config so user override precedence is centralized.
library_id = 0
path_id = 0
if not upload_to_bookdrop:
if user_id is not None:
library_id_val = core_config.config.get(
"BOOKLORE_LIBRARY_ID",
values.get("BOOKLORE_LIBRARY_ID"),
user_id=user_id,
)
path_id_val = core_config.config.get(
"BOOKLORE_PATH_ID",
values.get("BOOKLORE_PATH_ID"),
user_id=user_id,
)
else:
library_id_val = values.get("BOOKLORE_LIBRARY_ID")
path_id_val = values.get("BOOKLORE_PATH_ID")
library_id = _parse_int(library_id_val, "Booklore library ID")
path_id = _parse_int(path_id_val, "Booklore path ID")
return BookloreConfig(
base_url=base_url.rstrip("/"),
@@ -89,7 +107,8 @@ def build_booklore_config(
library_id=library_id,
path_id=path_id,
verify_tls=True,
refresh_after_upload=True, # Always refresh library after upload
upload_to_bookdrop=upload_to_bookdrop,
refresh_after_upload=not upload_to_bookdrop,
)
@@ -143,9 +162,14 @@ def booklore_list_libraries(booklore_config: BookloreConfig, token: str) -> list
def booklore_upload_file(booklore_config: BookloreConfig, token: str, file_path: Path) -> None:
url = f"{booklore_config.base_url}/api/v1/files/upload"
if booklore_config.upload_to_bookdrop:
url = f"{booklore_config.base_url}/api/v1/files/upload/bookdrop"
params = None
else:
url = f"{booklore_config.base_url}/api/v1/files/upload"
params = {"libraryId": booklore_config.library_id, "pathId": booklore_config.path_id}
headers = {"Authorization": f"Bearer {token}"}
params = {"libraryId": booklore_config.library_id, "pathId": booklore_config.path_id}
response = None
@@ -194,6 +218,10 @@ def _get_booklore_settings() -> Dict[str, Any]:
"BOOKLORE_HOST": core_config.config.get("BOOKLORE_HOST", ""),
"BOOKLORE_USERNAME": core_config.config.get("BOOKLORE_USERNAME", ""),
"BOOKLORE_PASSWORD": core_config.config.get("BOOKLORE_PASSWORD", ""),
"BOOKLORE_DESTINATION": core_config.config.get(
"BOOKLORE_DESTINATION",
BOOKLORE_DESTINATION_LIBRARY,
),
"BOOKLORE_LIBRARY_ID": core_config.config.get("BOOKLORE_LIBRARY_ID"),
"BOOKLORE_PATH_ID": core_config.config.get("BOOKLORE_PATH_ID"),
}
@@ -309,8 +337,17 @@ def _post_process_booklore(
output_details={
"booklore": {
"base_url": booklore_config.base_url,
"library_id": booklore_config.library_id,
"path_id": booklore_config.path_id,
"destination": (
BOOKLORE_DESTINATION_BOOKDROP
if booklore_config.upload_to_bookdrop
else BOOKLORE_DESTINATION_LIBRARY
),
"library_id": (
None
if booklore_config.upload_to_bookdrop
else booklore_config.library_id
),
"path_id": None if booklore_config.upload_to_bookdrop else booklore_config.path_id,
"refresh_after_upload": bool(booklore_config.refresh_after_upload),
}
},
@@ -9,7 +9,12 @@ import {
import { SelectField } from './fields';
import { FieldWrapper } from './shared';
import { UserAccountCardContent, UserEditActions, UserIdentityHeader } from './users/UserCard';
import { UserOverridesSections } from './users/UserOverridesSections';
import {
DEFAULT_SELF_USER_OVERRIDE_SECTIONS,
normalizeUserOverrideSections,
UserOverridesSections,
type UserOverrideSectionId,
} from './users';
import { PerUserSettings } from './users/types';
import { useUserOverridesState } from './users/useUserOverridesState';
import { getStoredThemePreference, setThemePreference, THEME_FIELD } from '../../utils/themePreference';
@@ -52,6 +57,9 @@ export const SelfSettingsModal = ({ isOpen, onClose, onShowToast }: SelfSettings
const [originalUser, setOriginalUser] = useState<AdminUser | null>(null);
const [deliveryPreferences, setDeliveryPreferences] = useState<DeliveryPreferencesResponse | null>(null);
const [notificationPreferences, setNotificationPreferences] = useState<DeliveryPreferencesResponse | null>(null);
const [visibleSections, setVisibleSections] = useState<UserOverrideSectionId[]>(
DEFAULT_SELF_USER_OVERRIDE_SECTIONS
);
const [editPassword, setEditPassword] = useState('');
const [editPasswordConfirm, setEditPasswordConfirm] = useState('');
@@ -81,6 +89,9 @@ export const SelfSettingsModal = ({ isOpen, onClose, onShowToast }: SelfSettings
setOriginalUser(context.user);
setDeliveryPreferences(context.deliveryPreferences || null);
setNotificationPreferences(context.notificationPreferences || null);
setVisibleSections(
normalizeUserOverrideSections(context.visibleUserSettingsSections, 'self')
);
applyUserOverridesContext({
settings: (context.user.settings || {}) as PerUserSettings,
userOverridableKeys: context.userOverridableKeys || [],
@@ -309,6 +320,7 @@ export const SelfSettingsModal = ({ isOpen, onClose, onShowToast }: SelfSettings
children: (
<UserOverridesSections
scope="self"
sections={visibleSections}
deliveryPreferences={deliveryPreferences}
notificationPreferences={notificationPreferences}
isUserOverridable={isUserOverridable}
@@ -41,6 +41,7 @@ const USER_OVERRIDE_SECTION_DEFINITIONS: UserOverrideSectionDefinition[] = [
const USER_OVERRIDE_SECTION_ORDER: UserOverrideSectionId[] =
USER_OVERRIDE_SECTION_DEFINITIONS.map((section) => section.id);
const USER_OVERRIDE_SECTION_ID_SET = new Set<UserOverrideSectionId>(USER_OVERRIDE_SECTION_ORDER);
const USER_OVERRIDE_SECTION_META: Record<UserOverrideSectionId, UserOverrideSectionDefinition> = {
delivery: { id: 'delivery', adminOnly: false },
@@ -48,6 +49,53 @@ const USER_OVERRIDE_SECTION_META: Record<UserOverrideSectionId, UserOverrideSect
requestPolicy: { id: 'requestPolicy', adminOnly: true },
};
export const DEFAULT_SELF_USER_OVERRIDE_SECTIONS: UserOverrideSectionId[] =
USER_OVERRIDE_SECTION_ORDER.filter((sectionId) => !USER_OVERRIDE_SECTION_META[sectionId].adminOnly);
const isUserOverrideSectionId = (value: string): value is UserOverrideSectionId => (
USER_OVERRIDE_SECTION_ID_SET.has(value as UserOverrideSectionId)
);
export const normalizeUserOverrideSections = (
sections: Iterable<unknown> | null | undefined,
scope: UserOverrideScope,
): UserOverrideSectionId[] => {
const fallbackSections = scope === 'self'
? DEFAULT_SELF_USER_OVERRIDE_SECTIONS
: USER_OVERRIDE_SECTION_ORDER;
if (!sections) {
return fallbackSections;
}
const requestedValues = Array.from(sections);
if (requestedValues.length === 0) {
return [];
}
const requestedIds = new Set<UserOverrideSectionId>();
requestedValues.forEach((value) => {
const normalizedValue = String(value ?? '').trim();
if (isUserOverrideSectionId(normalizedValue)) {
requestedIds.add(normalizedValue);
}
});
if (requestedIds.size === 0) {
return fallbackSections;
}
return USER_OVERRIDE_SECTION_ORDER.filter((sectionId) => {
if (!requestedIds.has(sectionId)) {
return false;
}
if (scope === 'self' && USER_OVERRIDE_SECTION_META[sectionId].adminOnly) {
return false;
}
return true;
});
};
export const UserOverridesSections = ({
scope,
sections,
@@ -60,13 +108,7 @@ export const UserOverridesSections = ({
globalUsersSettingsValues,
onTestNotificationRoutes,
}: UserOverridesSectionsProps) => {
const requestedSections = sections ?? USER_OVERRIDE_SECTION_ORDER;
const activeSections = requestedSections.filter((sectionId) => {
if (scope === 'self' && USER_OVERRIDE_SECTION_META[sectionId].adminOnly) {
return false;
}
return true;
});
const activeSections = normalizeUserOverrideSections(sections, scope);
const sectionNodes: UserOverrideSectionNode[] = [];
@@ -11,7 +11,11 @@ export { UserListView } from './UserListView';
export { RequestPolicyGrid } from './RequestPolicyGrid';
export { UserNotificationOverridesSection } from './UserNotificationOverridesSection';
export { UserOverridesSection } from './UserOverridesSection';
export { UserOverridesSections } from './UserOverridesSections';
export {
UserOverridesSections,
DEFAULT_SELF_USER_OVERRIDE_SECTIONS,
normalizeUserOverrideSections,
} from './UserOverridesSections';
export { UserOverridesView } from './UserOverridesView';
export { useUserForm } from './useUserForm';
export { useUserMutations } from './useUserMutations';
@@ -27,4 +31,5 @@ export {
export type {
RequestPolicyContentType,
} from './requestPolicyGridUtils';
export type { UserOverrideSectionId } from './UserOverridesSections';
export type { RequestPolicyMode } from '../../../types';
+1
View File
@@ -600,6 +600,7 @@ export interface SelfUserEditContext {
deliveryPreferences: DeliveryPreferencesResponse | null;
notificationPreferences: DeliveryPreferencesResponse | null;
userOverridableKeys: string[];
visibleUserSettingsSections?: string[];
}
export const getAdminUsers = async (): Promise<AdminUser[]> => {
+28
View File
@@ -46,3 +46,31 @@ def test_download_settings_email_recipient_field_uses_default_label():
assert email_field.label == "Default Email Recipient"
assert "Optional fallback" in email_field.description
def test_download_settings_booklore_destination_field_defaults_to_library():
from shelfmark.config.settings import download_settings
fields = download_settings()
destination_field = next(field for field in fields if getattr(field, "key", None) == "BOOKLORE_DESTINATION")
assert destination_field.default == "library"
option_values = {option["value"] for option in destination_field.options}
assert option_values == {"library", "bookdrop"}
def test_download_settings_booklore_library_and_path_depend_on_library_destination():
from shelfmark.config.settings import download_settings
fields = download_settings()
library_field = next(field for field in fields if getattr(field, "key", None) == "BOOKLORE_LIBRARY_ID")
path_field = next(field for field in fields if getattr(field, "key", None) == "BOOKLORE_PATH_ID")
assert library_field.show_when == [
{"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
{"field": "BOOKLORE_DESTINATION", "value": "library"},
]
assert path_field.show_when == [
{"field": "BOOKS_OUTPUT_MODE", "value": "booklore"},
{"field": "BOOKLORE_DESTINATION", "value": "library"},
]
+23
View File
@@ -21,6 +21,7 @@ def test_users_tab_registers_request_policy_fields():
fields = _field_map("users")
expected_keys = {
"users_management",
"VISIBLE_SELF_SETTINGS_SECTIONS",
"REQUESTS_ENABLED",
"request_policy_editor",
"MAX_PENDING_REQUESTS_PER_USER",
@@ -70,6 +71,28 @@ def test_request_policy_fields_are_user_overridable():
}
assert expected_keys.issubset(set(overridable_map))
assert "RESTRICT_SETTINGS_TO_ADMIN" not in overridable_map
assert "VISIBLE_SELF_SETTINGS_SECTIONS" not in overridable_map
def test_visible_self_settings_sections_field_defaults_and_options():
fields = _field_map("users")
field = fields["VISIBLE_SELF_SETTINGS_SECTIONS"]
assert field.default == ["delivery", "notifications"]
assert field.variant == "dropdown"
assert field.env_supported is False
assert field.options == [
{
"value": "delivery",
"label": "Delivery Preferences",
"description": "Show personal delivery output and destination settings.",
},
{
"value": "notifications",
"label": "Notifications",
"description": "Show personal notification route settings.",
},
]
def test_users_tab_registers_custom_components():
+17
View File
@@ -10,6 +10,7 @@ class TestBuildBookloreConfigWithOverrides:
"BOOKLORE_HOST": "http://booklore:6060",
"BOOKLORE_USERNAME": "admin",
"BOOKLORE_PASSWORD": "secret",
"BOOKLORE_DESTINATION": "library",
"BOOKLORE_LIBRARY_ID": 1,
"BOOKLORE_PATH_ID": 10,
}
@@ -58,6 +59,7 @@ class TestBuildBookloreConfigWithOverrides:
config = build_booklore_config(self.BASE_SETTINGS, user_id=None)
assert config.library_id == 1
assert config.path_id == 10
assert config.upload_to_bookdrop is False
def test_auth_fields_remain_global(self, monkeypatch):
"""Only Booklore library/path should be resolved with user context."""
@@ -73,3 +75,18 @@ class TestBuildBookloreConfigWithOverrides:
assert config.base_url == "http://booklore:6060"
assert config.username == "admin"
assert config.library_id == 5
def test_bookdrop_destination_ignores_library_and_path_values(self):
settings = {
"BOOKLORE_HOST": "http://booklore:6060",
"BOOKLORE_USERNAME": "admin",
"BOOKLORE_PASSWORD": "secret",
"BOOKLORE_DESTINATION": "bookdrop",
}
config = build_booklore_config(settings)
assert config.upload_to_bookdrop is True
assert config.library_id == 0
assert config.path_id == 0
assert config.refresh_after_upload is False
+53
View File
@@ -0,0 +1,53 @@
from unittest.mock import MagicMock, patch
from shelfmark.download.outputs.booklore import BookloreConfig, booklore_upload_file
def _booklore_config(upload_to_bookdrop: bool) -> BookloreConfig:
return BookloreConfig(
base_url="http://booklore:6060",
username="admin",
password="secret",
library_id=7,
path_id=21,
upload_to_bookdrop=upload_to_bookdrop,
refresh_after_upload=not upload_to_bookdrop,
)
def test_booklore_upload_file_uses_library_endpoint_with_query_params(tmp_path):
file_path = tmp_path / "book.epub"
file_path.write_bytes(b"content")
response = MagicMock()
response.raise_for_status.return_value = None
with patch(
"shelfmark.download.outputs.booklore.requests.post",
return_value=response,
) as mock_post:
booklore_upload_file(_booklore_config(upload_to_bookdrop=False), "token", file_path)
assert mock_post.call_count == 1
args, kwargs = mock_post.call_args
assert args[0] == "http://booklore:6060/api/v1/files/upload"
assert kwargs["params"] == {"libraryId": 7, "pathId": 21}
assert kwargs["headers"] == {"Authorization": "Bearer token"}
def test_booklore_upload_file_uses_bookdrop_endpoint_without_query_params(tmp_path):
file_path = tmp_path / "book.epub"
file_path.write_bytes(b"content")
response = MagicMock()
response.raise_for_status.return_value = None
with patch(
"shelfmark.download.outputs.booklore.requests.post",
return_value=response,
) as mock_post:
booklore_upload_file(_booklore_config(upload_to_bookdrop=True), "token", file_path)
assert mock_post.call_count == 1
args, kwargs = mock_post.call_args
assert args[0] == "http://booklore:6060/api/v1/files/upload/bookdrop"
assert kwargs["params"] is None
assert kwargs["headers"] == {"Authorization": "Bearer token"}
+141
View File
@@ -0,0 +1,141 @@
"""Tests for self-service account edit context and update endpoints."""
import os
import tempfile
from typing import Any
from unittest.mock import patch
import pytest
from flask import Flask
from shelfmark.core.self_user_routes import register_self_user_routes
from shelfmark.core.user_db import UserDB
@pytest.fixture
def db_path():
with tempfile.TemporaryDirectory() as tmpdir:
yield os.path.join(tmpdir, "shelfmark.db")
@pytest.fixture
def user_db(db_path):
db = UserDB(db_path)
db.initialize()
return db
@pytest.fixture
def app(user_db):
test_app = Flask(__name__)
test_app.config["SECRET_KEY"] = "test-secret"
test_app.config["TESTING"] = True
register_self_user_routes(test_app, user_db)
return test_app
def _authed_client_for_user(app: Flask, user: dict) -> Any:
client = app.test_client()
with client.session_transaction() as sess:
sess["user_id"] = user["username"]
sess["db_user_id"] = user["id"]
sess["is_admin"] = False
return client
def test_users_me_edit_context_respects_visible_sections(app, user_db):
user = user_db.create_user(username="alice")
client = _authed_client_for_user(app, user)
def build_preferences(_user_db, _user_id, tab_name):
if tab_name == "downloads":
return {
"tab": "downloads",
"keys": ["DESTINATION"],
"fields": [],
"globalValues": {},
"userOverrides": {},
"effective": {},
}
raise AssertionError(f"Unexpected tab requested: {tab_name}")
with patch("shelfmark.core.self_user_routes._get_auth_mode", return_value="builtin"):
with patch(
"shelfmark.core.self_user_routes.load_config_file",
side_effect=lambda tab_name: {"VISIBLE_SELF_SETTINGS_SECTIONS": ["delivery"]} if tab_name == "users" else {},
):
with patch(
"shelfmark.core.self_user_routes._build_user_preferences_payload",
side_effect=build_preferences,
):
resp = client.get("/api/users/me/edit-context")
assert resp.status_code == 200
assert resp.json["visibleUserSettingsSections"] == ["delivery"]
assert resp.json["deliveryPreferences"]["tab"] == "downloads"
assert resp.json["notificationPreferences"] is None
assert resp.json["userOverridableKeys"] == ["DESTINATION"]
def test_users_me_update_rejects_hidden_section_settings(app, user_db):
user = user_db.create_user(username="alice")
client = _authed_client_for_user(app, user)
def ordered_overrides(tab_name: str):
if tab_name == "downloads":
return [("DESTINATION", object())]
raise AssertionError(f"Unexpected tab requested: {tab_name}")
with patch("shelfmark.core.self_user_routes._get_auth_mode", return_value="builtin"):
with patch(
"shelfmark.core.self_user_routes.load_config_file",
side_effect=lambda tab_name: {"VISIBLE_SELF_SETTINGS_SECTIONS": ["delivery"]} if tab_name == "users" else {},
):
with patch(
"shelfmark.core.self_user_routes._get_ordered_user_overridable_fields",
side_effect=ordered_overrides,
):
resp = client.put(
"/api/users/me",
json={
"settings": {
"USER_NOTIFICATION_ROUTES": [{"event": "all", "url": "ntfys://ntfy.sh/alice"}],
}
},
)
assert resp.status_code == 400
assert resp.json["error"] == "Some settings are admin-only"
assert "Setting not user-overridable: USER_NOTIFICATION_ROUTES" in resp.json["details"]
def test_users_me_update_accepts_visible_section_settings(app, user_db):
user = user_db.create_user(username="alice")
client = _authed_client_for_user(app, user)
def ordered_overrides(tab_name: str):
if tab_name == "downloads":
return [("DESTINATION", object())]
raise AssertionError(f"Unexpected tab requested: {tab_name}")
with patch("shelfmark.core.self_user_routes._get_auth_mode", return_value="builtin"):
with patch(
"shelfmark.core.self_user_routes.load_config_file",
side_effect=lambda tab_name: {"VISIBLE_SELF_SETTINGS_SECTIONS": ["delivery"]} if tab_name == "users" else {},
):
with patch(
"shelfmark.core.self_user_routes._get_ordered_user_overridable_fields",
side_effect=ordered_overrides,
):
with patch(
"shelfmark.core.self_user_routes.validate_user_settings",
side_effect=lambda payload: (payload, []),
):
resp = client.put(
"/api/users/me",
json={"settings": {"DESTINATION": "/books/alice"}},
)
assert resp.status_code == 200
assert user_db.get_user_settings(user["id"]).get("DESTINATION") == "/books/alice"
+99
View File
@@ -0,0 +1,99 @@
"""Unit tests for the Deluge client."""
from unittest.mock import MagicMock, patch
from shelfmark.download.clients.torrent_utils import TorrentInfo
def make_config_getter(values):
"""Create a config.get function that returns values from a dict."""
def getter(key, default=""):
return values.get(key, default)
return getter
class TestDelugeClientAddDownload:
"""Tests for DelugeClient.add_download()."""
def test_add_download_uses_configured_download_dir(self, monkeypatch):
"""Add torrent should pass configured download location option."""
config_values = {
"DELUGE_HOST": "http://localhost",
"DELUGE_PORT": "8112",
"DELUGE_PASSWORD": "password",
"DELUGE_CATEGORY": "books",
"DELUGE_DOWNLOAD_DIR": "/downloads/books",
}
monkeypatch.setattr(
"shelfmark.download.clients.deluge.config.get",
make_config_getter(config_values),
)
from shelfmark.download.clients.deluge import DelugeClient
client = DelugeClient()
monkeypatch.setattr(client, "_ensure_connected", lambda: None)
mock_rpc_call = MagicMock(return_value="abcdef1234567890abcdef1234567890abcdef12")
monkeypatch.setattr(client, "_rpc_call", mock_rpc_call)
mock_try_set_label = MagicMock()
monkeypatch.setattr(client, "_try_set_label", mock_try_set_label)
magnet = "magnet:?xt=urn:btih:ABCDEF1234567890ABCDEF1234567890ABCDEF12&dn=test"
with patch("shelfmark.download.clients.deluge.extract_torrent_info", autospec=True) as mock_extract:
mock_extract.return_value = TorrentInfo(
info_hash="abcdef1234567890abcdef1234567890abcdef12",
torrent_data=None,
is_magnet=True,
magnet_url=magnet,
)
result = client.add_download(magnet, "Test")
assert result == "abcdef1234567890abcdef1234567890abcdef12"
mock_rpc_call.assert_called_once_with(
"core.add_torrent_magnet",
magnet,
{"download_location": "/downloads/books"},
)
mock_try_set_label.assert_called_once_with(
"abcdef1234567890abcdef1234567890abcdef12",
"books",
)
def test_add_download_uses_empty_options_without_download_dir(self, monkeypatch):
"""Add torrent should keep options empty when no directory is configured."""
config_values = {
"DELUGE_HOST": "http://localhost",
"DELUGE_PORT": "8112",
"DELUGE_PASSWORD": "password",
"DELUGE_CATEGORY": "books",
}
monkeypatch.setattr(
"shelfmark.download.clients.deluge.config.get",
make_config_getter(config_values),
)
from shelfmark.download.clients.deluge import DelugeClient
client = DelugeClient()
monkeypatch.setattr(client, "_ensure_connected", lambda: None)
mock_rpc_call = MagicMock(return_value="abcdef1234567890abcdef1234567890abcdef12")
monkeypatch.setattr(client, "_rpc_call", mock_rpc_call)
monkeypatch.setattr(client, "_try_set_label", MagicMock())
magnet = "magnet:?xt=urn:btih:ABCDEF1234567890ABCDEF1234567890ABCDEF12&dn=test"
with patch("shelfmark.download.clients.deluge.extract_torrent_info", autospec=True) as mock_extract:
mock_extract.return_value = TorrentInfo(
info_hash="abcdef1234567890abcdef1234567890abcdef12",
torrent_data=None,
is_magnet=True,
magnet_url=magnet,
)
client.add_download(magnet, "Test")
mock_rpc_call.assert_called_once_with(
"core.add_torrent_magnet",
magnet,
{},
)
+42
View File
@@ -587,6 +587,48 @@ class TestQBittorrentClientAddDownload:
mock_client_instance.torrents_create_category.assert_called_once_with(name="books")
def test_add_download_uses_configured_download_dir(self, monkeypatch):
"""Test that add_download passes configured download directory."""
config_values = {
"QBITTORRENT_URL": "http://localhost:8080",
"QBITTORRENT_USERNAME": "admin",
"QBITTORRENT_PASSWORD": "password",
"QBITTORRENT_CATEGORY": "books",
"QBITTORRENT_DOWNLOAD_DIR": "/downloads/books",
}
monkeypatch.setattr(
"shelfmark.download.clients.qbittorrent.config.get",
lambda key, default="": config_values.get(key, default),
)
valid_hash = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
mock_client_instance = MagicMock()
mock_client_instance.torrents_add.return_value = "Ok."
mock_client_instance._session.get.return_value = create_mock_session_response({}, status_code=200)
mock_client_class = MagicMock(return_value=mock_client_instance)
with patch.dict('sys.modules', {'qbittorrentapi': MagicMock(Client=mock_client_class)}):
import importlib
import shelfmark.download.clients.qbittorrent as qb_module
importlib.reload(qb_module)
with patch(
"shelfmark.download.clients.qbittorrent.extract_torrent_info",
autospec=True,
) as mock_extract:
mock_extract.return_value = TorrentInfo(
info_hash=valid_hash,
torrent_data=None,
is_magnet=True,
magnet_url=f"magnet:?xt=urn:btih:{valid_hash}&dn=test",
)
client = qb_module.QBittorrentClient()
client.add_download("magnet:?xt=urn:btih:test&dn=test", "Test")
call_kwargs = mock_client_instance.torrents_add.call_args.kwargs
assert call_kwargs.get("save_path") == "/downloads/books"
class TestQBittorrentClientRemove:
"""Tests for QBittorrentClient.remove()."""
@@ -474,6 +474,43 @@ class TestTransmissionClientAddDownload:
call_kwargs = mock_client_instance.add_torrent.call_args
assert call_kwargs.kwargs.get("labels") == ["mybooks"]
def test_add_download_uses_configured_download_dir(self, monkeypatch):
"""Test that add_download passes configured download directory."""
config_values = {
"TRANSMISSION_URL": "http://localhost:9091",
"TRANSMISSION_USERNAME": "admin",
"TRANSMISSION_PASSWORD": "password",
"TRANSMISSION_CATEGORY": "mybooks",
"TRANSMISSION_DOWNLOAD_DIR": "/downloads/books",
}
monkeypatch.setattr(
"shelfmark.download.clients.transmission.config.get",
make_config_getter(config_values),
)
mock_torrent = MockTorrent(hash_string="abc123")
mock_client_instance = MagicMock()
mock_client_instance.add_torrent.return_value = mock_torrent
mock_transmission_rpc = create_mock_transmission_rpc_module()
mock_transmission_rpc.Client.return_value = mock_client_instance
with patch.dict("sys.modules", {"transmission_rpc": mock_transmission_rpc}):
if "shelfmark.download.clients.transmission" in sys.modules:
del sys.modules["shelfmark.download.clients.transmission"]
from shelfmark.download.clients.transmission import (
TransmissionClient,
)
client = TransmissionClient()
magnet = "magnet:?xt=urn:btih:abc123&dn=test"
client.add_download(magnet, "Test")
call_kwargs = mock_client_instance.add_torrent.call_args
assert call_kwargs.kwargs.get("labels") == ["mybooks"]
assert call_kwargs.kwargs.get("download_dir") == "/downloads/books"
class TestTransmissionClientRemove:
"""Tests for TransmissionClient.remove()."""