new continue watching store

This commit is contained in:
mrjvs 2023-10-17 16:01:26 +02:00
parent accc13ab0e
commit aff39d1999
14 changed files with 130 additions and 148 deletions

View File

@ -1,22 +1,27 @@
import { SimpleCache } from "@/utils/cache"; import { SimpleCache } from "@/utils/cache";
import { MediaItem } from "@/utils/mediaTypes";
import { formatTMDBMeta, formatTMDBSearchResult, multiSearch } from "./tmdb"; import {
import { MWMediaMeta, MWQuery } from "./types/mw"; formatTMDBMetaToMediaItem,
formatTMDBSearchResult,
multiSearch,
} from "./tmdb";
import { MWQuery } from "./types/mw";
const cache = new SimpleCache<MWQuery, MWMediaMeta[]>(); const cache = new SimpleCache<MWQuery, MediaItem[]>();
cache.setCompare((a, b) => { cache.setCompare((a, b) => {
return a.searchQuery.trim() === b.searchQuery.trim(); return a.searchQuery.trim() === b.searchQuery.trim();
}); });
cache.initialize(); cache.initialize();
export async function searchForMedia(query: MWQuery): Promise<MWMediaMeta[]> { export async function searchForMedia(query: MWQuery): Promise<MediaItem[]> {
if (cache.has(query)) return cache.get(query) as MWMediaMeta[]; if (cache.has(query)) return cache.get(query) as MediaItem[];
const { searchQuery } = query; const { searchQuery } = query;
const data = await multiSearch(searchQuery); const data = await multiSearch(searchQuery);
const results = data.map((v) => { const results = data.map((v) => {
const formattedResult = formatTMDBSearchResult(v, v.media_type); const formattedResult = formatTMDBSearchResult(v, v.media_type);
return formatTMDBMeta(formattedResult); return formatTMDBMetaToMediaItem(formattedResult);
}); });
cache.set(query, results, 3600); // cache results for 1 hour cache.set(query, results, 3600); // cache results for 1 hour

View File

@ -1,6 +1,7 @@
import slugify from "slugify"; import slugify from "slugify";
import { conf } from "@/setup/config"; import { conf } from "@/setup/config";
import { MediaItem } from "@/utils/mediaTypes";
import { MWMediaMeta, MWMediaType, MWSeasonMeta } from "./types/mw"; import { MWMediaMeta, MWMediaType, MWSeasonMeta } from "./types/mw";
import { import {
@ -24,12 +25,26 @@ export function mediaTypeToTMDB(type: MWMediaType): TMDBContentTypes {
throw new Error("unsupported type"); throw new Error("unsupported type");
} }
export function mediaItemTypeToMediaType(type: MediaItem["type"]): MWMediaType {
if (type === "movie") return MWMediaType.MOVIE;
if (type === "show") return MWMediaType.SERIES;
throw new Error("unsupported type");
}
export function TMDBMediaToMediaType(type: TMDBContentTypes): MWMediaType { export function TMDBMediaToMediaType(type: TMDBContentTypes): MWMediaType {
if (type === TMDBContentTypes.MOVIE) return MWMediaType.MOVIE; if (type === TMDBContentTypes.MOVIE) return MWMediaType.MOVIE;
if (type === TMDBContentTypes.TV) return MWMediaType.SERIES; if (type === TMDBContentTypes.TV) return MWMediaType.SERIES;
throw new Error("unsupported type"); throw new Error("unsupported type");
} }
export function TMDBMediaToMediaItemType(
type: TMDBContentTypes
): MediaItem["type"] {
if (type === TMDBContentTypes.MOVIE) return "movie";
if (type === TMDBContentTypes.TV) return "show";
throw new Error("unsupported type");
}
export function formatTMDBMeta( export function formatTMDBMeta(
media: TMDBMediaResult, media: TMDBMediaResult,
season?: TMDBSeasonMetaResult season?: TMDBSeasonMetaResult
@ -72,6 +87,18 @@ export function formatTMDBMeta(
}; };
} }
export function formatTMDBMetaToMediaItem(media: TMDBMediaResult): MediaItem {
const type = TMDBMediaToMediaItemType(media.object_type);
return {
title: media.title,
id: media.id.toString(),
year: media.original_release_year ?? 0,
poster: media.poster,
type,
};
}
export function TMDBIdToUrlId( export function TMDBIdToUrlId(
type: MWMediaType, type: MWMediaType,
tmdbId: string, tmdbId: string,
@ -89,6 +116,14 @@ export function TMDBMediaToId(media: MWMediaMeta): string {
return TMDBIdToUrlId(media.type, media.id, media.title); return TMDBIdToUrlId(media.type, media.id, media.title);
} }
export function mediaItemToId(media: MediaItem): string {
return TMDBIdToUrlId(
mediaItemTypeToMediaType(media.type),
media.id,
media.title
);
}
export function decodeTMDBId( export function decodeTMDBId(
paramId: string paramId: string
): { id: string; type: MWMediaType } | null { ): { id: string; type: MWMediaType } | null {

View File

@ -2,16 +2,16 @@ import c from "classnames";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { TMDBMediaToId } from "@/backend/metadata/tmdb"; import { mediaItemToId } from "@/backend/metadata/tmdb";
import { MWMediaMeta } from "@/backend/metadata/types/mw";
import { DotList } from "@/components/text/DotList"; import { DotList } from "@/components/text/DotList";
import { Flare } from "@/components/utils/Flare"; import { Flare } from "@/components/utils/Flare";
import { MediaItem } from "@/utils/mediaTypes";
import { IconPatch } from "../buttons/IconPatch"; import { IconPatch } from "../buttons/IconPatch";
import { Icons } from "../Icon"; import { Icons } from "../Icon";
export interface MediaCardProps { export interface MediaCardProps {
media: MWMediaMeta; media: MediaItem;
linkable?: boolean; linkable?: boolean;
series?: { series?: {
episode: number; episode: number;
@ -38,7 +38,7 @@ function MediaCardContent({
const canLink = linkable && !closable; const canLink = linkable && !closable;
const dotListContent = [t(`media.${media.type}`)]; const dotListContent = [t(`media.${media.type}`)];
if (media.year) dotListContent.push(media.year); if (media.year) dotListContent.push(media.year.toFixed());
return ( return (
<Flare.Base <Flare.Base
@ -141,7 +141,7 @@ export function MediaCard(props: MediaCardProps) {
const canLink = props.linkable && !props.closable; const canLink = props.linkable && !props.closable;
let link = canLink let link = canLink
? `/media/${encodeURIComponent(TMDBMediaToId(props.media))}` ? `/media/${encodeURIComponent(mediaItemToId(props.media))}`
: "#"; : "#";
if (canLink && props.series) { if (canLink && props.series) {
if (props.series.season === 0 && !props.series.episodeId) { if (props.series.season === 0 && !props.series.episodeId) {

View File

@ -1,44 +1,49 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { MWMediaMeta } from "@/backend/metadata/types/mw"; import { ProgressMediaItem, useProgressStore } from "@/stores/progress";
import { useWatchedContext } from "@/state/watched"; import { MediaItem } from "@/utils/mediaTypes";
import { MediaCard } from "./MediaCard"; import { MediaCard } from "./MediaCard";
export interface WatchedMediaCardProps { export interface WatchedMediaCardProps {
media: MWMediaMeta; media: MediaItem;
closable?: boolean; closable?: boolean;
onClose?: () => void; onClose?: () => void;
} }
function formatSeries( function formatSeries(obj: ProgressMediaItem | undefined) {
obj:
| { episodeId: string; seasonId: string; episode: number; season: number }
| undefined
) {
if (!obj) return undefined; if (!obj) return undefined;
if (obj.type !== "show") return;
// TODO only show latest episode watched
const ep = Object.values(obj.episodes)[0];
const season = obj.seasons[ep?.seasonId];
if (!ep || !season) return;
return { return {
season: obj.season, season: season.number,
episode: obj.episode, episode: ep.number,
episodeId: obj.episodeId, episodeId: ep.id,
seasonId: obj.seasonId, seasonId: ep.seasonId,
progress: ep.progress,
}; };
} }
export function WatchedMediaCard(props: WatchedMediaCardProps) { export function WatchedMediaCard(props: WatchedMediaCardProps) {
const { watched } = useWatchedContext(); const progressItems = useProgressStore((s) => s.items);
const watchedMedia = useMemo(() => { const item = useMemo(() => {
return watched.items return progressItems[props.media.id];
.sort((a, b) => b.watchedAt - a.watchedAt) }, [progressItems, props.media]);
.find((v) => v.item.meta.id === props.media.id); const series = useMemo(() => formatSeries(item), [item]);
}, [watched, props.media]); const progress = item?.progress ?? series?.progress;
const percentage = progress
? (progress.watched / progress.duration) * 100
: undefined;
return ( return (
<MediaCard <MediaCard
media={props.media} media={props.media}
series={formatSeries(watchedMedia?.item?.series)} series={series}
linkable linkable
percentage={watchedMedia?.percentage} percentage={percentage}
onClose={props.onClose} onClose={props.onClose}
closable={props.closable} closable={props.closable}
/> />

View File

@ -23,6 +23,7 @@ export function usePlayerMeta() {
type: "show", type: "show",
releaseYear: +(m.meta.year ?? 0), releaseYear: +(m.meta.year ?? 0),
title: m.meta.title, title: m.meta.title,
poster: m.meta.poster,
tmdbId: m.tmdbId ?? "", tmdbId: m.tmdbId ?? "",
imdbId: m.imdbId, imdbId: m.imdbId,
episode: { episode: {
@ -41,6 +42,7 @@ export function usePlayerMeta() {
type: "movie", type: "movie",
releaseYear: +(m.meta.year ?? 0), releaseYear: +(m.meta.year ?? 0),
title: m.meta.title, title: m.meta.title,
poster: m.meta.poster,
tmdbId: m.tmdbId ?? "", tmdbId: m.tmdbId ?? "",
imdbId: m.imdbId, imdbId: m.imdbId,
}; };

View File

@ -1,88 +0,0 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { searchForMedia } from "@/backend/metadata/search";
import { MWMediaMeta, MWQuery } from "@/backend/metadata/types/mw";
import { IconPatch } from "@/components/buttons/IconPatch";
import { Icons } from "@/components/Icon";
import { SectionHeading } from "@/components/layout/SectionHeading";
import { MediaGrid } from "@/components/media/MediaGrid";
import { WatchedMediaCard } from "@/components/media/WatchedMediaCard";
import { useLoading } from "@/hooks/useLoading";
import { SearchLoadingPart } from "@/pages/parts/search/SearchLoadingPart";
function SearchSuffix(props: { failed?: boolean; results?: number }) {
const { t } = useTranslation();
const icon: Icons = props.failed ? Icons.WARNING : Icons.EYE_SLASH;
return (
<div className="mb-24 mt-40 flex flex-col items-center justify-center space-y-3 text-center">
<IconPatch
icon={icon}
className={`text-xl ${props.failed ? "text-red-400" : "text-bink-600"}`}
/>
{/* standard suffix */}
{!props.failed ? (
<div>
{(props.results ?? 0) > 0 ? (
<p>{t("search.allResults")}</p>
) : (
<p>{t("search.noResults")}</p>
)}
</div>
) : null}
{/* Error result */}
{props.failed ? (
<div>
<p>{t("search.allFailed")}</p>
</div>
) : null}
</div>
);
}
export function SearchResultsView({ searchQuery }: { searchQuery: MWQuery }) {
const { t } = useTranslation();
const [results, setResults] = useState<MWMediaMeta[]>([]);
const [runSearchQuery, loading, error] = useLoading((query: MWQuery) =>
searchForMedia(query)
);
useEffect(() => {
async function runSearch(query: MWQuery) {
const searchResults = await runSearchQuery(query);
if (!searchResults) return;
setResults(searchResults);
}
if (searchQuery.searchQuery !== "") runSearch(searchQuery);
}, [searchQuery, runSearchQuery]);
if (loading) return <SearchLoadingPart />;
if (error) return <SearchSuffix failed />;
if (!results) return null;
return (
<div>
{results.length > 0 ? (
<div>
<SectionHeading
title={t("search.headingTitle") || "Search results"}
icon={Icons.SEARCH}
/>
<MediaGrid>
{results.map((v) => (
<WatchedMediaCard key={v.id.toString()} media={v} />
))}
</MediaGrid>
</div>
) : null}
<SearchSuffix results={results.length} />
</div>
);
}

View File

@ -45,12 +45,13 @@ export function BookmarksPart() {
</SectionHeading> </SectionHeading>
<MediaGrid ref={gridRef}> <MediaGrid ref={gridRef}>
{bookmarksSorted.map((v) => ( {bookmarksSorted.map((v) => (
<WatchedMediaCard <div key={v.id}>Bookmark</div>
key={v.id} // <WatchedMediaCard
media={v} // key={v.id}
closable={editing} // media={v}
onClose={() => setItemBookmark(v, false)} // closable={editing}
/> // onClose={() => setItemBookmark(v, false)}
// />
))} ))}
</MediaGrid> </MediaGrid>
</div> </div>

View File

@ -1,5 +1,5 @@
import { useAutoAnimate } from "@formkit/auto-animate/react"; import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useState } from "react"; import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { EditButton } from "@/components/buttons/EditButton"; import { EditButton } from "@/components/buttons/EditButton";
@ -7,25 +7,29 @@ import { Icons } from "@/components/Icon";
import { SectionHeading } from "@/components/layout/SectionHeading"; import { SectionHeading } from "@/components/layout/SectionHeading";
import { MediaGrid } from "@/components/media/MediaGrid"; import { MediaGrid } from "@/components/media/MediaGrid";
import { WatchedMediaCard } from "@/components/media/WatchedMediaCard"; import { WatchedMediaCard } from "@/components/media/WatchedMediaCard";
import { import { useProgressStore } from "@/stores/progress";
getIfBookmarkedFromPortable, import { MediaItem } from "@/utils/mediaTypes";
useBookmarkContext,
} from "@/state/bookmark";
import { useWatchedContext } from "@/state/watched";
export function WatchingPart() { export function WatchingPart() {
const { t } = useTranslation(); const { t } = useTranslation();
const { getFilteredBookmarks } = useBookmarkContext(); const progressItems = useProgressStore((s) => s.items);
const { getFilteredWatched, removeProgress } = useWatchedContext(); const removeItem = useProgressStore((s) => s.removeItem);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [gridRef] = useAutoAnimate<HTMLDivElement>(); const [gridRef] = useAutoAnimate<HTMLDivElement>();
const bookmarks = getFilteredBookmarks(); const sortedProgressItems = useMemo(() => {
const watchedItems = getFilteredWatched().filter( const output: MediaItem[] = [];
(v) => !getIfBookmarkedFromPortable(bookmarks, v.item.meta) Object.entries(progressItems).forEach((entry) => {
); output.push({
id: entry[0],
...entry[1],
});
});
// TODO sort on last modified date
return output;
}, [progressItems]);
if (watchedItems.length === 0) return null; if (sortedProgressItems.length === 0) return null;
return ( return (
<div> <div>
@ -36,12 +40,12 @@ export function WatchingPart() {
<EditButton editing={editing} onEdit={setEditing} /> <EditButton editing={editing} onEdit={setEditing} />
</SectionHeading> </SectionHeading>
<MediaGrid ref={gridRef}> <MediaGrid ref={gridRef}>
{watchedItems.map((v) => ( {sortedProgressItems.map((v) => (
<WatchedMediaCard <WatchedMediaCard
key={v.item.meta.id} key={v.id}
media={v.item.meta} media={v}
closable={editing} closable={editing}
onClose={() => removeProgress(v.item.meta.id)} onClose={() => removeItem(v.id)}
/> />
))} ))}
</MediaGrid> </MediaGrid>

View File

@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { searchForMedia } from "@/backend/metadata/search"; import { searchForMedia } from "@/backend/metadata/search";
import { MWMediaMeta, MWQuery } from "@/backend/metadata/types/mw"; import { MWQuery } from "@/backend/metadata/types/mw";
import { IconPatch } from "@/components/buttons/IconPatch"; import { IconPatch } from "@/components/buttons/IconPatch";
import { Icons } from "@/components/Icon"; import { Icons } from "@/components/Icon";
import { SectionHeading } from "@/components/layout/SectionHeading"; import { SectionHeading } from "@/components/layout/SectionHeading";
@ -10,6 +10,7 @@ import { MediaGrid } from "@/components/media/MediaGrid";
import { WatchedMediaCard } from "@/components/media/WatchedMediaCard"; import { WatchedMediaCard } from "@/components/media/WatchedMediaCard";
import { useLoading } from "@/hooks/useLoading"; import { useLoading } from "@/hooks/useLoading";
import { SearchLoadingPart } from "@/pages/parts/search/SearchLoadingPart"; import { SearchLoadingPart } from "@/pages/parts/search/SearchLoadingPart";
import { MediaItem } from "@/utils/mediaTypes";
function SearchSuffix(props: { failed?: boolean; results?: number }) { function SearchSuffix(props: { failed?: boolean; results?: number }) {
const { t } = useTranslation(); const { t } = useTranslation();
@ -47,7 +48,7 @@ function SearchSuffix(props: { failed?: boolean; results?: number }) {
export function SearchListPart({ searchQuery }: { searchQuery: string }) { export function SearchListPart({ searchQuery }: { searchQuery: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [results, setResults] = useState<MWMediaMeta[]>([]); const [results, setResults] = useState<MediaItem[]>([]);
const [runSearchQuery, loading, error] = useLoading((query: MWQuery) => const [runSearchQuery, loading, error] = useLoading((query: MWQuery) =>
searchForMedia(query) searchForMedia(query)
); );

View File

@ -15,7 +15,7 @@
}, },
"media": { "media": {
"movie": "Movie", "movie": "Movie",
"series": "Series", "show": "Show",
"stopEditing": "Stop editing", "stopEditing": "Stop editing",
"errors": { "errors": {
"genericTitle": "Whoops, it broke!", "genericTitle": "Whoops, it broke!",

View File

@ -1,5 +1,6 @@
import { DetailedMeta, getMetaFromId } from "@/backend/metadata/getmeta"; import { DetailedMeta, getMetaFromId } from "@/backend/metadata/getmeta";
import { searchForMedia } from "@/backend/metadata/search"; import { searchForMedia } from "@/backend/metadata/search";
import { mediaItemTypeToMediaType } from "@/backend/metadata/tmdb";
import { MWMediaMeta, MWMediaType } from "@/backend/metadata/types/mw"; import { MWMediaMeta, MWMediaType } from "@/backend/metadata/types/mw";
import { compareTitle } from "@/utils/titleMatch"; import { compareTitle } from "@/utils/titleMatch";
@ -69,8 +70,8 @@ async function getMetas(
if (!item) continue; if (!item) continue;
let keys: (string | null)[][] = [["0", "0"]]; let keys: (string | null)[][] = [["0", "0"]];
if (item.data.type === "series") { if (item.data.type === "show") {
const meta = await getMetaFromId(item.data.type, item.data.id); const meta = await getMetaFromId(MWMediaType.SERIES, item.data.id);
if (!meta || !meta?.meta.seasons) return; if (!meta || !meta?.meta.seasons) return;
const seasonNumbers = [ const seasonNumbers = [
...new Set( ...new Set(
@ -95,7 +96,7 @@ async function getMetas(
keys.map(async ([key, id]) => { keys.map(async ([key, id]) => {
if (!key) return; if (!key) return;
mediaMetas[item.id][key] = await getMetaFromId( mediaMetas[item.id][key] = await getMetaFromId(
item.data.type, mediaItemTypeToMediaType(item.data.type),
item.data.id, item.data.id,
id === "0" || id === null ? undefined : id id === "0" || id === null ? undefined : id
); );

View File

@ -22,6 +22,7 @@ export interface PlayerMeta {
tmdbId: string; tmdbId: string;
imdbId?: string; imdbId?: string;
releaseYear: number; releaseYear: number;
poster?: string;
episode?: { episode?: {
number: number; number: number;
tmdbId: string; tmdbId: string;

View File

@ -26,6 +26,7 @@ export interface ProgressEpisodeItem {
export interface ProgressMediaItem { export interface ProgressMediaItem {
title: string; title: string;
year: number; year: number;
poster?: string;
type: "show" | "movie"; type: "show" | "movie";
progress?: ProgressItem; progress?: ProgressItem;
seasons: Record<string, ProgressSeasonItem>; seasons: Record<string, ProgressSeasonItem>;
@ -40,6 +41,7 @@ export interface UpdateItemOptions {
export interface ProgressStore { export interface ProgressStore {
items: Record<string, ProgressMediaItem>; items: Record<string, ProgressMediaItem>;
updateItem(ops: UpdateItemOptions): void; updateItem(ops: UpdateItemOptions): void;
removeItem(id: string): void;
} }
// TODO add migration from previous progress store // TODO add migration from previous progress store
@ -47,6 +49,11 @@ export const useProgressStore = create(
persist( persist(
immer<ProgressStore>((set) => ({ immer<ProgressStore>((set) => ({
items: {}, items: {},
removeItem(id) {
set((s) => {
delete s.items[id];
});
},
updateItem({ meta, progress }) { updateItem({ meta, progress }) {
set((s) => { set((s) => {
if (!s.items[meta.tmdbId]) if (!s.items[meta.tmdbId])
@ -56,6 +63,7 @@ export const useProgressStore = create(
seasons: {}, seasons: {},
title: meta.title, title: meta.title,
year: meta.releaseYear, year: meta.releaseYear,
poster: meta.poster,
}; };
const item = s.items[meta.tmdbId]; const item = s.items[meta.tmdbId];
if (meta.type === "movie") { if (meta.type === "movie") {

7
src/utils/mediaTypes.ts Normal file
View File

@ -0,0 +1,7 @@
export interface MediaItem {
id: string;
title: string;
year: number;
poster?: string;
type: "show" | "movie";
}