feat(requests): Request Overrides & Request Editing (#653)

pull/661/head
sct 4 years ago committed by GitHub
parent d9919abb89
commit bdb33722e6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -2507,6 +2507,26 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MediaRequest'
put:
summary: Update a specific MediaRequest
description: Updats a specific media request and returns the request in JSON format. Requires the `MANAGE_REQUESTS` permission.
tags:
- request
parameters:
- in: path
name: requestId
description: Request ID
required: true
example: 1
schema:
type: string
responses:
'200':
description: Succesfully updated request
content:
application/json:
schema:
$ref: '#/components/schemas/MediaRequest'
delete:
summary: Delete a request
description: Removes a request. If the user has the `MANAGE_REQUESTS` permission, then any request can be removed. Otherwise, only pending requests can be removed.
@ -3066,6 +3086,86 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Collection'
/service/radarr:
get:
summary: Returns non-sensitive radarr server list
description: Returns a list of radarr servers, both ID and name in JSON format
tags:
- service
responses:
'200':
description: Request successful
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/RadarrSettings'
/service/radarr/{radarrId}:
get:
summary: Returns radarr server quality profiles and root folders
description: Returns a radarr server quality profile and root folder details in JSON format
tags:
- service
parameters:
- in: path
name: radarrId
required: true
schema:
type: number
example: 0
responses:
'200':
description: Request successful
content:
application/json:
schema:
type: object
properties:
server:
$ref: '#/components/schemas/RadarrSettings'
profiles:
$ref: '#/components/schemas/ServiceProfile'
/service/sonarr:
get:
summary: Returns non-sensitive sonarr server list
description: Returns a list of sonarr servers, both ID and name in JSON format
tags:
- service
responses:
'200':
description: Request successful
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/SonarrSettings'
/service/sonarr/{sonarrId}:
get:
summary: Returns sonarr server quality profiles and root folders
description: Returns a sonarr server quality profile and root folder details in JSON format
tags:
- service
parameters:
- in: path
name: sonarrId
required: true
schema:
type: number
example: 0
responses:
'200':
description: Request successful
content:
application/json:
schema:
type: object
properties:
server:
$ref: '#/components/schemas/SonarrSettings'
profiles:
$ref: '#/components/schemas/ServiceProfile'
security:
- cookieAuth: []

@ -29,7 +29,7 @@ interface RadarrMovie {
hasFile: boolean;
}
interface RadarrRootFolder {
export interface RadarrRootFolder {
id: number;
path: string;
freeSpace: number;
@ -40,7 +40,7 @@ interface RadarrRootFolder {
}[];
}
interface RadarrProfile {
export interface RadarrProfile {
id: number;
name: string;
}

@ -202,7 +202,7 @@ export class MediaRequest {
}
if (
this.media.mediaType === MediaType.MOVIE &&
media.mediaType === MediaType.MOVIE &&
this.status === MediaRequestStatus.DECLINED
) {
if (this.is4k) {
@ -284,10 +284,24 @@ export class MediaRequest {
return;
}
const radarrSettings = settings.radarr.find(
let radarrSettings = settings.radarr.find(
(radarr) => radarr.isDefault && radarr.is4k === this.is4k
);
if (
this.serverId !== null &&
this.serverId >= 0 &&
radarrSettings?.id !== this.serverId
) {
radarrSettings = settings.radarr.find(
(radarr) => radarr.id === this.serverId
);
logger.info(
`Request has an override server: ${radarrSettings?.name}`,
{ label: 'Media Request' }
);
}
if (!radarrSettings) {
logger.info(
`There is no default ${
@ -298,6 +312,30 @@ export class MediaRequest {
return;
}
let rootFolder = radarrSettings.activeDirectory;
let qualityProfile = radarrSettings.activeProfileId;
if (
this.rootFolder &&
this.rootFolder !== '' &&
this.rootFolder !== radarrSettings.activeDirectory
) {
rootFolder = this.rootFolder;
logger.info(`Request has an override root folder: ${rootFolder}`, {
label: 'Media Request',
});
}
if (
this.profileId &&
this.profileId !== radarrSettings.activeProfileId
) {
qualityProfile = this.profileId;
logger.info(`Request has an override profile id: ${qualityProfile}`, {
label: 'Media Request',
});
}
const tmdb = new TheMovieDb();
const radarr = new RadarrAPI({
apiKey: radarrSettings.apiKey,
@ -310,9 +348,9 @@ export class MediaRequest {
// Run this asynchronously so we don't wait for it on the UI side
radarr
.addMovie({
profileId: radarrSettings.activeProfileId,
qualityProfileId: radarrSettings.activeProfileId,
rootFolderPath: radarrSettings.activeDirectory,
profileId: qualityProfile,
qualityProfileId: qualityProfile,
rootFolderPath: rootFolder,
minimumAvailability: radarrSettings.minimumAvailability,
title: movie.title,
tmdbId: movie.id,
@ -376,10 +414,24 @@ export class MediaRequest {
return;
}
const sonarrSettings = settings.sonarr.find(
let sonarrSettings = settings.sonarr.find(
(sonarr) => sonarr.isDefault && sonarr.is4k === this.is4k
);
if (
this.serverId !== null &&
this.serverId >= 0 &&
sonarrSettings?.id !== this.serverId
) {
sonarrSettings = settings.sonarr.find(
(sonarr) => sonarr.id === this.serverId
);
logger.info(
`Request has an override server: ${sonarrSettings?.name}`,
{ label: 'Media Request' }
);
}
if (!sonarrSettings) {
logger.info(
`There is no default ${
@ -423,17 +475,38 @@ export class MediaRequest {
seriesType = 'anime';
}
let rootFolder =
seriesType === 'anime' && sonarrSettings.activeAnimeDirectory
? sonarrSettings.activeAnimeDirectory
: sonarrSettings.activeDirectory;
let qualityProfile =
seriesType === 'anime' && sonarrSettings.activeAnimeProfileId
? sonarrSettings.activeAnimeProfileId
: sonarrSettings.activeProfileId;
if (
this.rootFolder &&
this.rootFolder !== '' &&
this.rootFolder !== rootFolder
) {
rootFolder = this.rootFolder;
logger.info(`Request has an override root folder: ${rootFolder}`, {
label: 'Media Request',
});
}
if (this.profileId && this.profileId !== qualityProfile) {
qualityProfile = this.profileId;
logger.info(`Request has an override profile id: ${qualityProfile}`, {
label: 'Media Request',
});
}
// Run this asynchronously so we don't wait for it on the UI side
sonarr
.addSeries({
profileId:
seriesType === 'anime' && sonarrSettings.activeAnimeProfileId
? sonarrSettings.activeAnimeProfileId
: sonarrSettings.activeProfileId,
rootFolderPath:
seriesType === 'anime' && sonarrSettings.activeAnimeDirectory
? sonarrSettings.activeAnimeDirectory
: sonarrSettings.activeDirectory,
profileId: qualityProfile,
rootFolderPath: rootFolder,
title: series.name,
tvdbid: series.external_ids.tvdb_id,
seasons: this.seasons.map((season) => season.seasonNumber),

@ -0,0 +1,18 @@
import { RadarrProfile, RadarrRootFolder } from '../../api/radarr';
export interface ServiceCommonServer {
id: number;
name: string;
is4k: boolean;
isDefault: boolean;
activeProfileId: number;
activeDirectory: string;
activeAnimeProfileId?: number;
activeAnimeDirectory?: string;
}
export interface ServiceCommonServerWithDetails {
server: ServiceCommonServer;
profiles: RadarrProfile[];
rootFolders: Partial<RadarrRootFolder>[];
}

@ -12,6 +12,7 @@ export enum Permission {
REQUEST_4K = 1024,
REQUEST_4K_MOVIE = 2048,
REQUEST_4K_TV = 4096,
REQUEST_ADVANCED = 8192,
}
/**

@ -14,6 +14,7 @@ import mediaRoutes from './media';
import personRoutes from './person';
import collectionRoutes from './collection';
import { getAppVersion, getCommitTag } from '../utils/appVersion';
import serviceRoutes from './service';
const router = Router();
@ -45,6 +46,7 @@ router.use('/tv', isAuthenticated(), tvRoutes);
router.use('/media', isAuthenticated(), mediaRoutes);
router.use('/person', isAuthenticated(), personRoutes);
router.use('/collection', isAuthenticated(), collectionRoutes);
router.use('/service', isAuthenticated(), serviceRoutes);
router.use('/auth', authRoutes);
router.get('/', (_req, res) => {

@ -199,6 +199,9 @@ requestRoutes.post(
? req.user
: undefined,
is4k: req.body.is4k,
serverId: req.body.serverId,
profileId: req.body.profileId,
rootFolder: req.body.rootFolder,
seasons: finalSeasons.map(
(sn) =>
new SeasonRequest({
@ -238,6 +241,102 @@ requestRoutes.get('/:requestId', async (req, res, next) => {
}
});
requestRoutes.put<{ requestId: string }>(
'/:requestId',
isAuthenticated(Permission.MANAGE_REQUESTS),
async (req, res, next) => {
const requestRepository = getRepository(MediaRequest);
try {
const request = await requestRepository.findOne(
Number(req.params.requestId)
);
if (!request) {
return next({ status: 404, message: 'Request not found' });
}
if (req.body.mediaType === 'movie') {
request.serverId = req.body.serverId;
request.profileId = req.body.profileId;
request.rootFolder = req.body.rootFolder;
requestRepository.save(request);
} else if (req.body.mediaType === 'tv') {
const mediaRepository = getRepository(Media);
request.serverId = req.body.serverId;
request.profileId = req.body.profileId;
request.rootFolder = req.body.rootFolder;
const requestedSeasons = req.body.seasons as number[] | undefined;
if (!requestedSeasons || requestedSeasons.length === 0) {
throw new Error(
'Missing seasons. If you want to cancel a tv request, use the DELETE method.'
);
}
// Get existing media so we can work with all the requests
const media = await mediaRepository.findOneOrFail({
where: { tmdbId: request.media.tmdbId, mediaType: MediaType.TV },
relations: ['requests'],
});
// Get all requested seasons that are not part of this request we are editing
const existingSeasons = media.requests
.filter((r) => r.is4k === request.is4k && r.id !== request.id)
.reduce((seasons, r) => {
const combinedSeasons = r.seasons.map(
(season) => season.seasonNumber
);
return [...seasons, ...combinedSeasons];
}, [] as number[]);
const filteredSeasons = requestedSeasons.filter(
(rs) => !existingSeasons.includes(rs)
);
if (filteredSeasons.length === 0) {
return next({
status: 202,
message: 'No seasons available to request',
});
}
const newSeasons = requestedSeasons.filter(
(sn) => !request.seasons.map((s) => s.seasonNumber).includes(sn)
);
request.seasons = request.seasons.filter((rs) =>
filteredSeasons.includes(rs.seasonNumber)
);
if (newSeasons.length > 0) {
logger.debug('Adding new seasons to request', {
label: 'Media Request',
newSeasons,
});
request.seasons.push(
...newSeasons.map(
(ns) =>
new SeasonRequest({
seasonNumber: ns,
status: MediaRequestStatus.PENDING,
})
)
);
}
await requestRepository.save(request);
}
return res.status(200).json(request);
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
requestRoutes.delete('/:requestId', async (req, res, next) => {
const requestRepository = getRepository(MediaRequest);

@ -0,0 +1,148 @@
import { Router } from 'express';
import RadarrAPI from '../api/radarr';
import SonarrAPI from '../api/sonarr';
import {
ServiceCommonServer,
ServiceCommonServerWithDetails,
} from '../interfaces/api/serviceInterfaces';
import { getSettings } from '../lib/settings';
const serviceRoutes = Router();
serviceRoutes.get('/radarr', async (req, res) => {
const settings = getSettings();
const filteredRadarrServers: ServiceCommonServer[] = settings.radarr.map(
(radarr) => ({
id: radarr.id,
name: radarr.name,
is4k: radarr.is4k,
isDefault: radarr.isDefault,
activeDirectory: radarr.activeDirectory,
activeProfileId: radarr.activeProfileId,
})
);
return res.status(200).json(filteredRadarrServers);
});
serviceRoutes.get<{ radarrId: string }>(
'/radarr/:radarrId',
async (req, res, next) => {
const settings = getSettings();
const radarrSettings = settings.radarr.find(
(radarr) => radarr.id === Number(req.params.radarrId)
);
if (!radarrSettings) {
return next({
status: 404,
message: 'Radarr server with provided ID does not exist.',
});
}
const radarr = new RadarrAPI({
apiKey: radarrSettings.apiKey,
url: `${radarrSettings.useSsl ? 'https' : 'http'}://${
radarrSettings.hostname
}:${radarrSettings.port}${radarrSettings.baseUrl ?? ''}/api`,
});
const profiles = await radarr.getProfiles();
const rootFolders = await radarr.getRootFolders();
return res.status(200).json({
server: {
id: radarrSettings.id,
name: radarrSettings.name,
is4k: radarrSettings.is4k,
isDefault: radarrSettings.isDefault,
activeDirectory: radarrSettings.activeDirectory,
activeProfileId: radarrSettings.activeProfileId,
},
profiles: profiles.map((profile) => ({
id: profile.id,
name: profile.name,
})),
rootFolders: rootFolders.map((folder) => ({
id: folder.id,
freeSpace: folder.freeSpace,
path: folder.path,
totalSpace: folder.totalSpace,
})),
} as ServiceCommonServerWithDetails);
}
);
serviceRoutes.get('/sonarr', async (req, res) => {
const settings = getSettings();
const filteredSonarrServers: ServiceCommonServer[] = settings.sonarr.map(
(sonarr) => ({
id: sonarr.id,
name: sonarr.name,
is4k: sonarr.is4k,
isDefault: sonarr.isDefault,
activeDirectory: sonarr.activeDirectory,
activeProfileId: sonarr.activeProfileId,
activeAnimeProfileId: sonarr.activeAnimeProfileId,
activeAnimeDirectory: sonarr.activeAnimeDirectory,
})
);
return res.status(200).json(filteredSonarrServers);
});
serviceRoutes.get<{ sonarrId: string }>(
'/sonarr/:sonarrId',
async (req, res, next) => {
const settings = getSettings();
const sonarrSettings = settings.sonarr.find(
(radarr) => radarr.id === Number(req.params.sonarrId)
);
if (!sonarrSettings) {
return next({
status: 404,
message: 'Radarr server with provided ID does not exist.',
});
}
const sonarr = new SonarrAPI({
apiKey: sonarrSettings.apiKey,
url: `${sonarrSettings.useSsl ? 'https' : 'http'}://${
sonarrSettings.hostname
}:${sonarrSettings.port}${sonarrSettings.baseUrl ?? ''}/api`,
});
const profiles = await sonarr.getProfiles();
const rootFolders = await sonarr.getRootFolders();
return res.status(200).json({
server: {
id: sonarrSettings.id,
name: sonarrSettings.name,
is4k: sonarrSettings.is4k,
isDefault: sonarrSettings.isDefault,
activeDirectory: sonarrSettings.activeDirectory,
activeProfileId: sonarrSettings.activeProfileId,
activeAnimeProfileId: sonarrSettings.activeAnimeProfileId,
activeAnimeDirectory: sonarrSettings.activeAnimeDirectory,
},
profiles: profiles.map((profile) => ({
id: profile.id,
name: profile.name,
})),
rootFolders: rootFolders.map((folder) => ({
id: folder.id,
freeSpace: folder.freeSpace,
path: folder.path,
totalSpace: folder.totalSpace,
})),
} as ServiceCommonServerWithDetails);
}
);
export default serviceRoutes;

@ -103,6 +103,10 @@ export class MediaSubscriber implements EntitySubscriberInterface {
}
public beforeUpdate(event: UpdateEvent<Media>): void {
if (!event.entity) {
return;
}
if (
event.entity.mediaType === MediaType.MOVIE &&
event.entity.status === MediaStatus.AVAILABLE

@ -58,9 +58,9 @@ const Alert: React.FC<AlertProps> = ({ title, children, type }) => {
<div className="flex">
<div className={`flex-shrink-0 ${design.titleColor}`}>{design.svg}</div>
<div className="ml-3">
<h3 className={`text-sm font-medium ${design.titleColor}`}>
<div className={`text-sm font-medium ${design.titleColor}`}>
{title}
</h3>
</div>
<div className={`mt-2 text-sm ${design.textColor}`}>{children}</div>
</div>
</div>

@ -1,8 +1,37 @@
import React from 'react';
export const SmallLoadingSpinner: React.FC = () => {
return (
<div className="inset-0 flex items-center justify-center w-full h-full text-gray-200">
<svg
className="w-10 h-10"
viewBox="0 0 38 38"
xmlns="http://www.w3.org/2000/svg"
stroke="currentColor"
>
<g fill="none" fillRule="evenodd">
<g transform="translate(1 1)" strokeWidth="2">
<circle strokeOpacity=".5" cx="18" cy="18" r="18" />
<path d="M36 18c0-9.94-8.06-18-18-18">
<animateTransform
attributeName="transform"
type="rotate"
from="0 18 18"
to="360 18 18"
dur="1s"
repeatCount="indefinite"
/>
</path>
</g>
</g>
</svg>
</div>
);
};
const LoadingSpinner: React.FC = () => {
return (
<div className="h-64 inset-0 flex justify-center items-center text-gray-200">
<div className="inset-0 flex items-center justify-center h-64 text-gray-200">
<svg
className="w-16 h-16"
viewBox="0 0 38 38"

@ -66,7 +66,7 @@ const Modal: React.FC<ModalProps> = ({
return ReactDOM.createPortal(
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className="fixed top-0 left-0 right-0 bottom-0 bg-gray-800 bg-opacity-50 w-full h-full z-50 flex justify-center items-center"
className="fixed top-0 bottom-0 left-0 right-0 z-50 flex items-center justify-center w-full h-full bg-gray-800 bg-opacity-50"
onKeyDown={(e) => {
if (e.key === 'Escape') {
typeof onCancel === 'function' && backgroundClickable
@ -98,7 +98,7 @@ const Modal: React.FC<ModalProps> = ({
show={!loading}
>
<div
className="inline-block align-bottom bg-gray-700 sm:rounded-lg px-4 pt-5 pb-4 text-left overflow-auto shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-3xl w-full max-h-full"
className="inline-block w-full max-h-full px-4 pt-5 pb-4 overflow-auto text-left align-bottom transition-all transform bg-gray-700 shadow-xl sm:rounded-lg sm:my-8 sm:align-middle sm:max-w-3xl"
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline"
@ -106,7 +106,7 @@ const Modal: React.FC<ModalProps> = ({
>
<div className="sm:flex sm:items-center">
{iconSvg && (
<div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-gray-600 text-white sm:mx-0 sm:h-10 sm:w-10">
<div className="flex items-center justify-center flex-shrink-0 w-12 h-12 mx-auto text-white bg-gray-600 rounded-full sm:mx-0 sm:h-10 sm:w-10">
{iconSvg}
</div>
)}
@ -116,12 +116,12 @@ const Modal: React.FC<ModalProps> = ({
}`}
>
{title && (
<h3
className="text-lg leading-6 font-medium text-white"
<span
className="text-lg font-medium leading-6 text-white"
id="modal-headline"
>
{title}
</h3>
</span>
)}
</div>
</div>
@ -131,7 +131,7 @@ const Modal: React.FC<ModalProps> = ({
</div>
)}
{(onCancel || onOk || onSecondary || onTertiary) && (
<div className="mt-5 sm:mt-4 flex justify-center sm:justify-start flex-row-reverse">
<div className="flex flex-row-reverse justify-center mt-5 sm:mt-4 sm:justify-start">
{typeof onOk === 'function' && (
<Button
buttonType={okButtonType}

@ -1,8 +1,8 @@
/* eslint-disable jsx-a11y/click-events-have-key-events */
import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import Transition from '../../Transition';
import { useLockBodyScroll } from '../../../hooks/useLockBodyScroll';
import useClickOutside from '../../../hooks/useClickOutside';
interface SlideOverProps {
show?: boolean;
@ -21,9 +21,6 @@ const SlideOver: React.FC<SlideOverProps> = ({
const [isMounted, setIsMounted] = useState(false);
const slideoverRef = useRef(null);
useLockBodyScroll(show);
useClickOutside(slideoverRef, () => {
onClose();
});
useEffect(() => {
setIsMounted(true);
@ -44,8 +41,15 @@ const SlideOver: React.FC<SlideOverProps> = ({
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className={`z-50 fixed inset-0 overflow-hidden bg-opacity-50 bg-gray-800`}
onClick={() => onClose()}
onKeyDown={(e) => {
if (e.key === 'Escape') {
onClose();
}
}}
>
<div className="absolute inset-0 overflow-hidden">
<section className="absolute inset-y-0 right-0 flex max-w-full pl-10">
@ -59,7 +63,12 @@ const SlideOver: React.FC<SlideOverProps> = ({
leaveFrom="translate-x-0"
leaveTo="translate-x-full"
>
<div className="w-screen max-w-md" ref={slideoverRef}>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className="w-screen max-w-md"
ref={slideoverRef}
onClick={(e) => e.stopPropagation()}
>
<div className="flex flex-col h-full overflow-y-scroll bg-gray-700 shadow-xl">
<header className="px-4 py-6 space-y-1 bg-indigo-600">
<div className="flex items-center justify-between space-x-3">

@ -6,9 +6,15 @@ import { MediaRequestStatus } from '../../../server/constants/media';
import Button from '../Common/Button';
import axios from 'axios';
import globalMessages from '../../i18n/globalMessages';
import RequestModal from '../RequestModal';
import useRequestOverride from '../../hooks/useRequestOverride';
const messages = defineMessages({
seasons: 'Seasons',
requestoverrides: 'Request Overrides',
server: 'Server',
profilechanged: 'Profile Changed',
rootfolder: 'Root Folder',
});
interface RequestBlockProps {
@ -19,6 +25,8 @@ interface RequestBlockProps {
const RequestBlock: React.FC<RequestBlockProps> = ({ request, onUpdate }) => {
const intl = useIntl();
const [isUpdating, setIsUpdating] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const { profile, rootFolder, server } = useRequestOverride(request);
const updateRequest = async (type: 'approve' | 'decline'): Promise<void> => {
setIsUpdating(true);
@ -43,6 +51,20 @@ const RequestBlock: React.FC<RequestBlockProps> = ({ request, onUpdate }) => {
return (
<div className="block">
<RequestModal
show={showEditModal}
tmdbId={request.media.tmdbId}
type={request.type}
is4k={request.is4k}
editRequest={request}
onCancel={() => setShowEditModal(false)}
onComplete={() => {
if (onUpdate) {
onUpdate();
}
setShowEditModal(false);
}}
/>
<div className="px-4 py-4">
<div className="flex items-center justify-between">
<div className="flex-col items-center flex-1 min-w-0 mr-6 text-sm leading-5 text-gray-300">
@ -107,7 +129,7 @@ const RequestBlock: React.FC<RequestBlockProps> = ({ request, onUpdate }) => {
</svg>
</Button>
</span>
<span>
<span className="mr-1">
<Button
buttonType="danger"
onClick={() => updateRequest('decline')}
@ -127,6 +149,22 @@ const RequestBlock: React.FC<RequestBlockProps> = ({ request, onUpdate }) => {
</svg>
</Button>
</span>
<span>
<Button
buttonType="primary"
onClick={() => setShowEditModal(true)}
disabled={isUpdating}
>
<svg
className="w-4 h-4"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
</svg>
</Button>
</span>
</>
)}
{request.status !== MediaRequestStatus.PENDING && (
@ -209,6 +247,39 @@ const RequestBlock: React.FC<RequestBlockProps> = ({ request, onUpdate }) => {
</div>
</div>
)}
{(server || profile || rootFolder) && (
<>
<div className="mt-4 mb-1 text-sm">
{intl.formatMessage(messages.requestoverrides)}
</div>
<ul className="px-2 text-xs bg-gray-800 divide-y divide-gray-700 rounded-md">
{server && (
<li className="flex justify-between px-1 py-2">
<span className="font-bold">
{intl.formatMessage(messages.server)}
</span>
<span>{server}</span>
</li>
)}
{profile !== null && (
<li className="flex justify-between px-1 py-2">
<span className="font-bold">
{intl.formatMessage(messages.profilechanged)}
</span>
<span>ID {profile}</span>
</li>
)}
{rootFolder && (
<li className="flex justify-between px-1 py-2">
<span className="mr-2 font-bold">
{intl.formatMessage(messages.rootfolder)}
</span>
<span>{rootFolder}</span>
</li>
)}
</ul>
</>
)}
</div>
</div>
);

@ -24,6 +24,7 @@ import axios from 'axios';
import globalMessages from '../../../i18n/globalMessages';
import Link from 'next/link';
import { useToasts } from 'react-toast-notifications';
import RequestModal from '../../RequestModal';
const messages = defineMessages({
requestedby: 'Requested by {username}',
@ -51,6 +52,7 @@ const RequestItem: React.FC<RequestItemProps> = ({
const { addToast } = useToasts();
const intl = useIntl();
const { hasPermission } = useUser();
const [showEditModal, setShowEditModal] = useState(false);
const { locale } = useContext(LanguageContext);
const url =
request.type === 'movie'
@ -116,6 +118,18 @@ const RequestItem: React.FC<RequestItemProps> = ({
return (
<tr className="relative w-full h-24 p-2 text-white bg-gray-800">
<RequestModal
show={showEditModal}
tmdbId={request.media.tmdbId}
type={request.type}
is4k={request.is4k}
editRequest={request}
onCancel={() => setShowEditModal(false)}
onComplete={() => {
revalidateList();
setShowEditModal(false);
}}
/>
<Table.TD>
<div className="flex items-center">
<Link
@ -276,7 +290,7 @@ const RequestItem: React.FC<RequestItemProps> = ({
</span>
</Button>
</span>
<span>
<span className="mr-2">
<Button
buttonType="danger"
buttonSize="sm"
@ -299,6 +313,25 @@ const RequestItem: React.FC<RequestItemProps> = ({
</span>
</Button>
</span>
<span>
<Button
buttonType="primary"
buttonSize="sm"
onClick={() => setShowEditModal(true)}
>
<svg
className="w-4 h-4 mr-0 sm:mr-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
</svg>
<span className="hidden sm:block">
{intl.formatMessage(globalMessages.edit)}
</span>
</Button>
</span>
</>
)}
</Table.TD>

@ -0,0 +1,312 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react';
import useSWR from 'swr';
import { SmallLoadingSpinner } from '../../Common/LoadingSpinner';
import type {
ServiceCommonServer,
ServiceCommonServerWithDetails,
} from '../../../../server/interfaces/api/serviceInterfaces';
import { defineMessages, useIntl } from 'react-intl';
const formatBytes = (bytes: number, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
const messages = defineMessages({
advancedoptions: 'Advanced Options',
destinationserver: 'Destination Server',
qualityprofile: 'Quality Profile',
rootfolder: 'Root Folder',
animenote: '* This series is an anime.',
default: '(Default)',
loadingprofiles: 'Loading profiles…',
loadingfolders: 'Loading folders…',
});
export type RequestOverrides = {
server?: number;
profile?: number;
folder?: string;
};
interface AdvancedRequesterProps {
type: 'movie' | 'tv';
is4k: boolean;
isAnime?: boolean;
defaultOverrides?: RequestOverrides;
onChange: (overrides: RequestOverrides) => void;
}
const AdvancedRequester: React.FC<AdvancedRequesterProps> = ({
type,
is4k = false,
isAnime = false,
defaultOverrides,
onChange,
}) => {
const intl = useIntl();
const { data, error } = useSWR<ServiceCommonServer[]>(
`/api/v1/service/${type === 'movie' ? 'radarr' : 'sonarr'}`,
{
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
revalidateOnMount: true,
}
);
const [selectedServer, setSelectedServer] = useState<number | null>(
defaultOverrides?.server !== undefined && defaultOverrides?.server >= 0
? defaultOverrides?.server
: null
);
const [selectedProfile, setSelectedProfile] = useState<number>(
defaultOverrides?.profile ?? -1
);
const [selectedFolder, setSelectedFolder] = useState<string>(
defaultOverrides?.folder ?? ''
);
const {
data: serverData,
isValidating,
} = useSWR<ServiceCommonServerWithDetails>(
selectedServer !== null
? `/api/v1/service/${
type === 'movie' ? 'radarr' : 'sonarr'
}/${selectedServer}`
: null,
{
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
}
);
useEffect(() => {
let defaultServer = data?.find(
(server) => server.isDefault && is4k === server.is4k
);
if (!defaultServer && (data ?? []).length > 0) {
defaultServer = data?.[0];
}
if (
defaultServer &&
defaultServer.id !== selectedServer &&
(!defaultOverrides || defaultOverrides.server === null)
) {
setSelectedServer(defaultServer.id);
}
}, [data]);
useEffect(() => {
if (serverData) {
const defaultProfile = serverData.profiles.find(
(profile) =>
profile.id ===
(isAnime
? serverData.server.activeAnimeProfileId
: serverData.server.activeProfileId)
);
const defaultFolder = serverData.rootFolders.find(
(folder) =>
folder.path ===
(isAnime
? serverData.server.activeAnimeDirectory
: serverData.server.activeDirectory)
);
if (
defaultProfile &&
defaultProfile.id !== selectedProfile &&
(!defaultOverrides || defaultOverrides.profile === null)
) {
setSelectedProfile(defaultProfile.id);
}
if (
defaultFolder &&
defaultFolder.path !== selectedFolder &&
(!defaultOverrides || defaultOverrides.folder === null)
) {
setSelectedFolder(defaultFolder?.path ?? '');
}
}
}, [serverData]);
useEffect(() => {
if (
defaultOverrides &&
defaultOverrides.server !== null &&
defaultOverrides.server !== undefined
) {
setSelectedServer(defaultOverrides.server);
}
if (
defaultOverrides &&
defaultOverrides.profile !== null &&
defaultOverrides.profile !== undefined
) {
setSelectedProfile(defaultOverrides.profile);
}
if (
defaultOverrides &&
defaultOverrides.folder !== null &&
defaultOverrides.folder !== undefined
) {
setSelectedFolder(defaultOverrides.folder);
}
}, [
defaultOverrides?.server,
defaultOverrides?.folder,
defaultOverrides?.profile,
]);
useEffect(() => {
if (selectedServer !== null) {
onChange({
folder: selectedFolder !== '' ? selectedFolder : undefined,
profile: selectedProfile !== -1 ? selectedProfile : undefined,
server: selectedServer ?? undefined,
});
}
}, [selectedFolder, selectedServer, selectedProfile]);
if (!data && !error) {
return (
<div className="w-full mb-2">
<SmallLoadingSpinner />
</div>
);
}
if (!data || selectedServer === null) {
return null;
}
return (
<>
<div className="flex items-center mb-2 font-bold tracking-wider">
<svg
className="w-4 h-4 mr-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M9.707 7.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L13 8.586V5h3a2 2 0 012 2v5a2 2 0 01-2 2H8a2 2 0 01-2-2V7a2 2 0 012-2h3v3.586L9.707 7.293zM11 3a1 1 0 112 0v2h-2V3z" />
<path d="M4 9a2 2 0 00-2 2v5a2 2 0 002 2h8a2 2 0 002-2H4V9z" />
</svg>
{intl.formatMessage(messages.advancedoptions)}
</div>
<div className="p-4 bg-gray-600 rounded-md shadow">
<div className="flex flex-col items-center justify-between md:flex-row">
<div className="flex-grow flex-shrink-0 w-full mb-2 md:w-1/3 md:pr-4 md:mb-0">
<label htmlFor="server" className="block text-sm font-medium">
{intl.formatMessage(messages.destinationserver)}
</label>
<select
id="server"
name="server"
onChange={(e) => setSelectedServer(Number(e.target.value))}
onBlur={(e) => setSelectedServer(Number(e.target.value))}
value={selectedServer}
className="block w-full py-2 pl-3 pr-10 mt-1 text-base leading-6 text-white transition duration-150 ease-in-out bg-gray-800 border-gray-700 rounded-md form-select focus:outline-none focus:ring-blue focus:border-blue-300 sm:text-sm sm:leading-5"
>
{data.map((server) => (
<option key={`server-list-${server.id}`} value={server.id}>
{server.name}
{server.isDefault && server.is4k === is4k
? ` ${intl.formatMessage(messages.default)}`
: ''}
</option>
))}
</select>
</div>
<div className="flex-grow flex-shrink-0 w-full mb-2 md:w-1/3 md:pr-4 md:mb-0">
<label htmlFor="server" className="block text-sm font-medium">
{intl.formatMessage(messages.qualityprofile)}
</label>
<select
id="profile"
name="profile"
value={selectedProfile}
onChange={(e) => setSelectedProfile(Number(e.target.value))}
onBlur={(e) => setSelectedProfile(Number(e.target.value))}
className="block w-full py-2 pl-3 pr-10 mt-1 text-base leading-6 text-white transition duration-150 ease-in-out bg-gray-800 border-gray-700 rounded-md form-select focus:outline-none focus:ring-blue focus:border-blue-300 sm:text-sm sm:leading-5"
>
{isValidating && (
<option value="">
{intl.formatMessage(messages.loadingprofiles)}
</option>
)}
{!isValidating &&
serverData &&
serverData.profiles.map((profile) => (
<option key={`profile-list${profile.id}`} value={profile.id}>
{profile.name}
{isAnime &&
serverData.server.activeAnimeProfileId === profile.id
? ` ${intl.formatMessage(messages.default)}`
: !isAnime &&
serverData.server.activeProfileId === profile.id
? ` ${intl.formatMessage(messages.default)}`
: ''}
</option>
))}
</select>
</div>
<div className="flex-grow flex-shrink-0 w-full mb-2 md:w-1/3 md:mb-0">
<label htmlFor="server" className="block text-sm font-medium">
{intl.formatMessage(messages.rootfolder)}
</label>
<select
id="folder"
name="folder"
value={selectedFolder}
onChange={(e) => setSelectedFolder(e.target.value)}
onBlur={(e) => setSelectedFolder(e.target.value)}
className="block w-full py-2 pl-3 pr-10 mt-1 text-base leading-6 text-white transition duration-150 ease-in-out bg-gray-800 border-gray-700 rounded-md form-select focus:outline-none focus:ring-blue focus:border-blue-300 sm:text-sm sm:leading-5"
>
{isValidating && (
<option value="">
{intl.formatMessage(messages.loadingfolders)}
</option>
)}
{!isValidating &&
serverData &&
serverData.rootFolders.map((folder) => (
<option key={`folder-list${folder.id}`} value={folder.path}>
{folder.path} ({formatBytes(folder.freeSpace ?? 0)})
{isAnime &&
serverData.server.activeAnimeDirectory === folder.path
? ` ${intl.formatMessage(messages.default)}`
: !isAnime &&
serverData.server.activeDirectory === folder.path
? ` ${intl.formatMessage(messages.default)}`
: ''}
</option>
))}
</select>
</div>
</div>
{isAnime && (
<div className="mt-4 italic">
{intl.formatMessage(messages.animenote)}
</div>
)}
</div>
</>
);
};
export default AdvancedRequester;

@ -13,6 +13,9 @@ import {
MediaRequestStatus,
} from '../../../server/constants/media';
import DownloadIcon from '../../assets/download.svg';
import Alert from '../Common/Alert';
import AdvancedRequester, { RequestOverrides } from './AdvancedRequester';
import globalMessages from '../../i18n/globalMessages';
const messages = defineMessages({
requestadmin:
@ -33,11 +36,14 @@ const messages = defineMessages({
request4k: 'Request 4K',
requestfrom: 'There is currently a pending request from {username}',
request4kfrom: 'There is currently a pending 4K request from {username}',
errorediting: 'Something went wrong editing the request.',
requestedited: 'Request edited.',
});
interface RequestModalProps extends React.HTMLAttributes<HTMLDivElement> {
tmdbId: number;
is4k?: boolean;
editRequest?: MediaRequest;
onCancel?: () => void;
onComplete?: (newStatus: MediaStatus) => void;
onUpdating?: (isUpdating: boolean) => void;
@ -48,9 +54,14 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
onComplete,
tmdbId,
onUpdating,
is4k,
editRequest,
is4k = false,
}) => {
const [isUpdating, setIsUpdating] = useState(false);
const [
requestOverrides,
setRequestOverrides,
] = useState<RequestOverrides | null>(null);
const { addToast } = useToasts();
const { data, error } = useSWR<MovieDetails>(`/api/v1/movie/${tmdbId}`, {
revalidateOnMount: true,
@ -66,10 +77,19 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
const sendRequest = useCallback(async () => {
setIsUpdating(true);
let overrideParams = {};
if (requestOverrides) {
overrideParams = {
serverId: requestOverrides.server,
profileId: requestOverrides.profile,
rootFolder: requestOverrides.folder,
};
}
const response = await axios.post<MediaRequest>('/api/v1/request', {
mediaId: data?.id,
mediaType: 'movie',
is4k,
...overrideParams,
});
if (response.data) {
@ -94,7 +114,7 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
);
setIsUpdating(false);
}
}, [data, onComplete, addToast]);
}, [data, onComplete, addToast, requestOverrides]);
const activeRequest = data?.mediaInfo?.requests?.find(
(request) => request.is4k === !!is4k
@ -125,35 +145,64 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
}
};
const updateRequest = async () => {
setIsUpdating(true);
try {
await axios.put(`/api/v1/request/${editRequest?.id}`, {
mediaType: 'movie',
serverId: requestOverrides?.server,
profileId: requestOverrides?.profile,
rootFolder: requestOverrides?.folder,
});
addToast(<span>{intl.formatMessage(messages.requestedited)}</span>, {
appearance: 'success',
autoDismiss: true,
});
if (onComplete) {
onComplete(MediaStatus.PENDING);
}
} catch (e) {
addToast(<span>{intl.formatMessage(messages.errorediting)}</span>, {
appearance: 'error',
autoDismiss: true,
});
} finally {
setIsUpdating(false);
}
};
const isOwner = activeRequest
? activeRequest.requestedBy.id === user?.id ||
hasPermission(Permission.MANAGE_REQUESTS)
: false;
const text = hasPermission(Permission.MANAGE_REQUESTS)
? intl.formatMessage(messages.requestadmin)
: undefined;
if (activeRequest?.status === MediaRequestStatus.PENDING) {
return (
<Modal
loading={!data && !error}
backgroundClickable
onCancel={onCancel}
onOk={isOwner ? () => cancelRequest() : undefined}
okDisabled={isUpdating}
title={intl.formatMessage(
is4k ? messages.pending4krequest : messages.pendingrequest,
{
title: data?.title,
}
)}
okText={
onOk={() => updateRequest()}
okDisabled={isUpdating}
okText={intl.formatMessage(globalMessages.edit)}
okButtonType="primary"
onSecondary={isOwner ? () => cancelRequest() : undefined}
secondaryDisabled={isUpdating}
secondaryText={
isUpdating
? intl.formatMessage(messages.cancelling)
: intl.formatMessage(messages.cancel)
}
okButtonType={'danger'}
secondaryButtonType="danger"
cancelText={intl.formatMessage(messages.close)}
iconSvg={<DownloadIcon className="w-6 h-6" />}
>
@ -163,6 +212,26 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
username: activeRequest.requestedBy.username,
}
)}
{hasPermission(Permission.REQUEST_ADVANCED) && (
<div className="mt-4">
<AdvancedRequester
type="movie"
is4k={is4k}
defaultOverrides={
editRequest
? {
folder: editRequest.rootFolder,
profile: editRequest.profileId,
server: editRequest.serverId,
}
: undefined
}
onChange={(overrides) => {
setRequestOverrides(overrides);
}}
/>
</div>
)}
</Modal>
);
}
@ -186,7 +255,24 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
okButtonType={'primary'}
iconSvg={<DownloadIcon className="w-6 h-6" />}
>
<p className="text-center md:text-left">{text}</p>
{(hasPermission(Permission.MANAGE_REQUESTS) ||
hasPermission(Permission.AUTO_APPROVE) ||
hasPermission(Permission.AUTO_APPROVE_MOVIE)) && (
<p className="mt-6">
<Alert title="Auto Approval" type="info">
{intl.formatMessage(messages.requestadmin)}
</Alert>
</p>
)}
{hasPermission(Permission.REQUEST_ADVANCED) && (
<AdvancedRequester
type="movie"
is4k={is4k}
onChange={(overrides) => {
setRequestOverrides(overrides);
}}
/>
)}
</Modal>
);
};

@ -6,6 +6,7 @@ import { defineMessages, useIntl } from 'react-intl';
import { MediaRequest } from '../../../server/entity/MediaRequest';
import useSWR from 'swr';
import { useToasts } from 'react-toast-notifications';
import { ANIME_KEYWORD_ID } from '../../../server/api/themoviedb';
import axios from 'axios';
import {
MediaStatus,
@ -15,13 +16,14 @@ import { TvDetails } from '../../../server/models/Tv';
import Badge from '../Common/Badge';
import globalMessages from '../../i18n/globalMessages';
import SeasonRequest from '../../../server/entity/SeasonRequest';
import Alert from '../Common/Alert';
import AdvancedRequester, { RequestOverrides } from './AdvancedRequester';
const messages = defineMessages({
requestadmin: 'Your request will be immediately approved.',
cancelrequest:
'This will remove your request. Are you sure you want to continue?',
requestSuccess: '<strong>{title}</strong> successfully requested!',
requestCancel: 'Request for <strong>{title}</strong> cancelled',
requesttitle: 'Request {title}',
request4ktitle: 'Request {title} in 4K',
requesting: 'Requesting...',
@ -34,6 +36,9 @@ const messages = defineMessages({
seasonnumber: 'Season {number}',
extras: 'Extras',
notrequested: 'Not Requested',
errorediting: 'Something went wrong editing the request.',
requestedited: 'Request edited.',
requestcancelled: 'Request cancelled.',
});
interface RequestModalProps extends React.HTMLAttributes<HTMLDivElement> {
@ -42,6 +47,7 @@ interface RequestModalProps extends React.HTMLAttributes<HTMLDivElement> {
onComplete?: (newStatus: MediaStatus) => void;
onUpdating?: (isUpdating: boolean) => void;
is4k?: boolean;
editRequest?: MediaRequest;
}
const TvRequestModal: React.FC<RequestModalProps> = ({
@ -49,14 +55,72 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
onComplete,
tmdbId,
onUpdating,
editRequest,
is4k = false,
}) => {
const { addToast } = useToasts();
const editingSeasons: number[] = (editRequest?.seasons ?? []).map(
(season) => season.seasonNumber
);
const { data, error } = useSWR<TvDetails>(`/api/v1/tv/${tmdbId}`);
const [selectedSeasons, setSelectedSeasons] = useState<number[]>([]);
const [
requestOverrides,
setRequestOverrides,
] = useState<RequestOverrides | null>(null);
const [selectedSeasons, setSelectedSeasons] = useState<number[]>(
editRequest ? editingSeasons : []
);
const intl = useIntl();
const { hasPermission } = useUser();
const updateRequest = async () => {
if (!editRequest) {
return;
}
if (onUpdating) {
onUpdating(true);
}
try {
if (selectedSeasons.length > 0) {
await axios.put(`/api/v1/request/${editRequest.id}`, {
mediaType: 'tv',
serverId: requestOverrides?.server,
profileId: requestOverrides?.profile,
rootFolder: requestOverrides?.folder,
seasons: selectedSeasons,
});
} else {
await axios.delete(`/api/v1/request/${editRequest.id}`);
}
addToast(
<span>
{selectedSeasons.length > 0
? intl.formatMessage(messages.requestedited)
: intl.formatMessage(messages.requestcancelled)}
</span>,
{
appearance: 'success',
autoDismiss: true,
}
);
if (onComplete) {
onComplete(MediaStatus.PENDING);
}
} catch (e) {
addToast(<span>{intl.formatMessage(messages.errorediting)}</span>, {
appearance: 'error',
autoDismiss: true,
});
} finally {
if (onUpdating) {
onUpdating(false);
}
}
};
const sendRequest = async () => {
if (selectedSeasons.length === 0) {
return;
@ -64,12 +128,21 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
if (onUpdating) {
onUpdating(true);
}
let overrideParams = {};
if (requestOverrides) {
overrideParams = {
serverId: requestOverrides.server,
profileId: requestOverrides.profile,
rootFolder: requestOverrides.folder,
};
}
const response = await axios.post<MediaRequest>('/api/v1/request', {
mediaId: data?.id,
tvdbId: data?.externalIds.tvdbId,
mediaType: 'tv',
is4k,
seasons: selectedSeasons,
...overrideParams,
});
if (response.data) {
@ -99,7 +172,9 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
.reduce((requestedSeasons, request) => {
return [
...requestedSeasons,
...request.seasons.map((sr) => sr.seasonNumber),
...request.seasons
.filter((season) => !editingSeasons.includes(season.seasonNumber))
.map((sr) => sr.seasonNumber),
];
}, [] as number[]);
@ -172,10 +247,6 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
);
};
const text = hasPermission(Permission.MANAGE_REQUESTS)
? intl.formatMessage(messages.requestadmin)
: undefined;
const getSeasonRequest = (
seasonNumber: number
): SeasonRequest | undefined => {
@ -205,20 +276,24 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
loading={!data && !error}
backgroundClickable
onCancel={onCancel}
onOk={() => sendRequest()}
onOk={() => (editRequest ? updateRequest() : sendRequest())}
title={intl.formatMessage(
is4k ? messages.request4ktitle : messages.requesttitle,
{ title: data?.name }
)}
okText={
selectedSeasons.length === 0
editRequest && selectedSeasons.length === 0
? 'Cancel Request'
: selectedSeasons.length === 0
? intl.formatMessage(messages.selectseason)
: intl.formatMessage(messages.requestseasons, {
seasonCount: selectedSeasons.length,
})
}
okDisabled={selectedSeasons.length === 0}
okButtonType="primary"
okDisabled={editRequest ? false : selectedSeasons.length === 0}
okButtonType={
editRequest && selectedSeasons.length === 0 ? 'danger' : `primary`
}
iconSvg={
<svg
className="w-6 h-6"
@ -236,8 +311,18 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
</svg>
}
>
{(hasPermission(Permission.MANAGE_REQUESTS) ||
hasPermission(Permission.AUTO_APPROVE) ||
hasPermission(Permission.AUTO_APPROVE_MOVIE)) &&
!editRequest && (
<p className="mt-6">
<Alert title="Auto Approval" type="info">
{intl.formatMessage(messages.requestadmin)}
</Alert>
</p>
)}
<div className="flex flex-col">
<div className="-mx-4 overflow-auto sm:mx-0 max-h-96">
<div className="-mx-4 sm:mx-0">
<div className="inline-block min-w-full py-2 align-middle">
<div className="overflow-hidden shadow sm:rounded-lg">
<table className="min-w-full">
@ -281,7 +366,7 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
</th>
</tr>
</thead>
<tbody className="bg-gray-600 divide-y">
<tbody className="bg-gray-600 divide-y divide-gray-700">
{data?.seasons
.filter((season) => season.seasonNumber !== 0)
.map((season) => {
@ -302,7 +387,10 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
tabIndex={0}
aria-checked={
!!mediaSeason ||
!!seasonRequest ||
(!!seasonRequest &&
!editingSeasons.includes(
season.seasonNumber
)) ||
isSelectedSeason(season.seasonNumber)
}
onClick={() => toggleSeason(season.seasonNumber)}
@ -312,14 +400,21 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
}
}}
className={`group relative inline-flex items-center justify-center flex-shrink-0 h-5 w-10 cursor-pointer focus:outline-none ${
mediaSeason || seasonRequest ? 'opacity-50' : ''
mediaSeason ||
(!!seasonRequest &&
!editingSeasons.includes(season.seasonNumber))
? 'opacity-50'
: ''
}`}
>
<span
aria-hidden="true"
className={`${
!!mediaSeason ||
!!seasonRequest ||
(!!seasonRequest &&
!editingSeasons.includes(
season.seasonNumber
)) ||
isSelectedSeason(season.seasonNumber)
? 'bg-indigo-500'
: 'bg-gray-800'
@ -329,7 +424,10 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
aria-hidden="true"
className={`${
!!mediaSeason ||
!!seasonRequest ||
(!!seasonRequest &&
!editingSeasons.includes(
season.seasonNumber
)) ||
isSelectedSeason(season.seasonNumber)
? 'translate-x-5'
: 'translate-x-0'
@ -398,7 +496,27 @@ const TvRequestModal: React.FC<RequestModalProps> = ({
</div>
</div>
</div>
<p className="mt-4">{text}</p>
{hasPermission(Permission.REQUEST_ADVANCED) && (
<div className="mt-4">
<AdvancedRequester
type="tv"
is4k={is4k}
isAnime={data?.keywords.some(
(keyword) => keyword.id === ANIME_KEYWORD_ID
)}
onChange={(overrides) => setRequestOverrides(overrides)}
defaultOverrides={
editRequest
? {
folder: editRequest.rootFolder,
profile: editRequest.profileId,
server: editRequest.serverId,
}
: undefined
}
/>
</div>
)}
</Modal>
);
};

@ -3,14 +3,15 @@ import MovieRequestModal from './MovieRequestModal';
import type { MediaStatus } from '../../../server/constants/media';
import TvRequestModal from './TvRequestModal';
import Transition from '../Transition';
import { MediaRequest } from '../../../server/entity/MediaRequest';
interface RequestModalProps {
show: boolean;
type: 'movie' | 'tv';
tmdbId: number;
is4k?: boolean;
editRequest?: MediaRequest;
onComplete?: (newStatus: MediaStatus) => void;
onError?: (error: string) => void;
onCancel?: () => void;
onUpdating?: (isUpdating: boolean) => void;
}
@ -20,6 +21,7 @@ const RequestModal: React.FC<RequestModalProps> = ({
show,
tmdbId,
is4k,
editRequest,
onComplete,
onUpdating,
onCancel,
@ -41,6 +43,7 @@ const RequestModal: React.FC<RequestModalProps> = ({
tmdbId={tmdbId}
onUpdating={onUpdating}
is4k={is4k}
editRequest={editRequest}
/>
</Transition>
);
@ -62,6 +65,7 @@ const RequestModal: React.FC<RequestModalProps> = ({
tmdbId={tmdbId}
onUpdating={onUpdating}
is4k={is4k}
editRequest={editRequest}
/>
</Transition>
);

@ -82,6 +82,16 @@ const SettingsMain: React.FC = () => {
permissionMessages.managerequestsDescription
),
permission: Permission.MANAGE_REQUESTS,
children: [
{
id: 'advancedrequest',
name: intl.formatMessage(permissionMessages.advancedrequest),
description: intl.formatMessage(
permissionMessages.advancedrequestDescription
),
permission: Permission.REQUEST_ADVANCED,
},
],
},
{
id: 'request',

@ -47,6 +47,9 @@ export const messages = defineMessages({
request4kMoviesDescription: 'Grants permission to request 4K movies.',
request4kTv: 'Request 4K Series',
request4kTvDescription: 'Grants permission to request 4K Series.',
advancedrequest: 'Advanced Requests',
advancedrequestDescription:
'Grants permission to use advanced request options. (Ex. Changing servers/profiles/paths)',
save: 'Save',
saving: 'Saving...',
usersaved: 'User saved',
@ -125,6 +128,14 @@ const UserEdit: React.FC = () => {
name: intl.formatMessage(messages.managerequests),
description: intl.formatMessage(messages.managerequestsDescription),
permission: Permission.MANAGE_REQUESTS,
children: [
{
id: 'advancedrequest',
name: intl.formatMessage(messages.advancedrequest),
description: intl.formatMessage(messages.advancedrequestDescription),
permission: Permission.REQUEST_ADVANCED,
},
],
},
{
id: 'request',

@ -0,0 +1,46 @@
import useSWR from 'swr';
import { MediaRequest } from '../../server/entity/MediaRequest';
import { ServiceCommonServer } from '../../server/interfaces/api/serviceInterfaces';
interface OverrideStatus {
server: string | null;
profile: number | null;
rootFolder: string | null;
}
const useRequestOverride = (request: MediaRequest): OverrideStatus => {
const { data } = useSWR<ServiceCommonServer[]>(
`/api/v1/service/${request.type === 'movie' ? 'radarr' : 'sonarr'}`
);
if (!data) {
return {
server: null,
profile: null,
rootFolder: null,
};
}
const defaultServer = data.find(
(server) => server.is4k === request.is4k && server.isDefault
);
const activeServer = data.find((server) => server.id === request.serverId);
return {
server:
activeServer && request.serverId !== defaultServer?.id
? activeServer.name
: null,
profile:
defaultServer?.activeProfileId !== request.profileId
? request.profileId
: null,
rootFolder:
defaultServer?.activeDirectory !== request.rootFolder
? request.rootFolder
: null,
};
};
export default useRequestOverride;

@ -20,6 +20,7 @@ const globalMessages = defineMessages({
retry: 'Retry',
deleting: 'Deleting…',
close: 'Close',
edit: 'Edit',
});
export default globalMessages;

@ -83,7 +83,11 @@
"components.PlexLoginButton.loading": "Loading…",
"components.PlexLoginButton.loggingin": "Logging in…",
"components.PlexLoginButton.loginwithplex": "Login with Plex",
"components.RequestBlock.profilechanged": "Profile Changed",
"components.RequestBlock.requestoverrides": "Request Overrides",
"components.RequestBlock.rootfolder": "Root Folder",
"components.RequestBlock.seasons": "Seasons",
"components.RequestBlock.server": "Server",
"components.RequestButton.approve4krequests": "Approve {requestCount} 4K {requestCount, plural, one {Request} other {Requests}}",
"components.RequestButton.approverequest": "Approve Request",
"components.RequestButton.approverequest4k": "Approve 4K Request",
@ -120,10 +124,19 @@
"components.RequestList.sortAdded": "Request Date",
"components.RequestList.sortModified": "Last Modified",
"components.RequestList.status": "Status",
"components.RequestModal.AdvancedRequester.advancedoptions": "Advanced Options",
"components.RequestModal.AdvancedRequester.animenote": "* This series is an anime.",
"components.RequestModal.AdvancedRequester.default": "(Default)",
"components.RequestModal.AdvancedRequester.destinationserver": "Destination Server",
"components.RequestModal.AdvancedRequester.loadingfolders": "Loading folders…",
"components.RequestModal.AdvancedRequester.loadingprofiles": "Loading profiles…",
"components.RequestModal.AdvancedRequester.qualityprofile": "Quality Profile",
"components.RequestModal.AdvancedRequester.rootfolder": "Root Folder",
"components.RequestModal.cancel": "Cancel Request",
"components.RequestModal.cancelling": "Cancelling…",
"components.RequestModal.cancelrequest": "This will remove your request. Are you sure you want to continue?",
"components.RequestModal.close": "Close",
"components.RequestModal.errorediting": "Something went wrong editing the request.",
"components.RequestModal.extras": "Extras",
"components.RequestModal.notrequested": "Not Requested",
"components.RequestModal.numberofepisodes": "# of Episodes",
@ -136,6 +149,8 @@
"components.RequestModal.requestCancel": "Request for <strong>{title}</strong> cancelled",
"components.RequestModal.requestSuccess": "<strong>{title}</strong> requested.",
"components.RequestModal.requestadmin": "Your request will be immediately approved.",
"components.RequestModal.requestcancelled": "Request cancelled.",
"components.RequestModal.requestedited": "Request edited.",
"components.RequestModal.requestfrom": "There is currently a pending request from {username}",
"components.RequestModal.requesting": "Requesting…",
"components.RequestModal.requestseasons": "Request {seasonCount} {seasonCount, plural, one {Season} other {Seasons}}",
@ -423,6 +438,8 @@
"components.TvDetails.watchtrailer": "Watch Trailer",
"components.UserEdit.admin": "Admin",
"components.UserEdit.adminDescription": "Full administrator access. Bypasses all permission checks.",
"components.UserEdit.advancedrequest": "Advanced Requests",
"components.UserEdit.advancedrequestDescription": "Grants permission to use advanced request options. (Ex. Changing servers/profiles/paths)",
"components.UserEdit.autoapprove": "Auto Approve",
"components.UserEdit.autoapproveDescription": "Grants auto approval for any requests made by this user.",
"components.UserEdit.autoapproveMovies": "Auto Approve Movies",
@ -496,6 +513,7 @@
"i18n.declined": "Declined",
"i18n.delete": "Delete",
"i18n.deleting": "Deleting…",
"i18n.edit": "Edit",
"i18n.failed": "Failed",
"i18n.movies": "Movies",
"i18n.partiallyavailable": "Partially Available",

Loading…
Cancel
Save