⭐️ feat: restrict who can see downloads and hide upcoming releases from libraries a profile cannot open

This commit is contained in:
WonderAliceUwU committed 2026-11-17 15:09:48 +01:00
1 parent 8fc9833679
commit 2b4119a906
4 files changed
+151 -11

No files matched your search

+14
View File
@@ -394,6 +394,14 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse):
return;
}
if (url.pathname.startsWith('/api/downloads')) {
const config = await readConfig(session!.encryptionKey);
if (!canViewDownloads(session!, config)) {
sendJson(response, 403, { error: 'You do not have access to downloads.' });
return;
}
}
if (url.pathname === '/api/downloads' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, await getDownloadsResponse(config));
@@ -711,6 +719,12 @@ function mergeStoredConfig(stored: Partial<AppConfig>): AppConfig {
// Profiles keep their own wishlist; the administrator has no Jellyfin profile
// and shares a single one.
// Profiles the administrator listed cannot open the Downloads page; the admin
// session always can.
function canViewDownloads(session: SessionRecord, config: AppConfig): boolean {
return session.role === 'admin' || !session.userId || !config.preferences.downloadsRestrictedUserIds.includes(session.userId);
}
function getWishlistOwner(session: SessionRecord): string {
return session.role === 'user' && session.userId ? session.userId : 'admin';
}
+85 -7
View File
@@ -190,6 +190,7 @@ interface SonarrCalendarRecord {
series?: {
title?: string;
tmdbId?: number;
path?: string;
images?: Array<{ coverType?: string; remoteUrl?: string; url?: string }>;
year?: number;
status?: string;
@@ -240,6 +241,7 @@ interface RadarrCalendarRecord {
digitalRelease?: string;
monitored?: boolean;
hasFile?: boolean;
path?: string;
images?: Array<{ coverType?: string; remoteUrl?: string; url?: string }>;
}
@@ -383,6 +385,9 @@ export function sanitizeConfig(input: AppConfig): AppConfig {
: [],
radarrDownloadQualityProfileIds: Array.isArray(input.preferences.radarrDownloadQualityProfileIds)
? input.preferences.radarrDownloadQualityProfileIds.map(String)
: [],
downloadsRestrictedUserIds: Array.isArray(input.preferences.downloadsRestrictedUserIds)
? input.preferences.downloadsRestrictedUserIds.map(String)
: []
},
jellyfin: {
@@ -745,16 +750,22 @@ export async function getCalendar(config: AppConfig, start: Date, end: Date): Pr
getRadarrCalendar(config, start, end)
])
const sonarrItems = sonarrResult.status === 'fulfilled'
? sonarrResult.value.map((item) => mapSonarrCalendarEntry(item))
: []
const radarrItems = radarrResult.status === 'fulfilled'
? radarrResult.value.map((item) => mapRadarrCalendarEntry(item))
: []
// Link each entry to its Jellyfin item, as search does, so the details can
// tell which episodes are already in the library.
const library = await getLibrarySnapshot(config).catch(() => null);
// A profile only sees upcoming releases that belong to the libraries it can open.
const hidden = await getHiddenLibraryScope(config, library?.allItems ?? []);
const sonarrItems = sonarrResult.status === 'fulfilled'
? sonarrResult.value
.filter((item) => !hidden?.hides('series', Number(item.series?.tmdbId) || undefined, item.series?.path))
.map((item) => mapSonarrCalendarEntry(item))
: []
const radarrItems = radarrResult.status === 'fulfilled'
? radarrResult.value
.filter((item) => !hidden?.hides('movie', Number(item.tmdbId) || undefined, item.path))
.map((item) => mapRadarrCalendarEntry(item))
: []
const libraryProviderIds = new Map<string, string>();
for (const libraryItem of library?.allItems ?? []) {
const libraryCard = jellyfinToCard(libraryItem, libraryItem.Name || 'Library');
@@ -791,6 +802,73 @@ export async function getCalendar(config: AppConfig, start: Date, end: Date): Pr
}
}
interface HiddenLibraryScope {
hides(kind: 'movie' | 'series', tmdbId: number | undefined, path: string | undefined): boolean;
}
function normalizeLibraryId(id: string | undefined): string {
return String(id || '').replace(/-/g, '').toLowerCase();
}
function normalizeLibraryPath(path: string): string {
return path.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
}
// What the signed-in Jellyfin profile cannot open: the libraries missing from
// its views, the titles inside them and where they live on disk. Sonarr and
// Radarr know nothing about those permissions, so releases are matched to a
// hidden library by TMDb id (for titles already in Jellyfin) or by folder.
// Admin sessions have no profile and see everything.
async function getHiddenLibraryScope(config: AppConfig, visibleItems: JellyfinItem[]): Promise<HiddenLibraryScope | null> {
if (!config.jellyfin.userId || !config.jellyfin.baseUrl || !config.jellyfin.apiKey) {
return null;
}
try {
const [folders, views] = await Promise.all([
jellyfinFetch<Array<{ ItemId?: string; Locations?: string[] }>>(config, '/Library/VirtualFolders'),
jellyfinFetch<JellyfinItem[]>(config, `/UserViews?userId=${encodeURIComponent(config.jellyfin.userId)}`)
]);
const visibleLibraryIds = new Set(views.map((view) => normalizeLibraryId(view.Id)));
const hiddenFolders = folders.filter((folder) => folder.ItemId && !visibleLibraryIds.has(normalizeLibraryId(folder.ItemId)));
if (!hiddenFolders.length) {
return null;
}
const toKey = (item: JellyfinItem) => {
const tmdbId = Number(item.ProviderIds?.Tmdb);
return tmdbId ? `${item.Type === 'Movie' ? 'movie' : 'series'}:${tmdbId}` : '';
};
const hiddenItems = await Promise.all(hiddenFolders.map((folder) =>
jellyfinFetch<JellyfinItem[]>(
config,
`/Items?parentId=${encodeURIComponent(String(folder.ItemId))}&recursive=true&includeItemTypes=Movie,Series&fields=ProviderIds`
).catch(() => [] as JellyfinItem[])
));
// A title that also sits in a library the profile can open stays visible.
const visibleKeys = new Set(visibleItems.map(toKey).filter(Boolean));
const hiddenKeys = new Set(hiddenItems.flat().map(toKey).filter((key) => key && !visibleKeys.has(key)));
const hiddenLocations = hiddenFolders.flatMap((folder) => folder.Locations ?? []).map(normalizeLibraryPath).filter(Boolean);
return {
hides(kind, tmdbId, path) {
if (tmdbId && visibleKeys.has(`${kind}:${tmdbId}`)) {
return false;
}
if (tmdbId && hiddenKeys.has(`${kind}:${tmdbId}`)) {
return true;
}
const normalized = path ? normalizeLibraryPath(path) : '';
return Boolean(normalized) && hiddenLocations.some((location) => normalized === location || normalized.startsWith(`${location}/`));
}
};
} catch (error) {
// Better to show the calendar than to break it when Jellyfin cannot be asked.
console.warn('Could not read the profile libraries; the calendar is not filtered.', error);
return null;
}
}
export async function searchTitles(
config: AppConfig,
rawQuery: string
+4 -1
View File
@@ -56,6 +56,8 @@ export interface AppPreferences {
animationLevel: 'smooth' | 'reduced';
sonarrDownloadQualityProfileIds: string[];
radarrDownloadQualityProfileIds: string[];
/** Jellyfin profiles that cannot open the Downloads page; empty lets everyone in. */
downloadsRestrictedUserIds: string[];
}
export interface AppConfig {
@@ -391,7 +393,8 @@ export const defaultConfig: AppConfig = {
excludeLibraryItems: true,
animationLevel: 'smooth',
sonarrDownloadQualityProfileIds: [],
radarrDownloadQualityProfileIds: []
radarrDownloadQualityProfileIds: [],
downloadsRestrictedUserIds: []
},
jellyfin: {
baseUrl: '',
+48 -3
View File
@@ -125,6 +125,8 @@ function App() {
const [downloadDeleteId, setDownloadDeleteId] = useState('')
const [wishlist, setWishlist] = useState<WishlistEntry[]>([])
const [entryTransitionState, setEntryTransitionState] = useState<EntryTransitionState>('idle')
// The administrator can keep some profiles away from Downloads.
const canViewDownloads = sessionRole !== 'user' || !config.preferences.downloadsRestrictedUserIds.includes(config.jellyfin.userId)
async function transitionEntryStage(nextStage: EntryStage) {
if (nextStage === entryStage) {
@@ -242,6 +244,10 @@ function App() {
}
if (route === 'downloads') {
if (!canViewDownloads) {
setRoute('home')
return
}
void refreshDownloads()
const interval = window.setInterval(() => {
void refreshDownloads()
@@ -270,7 +276,7 @@ function App() {
return () => {
cancelled = true
}
}, [authState, entryStage, route])
}, [authState, canViewDownloads, entryStage, route])
@@ -670,6 +676,7 @@ function App() {
<div className={`omniarr-app ${getEntryTransitionClassName(entryTransitionState)}`}>
<Sidebar
busy={busy}
canViewDownloads={canViewDownloads}
connections={connections}
currentUser={currentJellyfinUser}
diskSpace={diskSpace}
@@ -694,7 +701,7 @@ function App() {
/>
) : null}
{route === 'calendar' && isRouteAvailable(route, connections) ? <CalendarPage onOpenCard={(card, originRect) => setSelectedCard({ card, originRect: originRect ?? null })} /> : null}
{route === 'downloads' && isRouteAvailable(route, connections) ? <DownloadsPage busyId={downloadDeleteId} completedDownloads={completedDownloads} downloads={downloads} onDelete={handleDeleteDownload} onDismissAllCompleted={handleDismissAllCompleted} onDismissCompleted={handleDismissCompleted} onOpenCard={(card, originRect) => setSelectedCard({ card, originRect: originRect ?? null })} processingItems={processingItems} /> : null}
{route === 'downloads' && canViewDownloads && isRouteAvailable(route, connections) ? <DownloadsPage busyId={downloadDeleteId} completedDownloads={completedDownloads} downloads={downloads} onDelete={handleDeleteDownload} onDismissAllCompleted={handleDismissAllCompleted} onDismissCompleted={handleDismissCompleted} onOpenCard={(card, originRect) => setSelectedCard({ card, originRect: originRect ?? null })} processingItems={processingItems} /> : null}
{route === 'search' ? (
<SearchPage
loading={searchLoading}
@@ -775,6 +782,7 @@ function Sidebar(props: {
connections: ConnectionStatus[]
busy: boolean
canManage: boolean
canViewDownloads: boolean
onExitProfile: () => void
}) {
const [menuOpen, setMenuOpen] = useState(false)
@@ -835,7 +843,7 @@ function Sidebar(props: {
</button>
<div className="sidebar-links">
{topSidebarItems.filter((item) => isRouteAvailable(item.route, props.connections)).map((item) => (
{topSidebarItems.filter((item) => isRouteAvailable(item.route, props.connections) && (item.route !== 'downloads' || props.canViewDownloads)).map((item) => (
<button
className={item.route === props.route ? 'sidebar-link active' : 'sidebar-link'}
key={item.route}
@@ -4252,6 +4260,11 @@ function SettingsView(props: {
Region
<input className="input" maxLength={2} onChange={(event) => props.updateConfig('preferences', { ...props.config.preferences, region: event.target.value })} value={props.config.preferences.region} />
</label>
<DownloadsAccess
onChange={(downloadsRestrictedUserIds) => props.updateConfig('preferences', { ...props.config.preferences, downloadsRestrictedUserIds })}
restrictedUserIds={props.config.preferences.downloadsRestrictedUserIds}
users={props.options.jellyfinUsers}
/>
</SettingsCard>
<SettingsCard status={getServiceStatus(props.connections, 'jellyfin') ?? notCheckedYet('jellyfin')} title="Jellyfin" {...check}>
@@ -4432,6 +4445,38 @@ function QualityProfileVisibility(props: {
)
}
function DownloadsAccess(props: {
users: SelectOption[]
restrictedUserIds: string[]
onChange: (userIds: string[]) => void
}) {
return (
<fieldset className="quality-profile-visibility">
<legend>Who can see Downloads</legend>
<p>Untick the profiles that should not open the Downloads page. The administrator always can.</p>
{props.users.length ? (
<div className="quality-profile-visibility-list">
{props.users.map((user) => {
const restricted = props.restrictedUserIds.includes(user.id)
return (
<label key={user.id}>
<input
checked={!restricted}
onChange={() => props.onChange(restricted
? props.restrictedUserIds.filter((id) => id !== user.id)
: [...props.restrictedUserIds, user.id])}
type="checkbox"
/>
<span>{user.label}</span>
</label>
)
})}
</div>
) : <p>Connect Jellyfin first to load its profiles.</p>}
</fieldset>
)
}
function EmptyState({ title, copy, className }: { title: string; copy: string; className?: string }) {
return (
<div className={className ? `empty-state ${className}` : 'empty-state'}>