movie-web/src/stores/player/slices/source.ts

115 lines
2.7 KiB
TypeScript
Raw Normal View History

import { ScrapeMedia } from "@movie-web/providers";
2023-07-23 16:30:22 +02:00
import { MakeSlice } from "@/stores/player/slices/types";
import {
SourceQuality,
SourceSliceSource,
selectQuality,
} from "@/stores/player/utils/qualities";
2023-07-23 16:30:22 +02:00
import { ValuesOf } from "@/utils/typeguard";
export const playerStatus = {
IDLE: "idle",
SCRAPING: "scraping",
PLAYING: "playing",
} as const;
export type PlayerStatus = ValuesOf<typeof playerStatus>;
export interface PlayerMeta {
type: "movie" | "show";
title: string;
tmdbId: string;
imdbId?: string;
releaseYear: number;
episode?: {
number: number;
tmdbId: string;
title: string;
};
season?: {
number: number;
tmdbId: string;
title: string;
};
}
2023-07-23 16:30:22 +02:00
export interface SourceSlice {
status: PlayerStatus;
2023-08-15 19:55:48 +02:00
source: SourceSliceSource | null;
qualities: SourceQuality[];
currentQuality: SourceQuality | null;
meta: PlayerMeta | null;
2023-07-23 16:30:22 +02:00
setStatus(status: PlayerStatus): void;
setSource(stream: SourceSliceSource, startAt: number): void;
switchQuality(quality: SourceQuality): void;
setMeta(meta: PlayerMeta): void;
}
export function metaToScrapeMedia(meta: PlayerMeta): ScrapeMedia {
if (meta.type === "show") {
if (!meta.episode || !meta.season) throw new Error("missing show data");
return {
title: meta.title,
releaseYear: meta.releaseYear,
tmdbId: meta.tmdbId,
type: "show",
imdbId: meta.imdbId,
episode: meta.episode,
season: meta.season,
};
}
return {
title: meta.title,
releaseYear: meta.releaseYear,
tmdbId: meta.tmdbId,
type: "movie",
imdbId: meta.imdbId,
};
2023-07-23 16:30:22 +02:00
}
export const createSourceSlice: MakeSlice<SourceSlice> = (set, get) => ({
2023-07-23 16:30:22 +02:00
source: null,
qualities: [],
currentQuality: null,
2023-07-23 16:30:22 +02:00
status: playerStatus.IDLE,
meta: null,
2023-07-23 16:30:22 +02:00
setStatus(status: PlayerStatus) {
set((s) => {
s.status = status;
});
},
setMeta(meta) {
set((s) => {
s.meta = meta;
});
},
setSource(stream: SourceSliceSource, startAt: number) {
let qualities: string[] = [];
if (stream.type === "file") qualities = Object.keys(stream.qualities);
const store = get();
const loadableStream = selectQuality(stream);
2023-07-23 16:30:22 +02:00
set((s) => {
s.source = stream;
s.qualities = qualities as SourceQuality[];
s.currentQuality = loadableStream.quality;
2023-07-23 16:30:22 +02:00
});
store.display?.load(loadableStream.stream, startAt);
},
switchQuality(quality) {
const store = get();
if (!store.source) return;
if (store.source.type === "file") {
const selectedQuality = store.source.qualities[quality];
if (!selectedQuality) return;
set((s) => {
s.currentQuality = quality;
});
store.display?.load(selectedQuality, store.progress.time);
}
2023-07-23 16:30:22 +02:00
},
});