feat(frontend): recently added on discover

also improves modal requests by not waiting for result from radarr/sonarr
pull/42/head
sct 4 years ago
parent 7287a6a957
commit 06dc606bcf

@ -736,6 +736,21 @@ components:
name: name:
type: string type: string
example: 720p/1080p example: 720p/1080p
PageInfo:
type: object
properties:
page:
type: number
example: 1
pages:
type: number
example: 10
pageSize:
type: number
example: 10
results:
type: number
example: 100
securitySchemes: securitySchemes:
cookieAuth: cookieAuth:
@ -1847,6 +1862,45 @@ paths:
type: array type: array
items: items:
$ref: '#/components/schemas/TvResult' $ref: '#/components/schemas/TvResult'
/media:
get:
summary: Return all media
description: Returns all media (can be filtered and limited) in JSON format
tags:
- media
parameters:
- in: query
name: take
schema:
type: number
nullable: true
example: 20
- in: query
name: skip
schema:
type: number
nullable: true
example: 0
- in: query
name: filter
schema:
type: string
nullable: true
enum: [all, available, partial, processing, pending]
responses:
'200':
description: Returned media
content:
application/json:
schema:
type: object
properties:
pageInfo:
$ref: '#/components/schemas/PageInfo'
results:
type: array
items:
$ref: '#/components/schemas/MediaInfo'
security: security:
- cookieAuth: [] - cookieAuth: []

@ -151,7 +151,8 @@ export class MediaRequest {
}); });
const movie = await tmdb.getMovie({ movieId: this.media.tmdbId }); const movie = await tmdb.getMovie({ movieId: this.media.tmdbId });
await radarr.addMovie({ // Run this asynchronously so we don't wait for it on the UI side
radarr.addMovie({
profileId: radarrSettings.activeProfileId, profileId: radarrSettings.activeProfileId,
qualityProfileId: radarrSettings.activeProfileId, qualityProfileId: radarrSettings.activeProfileId,
rootFolderPath: radarrSettings.activeDirectory, rootFolderPath: radarrSettings.activeDirectory,
@ -212,7 +213,8 @@ export class MediaRequest {
throw new Error('Series was missing tvdb id'); throw new Error('Series was missing tvdb id');
} }
await sonarr.addSeries({ // Run this asynchronously so we don't wait for it on the UI side
sonarr.addSeries({
profileId: sonarrSettings.activeProfileId, profileId: sonarrSettings.activeProfileId,
rootFolderPath: sonarrSettings.activeDirectory, rootFolderPath: sonarrSettings.activeDirectory,
title: series.name, title: series.name,

@ -10,6 +10,7 @@ import discoverRoutes from './discover';
import requestRoutes from './request'; import requestRoutes from './request';
import movieRoutes from './movie'; import movieRoutes from './movie';
import tvRoutes from './tv'; import tvRoutes from './tv';
import mediaRoutes from './media';
const router = Router(); const router = Router();
@ -25,6 +26,7 @@ router.use('/discover', isAuthenticated(), discoverRoutes);
router.use('/request', isAuthenticated(), requestRoutes); router.use('/request', isAuthenticated(), requestRoutes);
router.use('/movie', isAuthenticated(), movieRoutes); router.use('/movie', isAuthenticated(), movieRoutes);
router.use('/tv', isAuthenticated(), tvRoutes); router.use('/tv', isAuthenticated(), tvRoutes);
router.use('/media', isAuthenticated(), mediaRoutes);
router.use('/auth', authRoutes); router.use('/auth', authRoutes);
router.get('/settings/public', (_req, res) => { router.get('/settings/public', (_req, res) => {

@ -0,0 +1,71 @@
import { Router } from 'express';
import { getRepository, FindOperator } from 'typeorm';
import Media from '../entity/Media';
import { MediaStatus } from '../constants/media';
export interface MediaResultsResponse {
pageInfo: {
pages: number;
page: number;
results: number;
pageSize: number;
};
results: Media[];
}
const mediaRoutes = Router();
mediaRoutes.get('/', async (req, res, next) => {
const mediaRepository = getRepository(Media);
const pageSize = Number(req.query.take) ?? 20;
const skip = Number(req.query.skip) ?? 0;
let statusFilter:
| MediaStatus
| FindOperator<MediaStatus>
| undefined = undefined;
switch (req.query.filter) {
case 'available':
statusFilter = MediaStatus.AVAILABLE;
break;
case 'partial':
statusFilter = MediaStatus.PARTIALLY_AVAILABLE;
break;
case 'processing':
statusFilter = MediaStatus.PROCESSING;
break;
case 'pending':
statusFilter = MediaStatus.PENDING;
break;
default:
statusFilter = undefined;
}
try {
const [media, mediaCount] = await mediaRepository.findAndCount({
order: {
id: 'DESC',
},
where: {
status: statusFilter,
},
take: pageSize,
skip,
});
return res.status(200).json({
pageInfo: {
pages: Math.ceil(mediaCount / pageSize),
pageSize,
results: mediaCount,
page: Math.ceil(skip / pageSize) + 1,
},
results: media,
} as MediaResultsResponse);
} catch (e) {
next({ status: 500, message: e.message });
}
});
export default mediaRoutes;

@ -20,7 +20,8 @@ requestRoutes.get('/', async (req, res, next) => {
id: 'DESC', id: 'DESC',
}, },
relations: ['media'], relations: ['media'],
take: 20, take: Number(req.query.take) ?? 20,
skip: Number(req.query.skip) ?? 0,
}) })
: await requestRepository.find({ : await requestRepository.find({
where: { requestedBy: { id: req.user?.id } }, where: { requestedBy: { id: req.user?.id } },
@ -28,7 +29,8 @@ requestRoutes.get('/', async (req, res, next) => {
order: { order: {
id: 'DESC', id: 'DESC',
}, },
take: 20, take: Number(req.query.limit) ?? 20,
skip: Number(req.query.skip) ?? 0,
}); });
return res.status(200).json(requests); return res.status(200).json(requests);

@ -6,13 +6,17 @@ import { MediaRequest } from '../../../server/entity/MediaRequest';
import RequestCard from '../TitleCard/RequestCard'; import RequestCard from '../TitleCard/RequestCard';
import Slider from '../Slider'; import Slider from '../Slider';
import Link from 'next/link'; import Link from 'next/link';
import { defineMessages, FormattedMessage } from 'react-intl'; import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import { LanguageContext } from '../../context/LanguageContext'; import { LanguageContext } from '../../context/LanguageContext';
import type Media from '../../../server/entity/Media';
import type { MediaResultsResponse } from '../../../server/routes/media';
const messages = defineMessages({ const messages = defineMessages({
recentrequests: 'Recent Requests', recentrequests: 'Recent Requests',
popularmovies: 'Popular Movies', popularmovies: 'Popular Movies',
populartv: 'Popular Series', populartv: 'Popular Series',
recentlyAdded: 'Recently Added',
nopending: 'No Pending Requests',
}); });
interface MovieDiscoverResult { interface MovieDiscoverResult {
@ -30,6 +34,7 @@ interface TvDiscoverResult {
} }
const Discover: React.FC = () => { const Discover: React.FC = () => {
const intl = useIntl();
const { locale } = useContext(LanguageContext); const { locale } = useContext(LanguageContext);
const { data: movieData, error: movieError } = useSWR<MovieDiscoverResult>( const { data: movieData, error: movieError } = useSWR<MovieDiscoverResult>(
`/api/v1/discover/movies?language=${locale}` `/api/v1/discover/movies?language=${locale}`
@ -38,12 +43,53 @@ const Discover: React.FC = () => {
`/api/v1/discover/tv?language=${locale}` `/api/v1/discover/tv?language=${locale}`
); );
const { data: media, error: mediaError } = useSWR<MediaResultsResponse>(
'/api/v1/media?filter=available&take=20'
);
const { data: requests, error: requestError } = useSWR<MediaRequest[]>( const { data: requests, error: requestError } = useSWR<MediaRequest[]>(
'/api/v1/request' '/api/v1/request'
); );
return ( return (
<> <>
<div className="md:flex md:items-center md:justify-between mb-4 mt-6">
<div className="flex-1 min-w-0">
<Link href="/recent">
<a className="inline-flex text-xl leading-7 text-cool-gray-300 hover:text-white sm:text-2xl sm:leading-9 sm:truncate items-center">
<span>
<FormattedMessage {...messages.recentlyAdded} />
</span>
<svg
className="w-6 h-6 ml-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</a>
</Link>
</div>
</div>
<Slider
sliderKey="requests"
isLoading={!media && !mediaError}
isEmpty={!!media && !mediaError && media.results.length === 0}
items={media?.results?.map((item) => (
<RequestCard
key={`media-slider-item-${item.id}`}
tmdbId={item.tmdbId}
type={item.mediaType}
/>
))}
/>
<div className="md:flex md:items-center md:justify-between mb-4 mt-6"> <div className="md:flex md:items-center md:justify-between mb-4 mt-6">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<Link href="/requests"> <Link href="/requests">
@ -80,6 +126,7 @@ const Discover: React.FC = () => {
type={request.media.mediaType} type={request.media.mediaType}
/> />
))} ))}
emptyMessage={intl.formatMessage(messages.nopending)}
/> />
<div className="md:flex md:items-center md:justify-between mb-4 mt-6"> <div className="md:flex md:items-center md:justify-between mb-4 mt-6">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">

@ -1,4 +1,4 @@
import React, { useCallback } from 'react'; import React, { useCallback, useState, useEffect } from 'react';
import Modal from '../Common/Modal'; import Modal from '../Common/Modal';
import { useUser } from '../../hooks/useUser'; import { useUser } from '../../hooks/useUser';
import { Permission } from '../../../server/lib/permissions'; import { Permission } from '../../../server/lib/permissions';
@ -35,6 +35,7 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
onUpdating, onUpdating,
...props ...props
}) => { }) => {
const [isUpdating, setIsUpdating] = useState(false);
const { addToast } = useToasts(); const { addToast } = useToasts();
const { data, error } = useSWR<MovieDetails>(`/api/v1/movie/${tmdbId}`, { const { data, error } = useSWR<MovieDetails>(`/api/v1/movie/${tmdbId}`, {
revalidateOnMount: true, revalidateOnMount: true,
@ -42,10 +43,14 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
const intl = useIntl(); const intl = useIntl();
const { user, hasPermission } = useUser(); const { user, hasPermission } = useUser();
const sendRequest = useCallback(async () => { useEffect(() => {
if (onUpdating) { if (onUpdating) {
onUpdating(true); onUpdating(isUpdating);
} }
}, [isUpdating, onUpdating]);
const sendRequest = useCallback(async () => {
setIsUpdating(true);
const response = await axios.post<MediaRequest>('/api/v1/request', { const response = await axios.post<MediaRequest>('/api/v1/request', {
mediaId: data?.id, mediaId: data?.id,
mediaType: 'movie', mediaType: 'movie',
@ -61,18 +66,14 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
</span>, </span>,
{ appearance: 'success', autoDismiss: true } { appearance: 'success', autoDismiss: true }
); );
if (onUpdating) { setIsUpdating(false);
onUpdating(false);
}
} }
}, [data, onComplete, onUpdating, addToast]); }, [data, onComplete, addToast]);
const activeRequest = data?.mediaInfo?.requests?.[0]; const activeRequest = data?.mediaInfo?.requests?.[0];
const cancelRequest = async () => { const cancelRequest = async () => {
if (onUpdating) { setIsUpdating(true);
onUpdating(true);
}
const response = await axios.delete<MediaRequest>( const response = await axios.delete<MediaRequest>(
`/api/v1/request/${activeRequest?.id}` `/api/v1/request/${activeRequest?.id}`
); );
@ -87,9 +88,7 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
</span>, </span>,
{ appearance: 'success', autoDismiss: true } { appearance: 'success', autoDismiss: true }
); );
if (onUpdating) { setIsUpdating(false);
onUpdating(false);
}
} }
}; };
@ -109,8 +108,9 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
backgroundClickable backgroundClickable
onCancel={onCancel} onCancel={onCancel}
onOk={isOwner ? () => cancelRequest() : undefined} onOk={isOwner ? () => cancelRequest() : undefined}
okDisabled={isUpdating}
title={`Pending request for ${data?.title}`} title={`Pending request for ${data?.title}`}
okText={'Cancel Request'} okText={isUpdating ? 'Cancelling...' : 'Cancel Request'}
okButtonType={'danger'} okButtonType={'danger'}
cancelText="Close" cancelText="Close"
iconSvg={<DownloadIcon className="w-6 h-6" />} iconSvg={<DownloadIcon className="w-6 h-6" />}
@ -128,8 +128,9 @@ const MovieRequestModal: React.FC<RequestModalProps> = ({
backgroundClickable backgroundClickable
onCancel={onCancel} onCancel={onCancel}
onOk={sendRequest} onOk={sendRequest}
okDisabled={isUpdating}
title={`Request ${data?.title}`} title={`Request ${data?.title}`}
okText={'Request'} okText={isUpdating ? 'Requesting...' : 'Request'}
okButtonType={'primary'} okButtonType={'primary'}
iconSvg={<DownloadIcon className="w-6 h-6" />} iconSvg={<DownloadIcon className="w-6 h-6" />}
{...props} {...props}

@ -2,12 +2,18 @@ import { debounce } from 'lodash';
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useSpring } from 'react-spring'; import { useSpring } from 'react-spring';
import TitleCard from '../TitleCard'; import TitleCard from '../TitleCard';
import { defineMessages, FormattedMessage } from 'react-intl';
const messages = defineMessages({
noresults: 'No Results',
});
interface SliderProps { interface SliderProps {
sliderKey: string; sliderKey: string;
items?: JSX.Element[]; items?: JSX.Element[];
isLoading: boolean; isLoading: boolean;
isEmpty: boolean; isEmpty: boolean;
emptyMessage?: string;
} }
enum Direction { enum Direction {
@ -20,6 +26,7 @@ const Slider: React.FC<SliderProps> = ({
items, items,
isLoading, isLoading,
isEmpty, isEmpty,
emptyMessage,
}) => { }) => {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const [scrollPos, setScrollPos] = useState({ isStart: true, isEnd: false }); const [scrollPos, setScrollPos] = useState({ isStart: true, isEnd: false });
@ -208,7 +215,13 @@ const Slider: React.FC<SliderProps> = ({
</div> </div>
))} ))}
{isEmpty && ( {isEmpty && (
<div className="text-center text-white mt-16 mb-16">No Results</div> <div className="text-center text-white mt-16 mb-16">
{emptyMessage ? (
emptyMessage
) : (
<FormattedMessage {...messages.noresults} />
)}
</div>
)} )}
</div> </div>
</div> </div>

Loading…
Cancel
Save