sudo-archive/src/views/Search.js

288 lines
12 KiB
JavaScript
Raw Normal View History

2021-07-13 22:31:37 +00:00
import React from 'react';
2021-08-02 13:15:24 +00:00
import { Helmet } from 'react-helmet';
2021-08-06 18:08:49 +00:00
import { Redirect, useHistory, useRouteMatch } from 'react-router-dom';
import { Arrow } from '../components/Arrow';
2021-07-20 10:20:56 +00:00
import { Card } from '../components/Card';
import { ErrorBanner } from '../components/ErrorBanner';
2021-08-06 18:08:49 +00:00
import { InputBox } from '../components/InputBox';
2021-07-20 10:20:56 +00:00
import { MovieRow } from '../components/MovieRow';
import { Progress } from '../components/Progress';
2021-08-06 18:08:49 +00:00
import { Title } from '../components/Title';
2021-07-20 10:20:56 +00:00
import { TypeSelector } from '../components/TypeSelector';
2021-08-06 18:08:49 +00:00
import { useMovie } from '../hooks/useMovie';
import { findContent, getEpisodes, getStreamUrl } from '../lib/index';
2021-07-13 22:31:37 +00:00
2021-07-20 10:20:56 +00:00
import './Search.css';
2021-07-13 22:31:37 +00:00
export function SearchView() {
const { navigate, setStreamUrl, setStreamData } = useMovie();
2021-08-02 12:15:18 +00:00
const history = useHistory();
const routeMatch = useRouteMatch('/:type');
const type = routeMatch?.params?.type;
const streamRouteMatch = useRouteMatch('/:type/:source/:title/:slug');
2021-07-14 22:09:42 +00:00
const maxSteps = 4;
2021-07-13 22:31:37 +00:00
const [options, setOptions] = React.useState([]);
const [progress, setProgress] = React.useState(0);
const [text, setText] = React.useState("");
const [failed, setFailed] = React.useState(false);
const [showingOptions, setShowingOptions] = React.useState(false);
2021-08-02 12:15:18 +00:00
const [errorStatus, setErrorStatus] = React.useState(false);
const [page, setPage] = React.useState('search');
const [continueWatching, setContinueWatching] = React.useState([])
2021-07-13 22:31:37 +00:00
const fail = (str) => {
setProgress(maxSteps);
setText(str)
setFailed(true)
}
async function getStream(title, slug, type, source, year) {
2021-07-13 22:31:37 +00:00
setStreamUrl("");
2021-07-14 22:09:42 +00:00
2021-07-13 22:31:37 +00:00
try {
setProgress(2);
2021-08-02 12:15:18 +00:00
setText(`Getting stream for "${title}"`);
2021-07-14 17:03:10 +00:00
2021-07-14 22:09:42 +00:00
let seasons = [];
let episodes = [];
if (type === "show") {
2021-07-20 22:49:33 +00:00
const data = await getEpisodes(slug, source);
2021-07-19 14:32:40 +00:00
seasons = data.seasons;
episodes = data.episodes;
2021-07-14 22:09:42 +00:00
}
let realUrl = '';
if (type === "movie") {
2021-07-20 22:49:33 +00:00
const { url } = await getStreamUrl(slug, type, source);
2021-07-22 20:11:53 +00:00
2021-07-14 22:09:42 +00:00
if (url === '') {
return fail(`Not found: ${title}`)
}
realUrl = url;
2021-07-14 17:03:10 +00:00
}
2021-07-13 22:31:37 +00:00
setProgress(maxSteps);
2021-07-14 22:09:42 +00:00
setStreamUrl(realUrl);
2021-07-13 22:31:37 +00:00
setStreamData({
title,
type,
2021-07-14 22:09:42 +00:00
seasons,
episodes,
2021-07-20 22:49:33 +00:00
slug,
source,
year
2021-07-13 22:31:37 +00:00
})
setText(`Streaming...`)
navigate("movie")
} catch (err) {
2021-07-20 10:20:56 +00:00
console.error(err);
2021-07-13 22:31:37 +00:00
fail("Failed to get stream")
}
}
2021-07-14 22:09:42 +00:00
async function searchMovie(query, contentType) {
2021-07-13 22:31:37 +00:00
setFailed(false);
2021-07-14 22:09:42 +00:00
setText(`Searching for ${contentType} "${query}"`);
2021-07-13 22:31:37 +00:00
setProgress(1)
setShowingOptions(false)
try {
2021-07-20 22:49:33 +00:00
const { options } = await findContent(query, contentType);
2021-07-13 22:31:37 +00:00
if (options.length === 0) {
2021-07-14 15:15:25 +00:00
return fail(`Could not find that ${contentType}`)
2021-07-13 22:31:37 +00:00
} else if (options.length > 1) {
setProgress(2);
2021-07-14 15:15:25 +00:00
setText(`Choose your ${contentType}`);
setOptions(options);
setShowingOptions(true);
2021-07-13 22:31:37 +00:00
return;
}
const { title, slug, type, source, year } = options[0];
2021-08-02 12:15:18 +00:00
history.push(`${routeMatch.url}/${source}/${title}/${slug}`);
getStream(title, slug, type, source, year);
2021-07-13 22:31:37 +00:00
} catch (err) {
2021-07-20 22:49:33 +00:00
console.error(err);
2021-07-14 15:15:25 +00:00
fail(`Failed to watch ${contentType}`)
2021-07-13 22:31:37 +00:00
}
}
2021-07-16 17:31:26 +00:00
React.useEffect(() => {
async function fetchHealth() {
2021-08-30 10:46:39 +00:00
await fetch(process.env.REACT_APP_CORS_PROXY_URL).catch(() => {
2021-07-16 17:31:26 +00:00
// Request failed; source likely offline
2021-08-02 12:15:18 +00:00
setErrorStatus(`Our content provider is currently offline, apologies.`)
2021-07-16 17:31:26 +00:00
})
}
fetchHealth()
2021-08-02 12:15:18 +00:00
}, []);
React.useEffect(() => {
if (streamRouteMatch) {
2021-08-02 13:45:10 +00:00
if (streamRouteMatch?.params.type === 'movie' || streamRouteMatch.params.type === 'show') getStream(streamRouteMatch.params.title, streamRouteMatch.params.slug, streamRouteMatch.params.type, streamRouteMatch.params.source);
else return setErrorStatus("Failed to find movie. Please try searching below.");
2021-08-02 12:15:18 +00:00
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(() => {
const progressData = JSON.parse(localStorage.getItem('video-progress') || "{}")
let newContinueWatching = []
2021-08-06 17:13:56 +00:00
Object.keys(progressData).forEach((source) => {
const all = [
...Object.entries(progressData[source]?.show ?? {}),
...Object.entries(progressData[source]?.movie ?? {})
2021-08-06 17:13:56 +00:00
];
for (const [slug, data] of all) {
for (let subselection of Object.values(data)) {
let entry = {
slug,
data: subselection,
type: subselection.show ? 'show' : 'movie',
percentageDone: Math.floor((subselection.currentlyAt / subselection.totalDuration) * 100),
source
}
2021-08-06 17:13:56 +00:00
2021-08-07 19:27:22 +00:00
// due to a constraint with incompatible localStorage data,
// we must quit here if episode and season data is not included
// in the show's data. watching the show will resolve.
if (!subselection.meta) continue;
if (entry.percentageDone < 90) {
newContinueWatching.push(entry)
2021-08-23 13:55:53 +00:00
// begin next episode logic
2021-08-07 08:55:39 +00:00
} else {
2021-08-07 10:04:35 +00:00
// we can't do next episode for movies!
2021-08-07 18:43:21 +00:00
if (!subselection.show) continue;
let newShow = {};
2021-08-07 19:51:16 +00:00
2021-08-07 10:04:35 +00:00
// if the current season has a next episode, load it
2021-08-07 08:55:39 +00:00
if (subselection.meta.episodes[subselection.show.season].includes(`${parseInt(subselection.show.episode) + 1}`)) {
2021-08-07 18:43:21 +00:00
newShow.season = subselection.show.season;
newShow.episode = `${parseInt(subselection.show.episode) + 1}`;
2021-08-07 08:55:39 +00:00
entry.percentageDone = 0;
2021-08-23 13:55:53 +00:00
// if the current season does not have a next epsiode, and the next season has a first episode, load that
} else if (subselection.meta.episodes?.[`${parseInt(subselection.show.season) + 1}`]?.[0]) {
2021-08-07 18:43:21 +00:00
newShow.season = `${parseInt(subselection.show.season) + 1}`;
newShow.episode = subselection.meta.episodes[`${parseInt(subselection.show.season) + 1}`][0];
2021-08-07 10:04:35 +00:00
entry.percentageDone = 0;
2021-08-23 13:55:53 +00:00
// the next episode does not exist
2021-08-07 08:55:39 +00:00
} else {
2021-08-07 18:43:21 +00:00
continue;
2021-08-07 08:55:39 +00:00
}
2021-08-23 13:55:53 +00:00
2021-08-07 18:43:21 +00:00
// assign the new episode and season data
entry.data.show = { ...newShow };
2021-08-23 13:55:53 +00:00
2021-08-07 18:43:21 +00:00
// if the next episode exists, continue. we don't want to end up with duplicate data.
let nextEpisode = progressData?.[source]?.show?.[slug]?.[`${entry.data.show.season}-${entry.data.show.episode}`];
if (nextEpisode) continue;
2021-08-07 08:55:39 +00:00
newContinueWatching.push(entry);
}
}
}
2021-08-06 17:13:56 +00:00
newContinueWatching = newContinueWatching.sort((a, b) => {
return b.data.updatedAt - a.data.updatedAt
2021-08-06 17:13:56 +00:00
});
setContinueWatching(newContinueWatching)
})
2021-08-06 18:08:49 +00:00
}, []);
if (!type || (type !== 'movie' && type !== 'show')) {
return <Redirect to="/movie" />
}
2021-07-16 17:31:26 +00:00
2021-07-13 22:31:37 +00:00
return (
<div className="cardView">
2021-08-02 13:15:24 +00:00
<Helmet>
2021-08-06 17:13:56 +00:00
<title>{type === 'movie' ? 'movies' : 'shows'} | movie-web</title>
2021-08-02 13:15:24 +00:00
</Helmet>
2021-08-02 13:22:13 +00:00
{/* Nav */}
<nav>
<a className={page === 'search' ? 'selected-link' : ''} onClick={() => setPage('search')} href>Search</a>
{continueWatching.length > 0 ?
<a className={page === 'watching' ? 'selected-link' : ''} onClick={() => setPage('watching')} href>Continue watching</a>
2021-08-07 08:55:39 +00:00
: ''}
</nav>
{/* Search */}
{page === 'search' ?
<React.Fragment>
<Card>
{errorStatus ? <ErrorBanner>{errorStatus}</ErrorBanner> : ''}
<Title accent="Because watching content legally is boring">
What do you wanna watch?
</Title>
<TypeSelector
setType={(type) => history.push(`/${type}`)}
choices={[
{ label: "Movie", value: "movie" },
{ label: "TV Show", value: "show" }
]}
noWrap={true}
selected={type}
/>
<InputBox placeholder={type === "movie" ? "Hamilton" : "Atypical"} onSubmit={(str) => searchMovie(str, type)} />
<Progress show={progress > 0} failed={failed} progress={progress} steps={maxSteps} text={text} />
</Card>
<Card show={showingOptions} doTransition>
<Title size="medium">
Whoops, there are a few {type}s like that
</Title>
{Object.entries(options.reduce((a, v) => {
if (!a[v.source]) a[v.source] = []
a[v.source].push(v)
return a;
}, {})).map(v => (
<div key={v[0]}>
<p className="source">{v[0]}</p>
{v[1].map((v, i) => (
<MovieRow key={i} title={v.title} slug={v.slug} type={v.type} year={v.year} source={v.source} onClick={() => {
history.push(`${routeMatch.url}/${v.source}/${v.title}/${v.slug}`);
setShowingOptions(false)
getStream(v.title, v.slug, v.type, v.source, v.year)
}} />
))}
</div>
2021-08-06 18:14:31 +00:00
))}
</Card>
</React.Fragment> : <React.Fragment />}
{/* Continue watching */}
{continueWatching.length > 0 && page === 'watching' ? <Card>
<Title>Continue watching</Title>
2021-07-13 22:31:37 +00:00
<Progress show={progress > 0} failed={failed} progress={progress} steps={maxSteps} text={text} />
2021-08-07 08:55:39 +00:00
{continueWatching?.map((v, i) => (
2021-08-23 13:55:53 +00:00
<MovieRow key={i} title={v.data.meta.title} slug={v.data.meta.slug} type={v.type} year={v.data.meta.year} source={v.source} place={v.data.show} percentage={v.percentageDone} deletable onClick={() => {
if (v.type === 'show') {
history.push(`/show/${v.source}/${v.data.meta.title}/${v.slug}/season/${v.data.show.season}/episode/${v.data.show.episode}`)
} else {
history.push(`/movie/${v.source}/${v.data.meta.title}/${v.slug}`)
}
setShowingOptions(false)
getStream(v.data.meta.title, v.data.meta.slug, v.type, v.source, v.data.meta.year)
}} />
))}
</Card> : <React.Fragment></React.Fragment>}
2021-07-13 23:17:34 +00:00
<div className="topRightCredits">
2021-08-02 12:44:54 +00:00
<a href="https://github.com/JamesHawkinss/movie-web" target="_blank" rel="noreferrer">Check it out on GitHub <Arrow /></a>
<br />
<a href="https://discord.gg/vXsRvye8BS" target="_blank" rel="noreferrer">Join the Discord <Arrow /></a>
2021-07-13 23:17:34 +00:00
</div>
2021-07-13 22:31:37 +00:00
</div>
)
}