mirror of
https://github.com/streamyfin/streamyfin.git
synced 2026-04-01 06:31:53 +01:00
refactor: remove unused code and simplify implementations
Removes extensive dead code including unused components, utilities, and augmentations that were no longer referenced in the codebase. Simplifies play settings logic by removing complex stream ranking algorithm in favor of direct previous index matching for audio and subtitle selections. Removes aspectRatio prop from video player as it was set to a constant "default" value and never changed. Inlines POSTER_CAROUSEL_HEIGHT constant directly where used instead of importing from centralized constants file. Eliminates unused features including image color extraction for TV platforms, M3U8 subtitle parsing, and various Jellyfin API helpers that were no longer needed. Cleans up credential management by making internal helper functions private that should not be exposed to external consumers.
This commit is contained in:
@@ -1,18 +0,0 @@
|
||||
/**
|
||||
* Convert bits to megabits or gigabits
|
||||
*
|
||||
* Return nice looking string
|
||||
* If under 1000Mb, return XXXMB, else return X.XGB
|
||||
*/
|
||||
|
||||
export function convertBitsToMegabitsOrGigabits(bits?: number | null): string {
|
||||
if (!bits) return "0MB";
|
||||
|
||||
const megabits = bits / 1000000;
|
||||
|
||||
if (megabits < 1000) {
|
||||
return `${Math.round(megabits)}MB`;
|
||||
}
|
||||
const gigabits = megabits / 1000;
|
||||
return `${gigabits.toFixed(1)}GB`;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import {
|
||||
BaseItemKind,
|
||||
CollectionType,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
|
||||
/**
|
||||
* Converts a ColletionType to a BaseItemKind (also called ItemType)
|
||||
*
|
||||
* CollectionTypes
|
||||
* readonly Unknown: "unknown";
|
||||
readonly Movies: "movies";
|
||||
readonly Tvshows: "tvshows";
|
||||
readonly Trailers: "trailers";
|
||||
readonly Homevideos: "homevideos";
|
||||
readonly Boxsets: "boxsets";
|
||||
readonly Books: "books";
|
||||
readonly Photos: "photos";
|
||||
readonly Livetv: "livetv";
|
||||
readonly Playlists: "playlists";
|
||||
readonly Folders: "folders";
|
||||
*/
|
||||
export const colletionTypeToItemType = (
|
||||
collectionType?: CollectionType | null,
|
||||
): BaseItemKind | undefined => {
|
||||
if (!collectionType) return undefined;
|
||||
|
||||
switch (collectionType) {
|
||||
case CollectionType.Movies:
|
||||
return BaseItemKind.Movie;
|
||||
case CollectionType.Tvshows:
|
||||
return BaseItemKind.Series;
|
||||
case CollectionType.Homevideos:
|
||||
return BaseItemKind.Video;
|
||||
case CollectionType.Books:
|
||||
return BaseItemKind.Book;
|
||||
case CollectionType.Playlists:
|
||||
return BaseItemKind.Playlist;
|
||||
case CollectionType.Folders:
|
||||
return BaseItemKind.Folder;
|
||||
case CollectionType.Photos:
|
||||
return BaseItemKind.Photo;
|
||||
case CollectionType.Trailers:
|
||||
return BaseItemKind.Trailer;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
@@ -1,56 +0,0 @@
|
||||
import axios from "axios";
|
||||
|
||||
export interface SubtitleTrack {
|
||||
index: number;
|
||||
name: string;
|
||||
uri: string;
|
||||
language: string;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
autoSelect: boolean;
|
||||
}
|
||||
|
||||
export async function parseM3U8ForSubtitles(
|
||||
url: string,
|
||||
): Promise<SubtitleTrack[]> {
|
||||
try {
|
||||
const response = await axios.get(url, { responseType: "text" });
|
||||
const lines = response.data.split(/\r?\n/);
|
||||
const subtitleTracks: SubtitleTrack[] = [];
|
||||
let index = 0;
|
||||
|
||||
lines.forEach((line: string) => {
|
||||
if (line.startsWith("#EXT-X-MEDIA:TYPE=SUBTITLES")) {
|
||||
const attributes = parseAttributes(line);
|
||||
const track: SubtitleTrack = {
|
||||
index: index++,
|
||||
name: attributes.NAME || "",
|
||||
uri: attributes.URI || "",
|
||||
language: attributes.LANGUAGE || "",
|
||||
default: attributes.DEFAULT === "YES",
|
||||
forced: attributes.FORCED === "YES",
|
||||
autoSelect: attributes.AUTOSELECT === "YES",
|
||||
};
|
||||
subtitleTracks.push(track);
|
||||
}
|
||||
});
|
||||
|
||||
return subtitleTracks;
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch or parse the M3U8 file:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function parseAttributes(line: string): { [key: string]: string } {
|
||||
const attributes: { [key: string]: string } = {};
|
||||
const regex = /([A-Z-]+)=(?:"([^"]*)"|([^,]*))/g;
|
||||
|
||||
for (const match of line.matchAll(regex)) {
|
||||
const key = match[1];
|
||||
const value = match[2] ?? match[3]; // quoted or unquoted
|
||||
attributes[key] = value;
|
||||
}
|
||||
|
||||
return attributes;
|
||||
}
|
||||
@@ -15,11 +15,6 @@ import type {
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { BITRATES } from "@/components/BitrateSelector";
|
||||
import { type Settings } from "../atoms/settings";
|
||||
import {
|
||||
AudioStreamRanker,
|
||||
StreamRanker,
|
||||
SubtitleStreamRanker,
|
||||
} from "../streamRanker";
|
||||
|
||||
export interface PlaySettings {
|
||||
item: BaseItemDto;
|
||||
@@ -54,42 +49,27 @@ export function getDefaultPlaySettings(
|
||||
}
|
||||
|
||||
const mediaSource = item.MediaSources?.[0];
|
||||
const streams = mediaSource?.MediaStreams ?? [];
|
||||
const _streams = mediaSource?.MediaStreams ?? [];
|
||||
|
||||
// Start with media source defaults
|
||||
let audioIndex = mediaSource?.DefaultAudioStreamIndex;
|
||||
let subtitleIndex = mediaSource?.DefaultSubtitleStreamIndex ?? -1;
|
||||
|
||||
// Try to match previous selections (sequential play)
|
||||
if (previous?.indexes && previous?.source && settings) {
|
||||
// Simplified: just use previous indexes if available
|
||||
if (previous?.indexes && settings) {
|
||||
if (
|
||||
settings.rememberSubtitleSelections &&
|
||||
previous.indexes.subtitleIndex !== undefined
|
||||
) {
|
||||
const ranker = new StreamRanker(new SubtitleStreamRanker());
|
||||
const result = { DefaultSubtitleStreamIndex: subtitleIndex };
|
||||
ranker.rankStream(
|
||||
previous.indexes.subtitleIndex,
|
||||
previous.source,
|
||||
streams,
|
||||
result,
|
||||
);
|
||||
subtitleIndex = result.DefaultSubtitleStreamIndex;
|
||||
subtitleIndex = previous.indexes.subtitleIndex;
|
||||
}
|
||||
|
||||
if (
|
||||
settings.rememberAudioSelections &&
|
||||
previous.indexes.audioIndex !== undefined
|
||||
) {
|
||||
const ranker = new StreamRanker(new AudioStreamRanker());
|
||||
const result = { DefaultAudioStreamIndex: audioIndex };
|
||||
ranker.rankStream(
|
||||
previous.indexes.audioIndex,
|
||||
previous.source,
|
||||
streams,
|
||||
result,
|
||||
);
|
||||
audioIndex = result.DefaultAudioStreamIndex;
|
||||
audioIndex = previous.indexes.audioIndex;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import type { Settings } from "../../atoms/settings";
|
||||
import { generateDeviceProfile } from "../../profiles/native";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface PostCapabilitiesParams {
|
||||
api: Api | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
sessionId: string | null | undefined;
|
||||
deviceProfile: Settings["deviceProfile"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a media item as not played for a specific user.
|
||||
*
|
||||
* @param params - The parameters for marking an item as not played
|
||||
* @returns A promise that resolves to true if the operation was successful, false otherwise
|
||||
*/
|
||||
export const postCapabilities = async ({
|
||||
api,
|
||||
itemId,
|
||||
sessionId,
|
||||
}: PostCapabilitiesParams): Promise<AxiosResponse> => {
|
||||
if (!api || !itemId || !sessionId) {
|
||||
throw new Error("Missing parameters for marking item as not played");
|
||||
}
|
||||
|
||||
try {
|
||||
const d = api.axiosInstance.post(
|
||||
`${api.basePath}/Sessions/Capabilities/Full`,
|
||||
{
|
||||
playableMediaTypes: ["Audio", "Video"],
|
||||
supportedCommands: [
|
||||
"PlayState",
|
||||
"Play",
|
||||
"ToggleFullscreen",
|
||||
"DisplayMessage",
|
||||
"Mute",
|
||||
"Unmute",
|
||||
"SetVolume",
|
||||
"ToggleMute",
|
||||
],
|
||||
supportsMediaControl: true,
|
||||
id: sessionId,
|
||||
DeviceProfile: generateDeviceProfile(),
|
||||
},
|
||||
{
|
||||
headers: getAuthHeaders(api),
|
||||
},
|
||||
);
|
||||
return d;
|
||||
} catch (_error) {
|
||||
throw new Error("Failed to mark as not played");
|
||||
}
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface NextUpParams {
|
||||
itemId?: string | null;
|
||||
userId?: string | null;
|
||||
api?: Api | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next up episodes for a series or all series for a user.
|
||||
*
|
||||
* @param params - The parameters for fetching next up episodes
|
||||
* @returns A promise that resolves to an array of BaseItemDto representing the next up episodes
|
||||
*/
|
||||
export const nextUp = async ({
|
||||
itemId,
|
||||
userId,
|
||||
api,
|
||||
}: NextUpParams): Promise<BaseItemDto[]> => {
|
||||
if (!userId || !api) {
|
||||
console.error("Invalid parameters for nextUp: missing userId or api");
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.get<{ Items: BaseItemDto[] }>(
|
||||
`${api.basePath}/Shows/NextUp`,
|
||||
{
|
||||
params: {
|
||||
SeriesId: itemId || undefined,
|
||||
UserId: userId,
|
||||
Fields: "MediaSourceCount",
|
||||
},
|
||||
headers: getAuthHeaders(api),
|
||||
},
|
||||
);
|
||||
|
||||
return response.data.Items;
|
||||
} catch (_error) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
|
||||
/**
|
||||
* Retrieves an item by its ID from the API.
|
||||
*
|
||||
* @param api - The Jellyfin API instance.
|
||||
* @param itemId - The ID of the item to retrieve.
|
||||
* @returns The item object or undefined if no item matches the ID.
|
||||
*/
|
||||
export const getItemById = async (
|
||||
api?: Api | null | undefined,
|
||||
itemId?: string | null | undefined,
|
||||
): Promise<BaseItemDto | undefined> => {
|
||||
if (!api || !itemId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const itemData = await getUserLibraryApi(api).getItem({ itemId });
|
||||
|
||||
const item = itemData.data;
|
||||
if (!item) {
|
||||
console.error("No items found with the specified ID:", itemId);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return item;
|
||||
} catch (error) {
|
||||
console.error("Failed to retrieve the item:", error);
|
||||
throw new Error(`Failed to retrieve the item due to an error: ${error}`);
|
||||
}
|
||||
};
|
||||
@@ -72,21 +72,6 @@ export const readFromLog = (): LogEntry[] => {
|
||||
return logs ? JSON.parse(logs) : [];
|
||||
};
|
||||
|
||||
export const clearLogs = () => {
|
||||
storage.remove("logs");
|
||||
};
|
||||
|
||||
export const dumpDownloadDiagnostics = (extra: any = {}) => {
|
||||
const diagnostics = {
|
||||
timestamp: new Date().toISOString(),
|
||||
processes: extra?.processes || [],
|
||||
nativeTasks: extra?.nativeTasks || [],
|
||||
focusedProcess: extra?.focusedProcess || null,
|
||||
};
|
||||
writeDebugLog("Download diagnostics", diagnostics);
|
||||
return diagnostics;
|
||||
};
|
||||
|
||||
export function useLog() {
|
||||
const context = useContext(LogContext);
|
||||
if (context === null) {
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// seconds to ticks util
|
||||
|
||||
export function secondsToTicks(seconds: number): number {
|
||||
return seconds * 10000000;
|
||||
}
|
||||
@@ -76,9 +76,9 @@ interface LegacyServerCredential {
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode server URL to valid secure store key (legacy, for migration).
|
||||
* Generate a unique key for a server URL (for secure storage).
|
||||
*/
|
||||
export function serverUrlToKey(serverUrl: string): string {
|
||||
function serverUrlToKey(serverUrl: string): string {
|
||||
const encoded = btoa(serverUrl).replace(/[^a-zA-Z0-9]/g, "_");
|
||||
return `${CREDENTIAL_KEY_PREFIX}${encoded}`;
|
||||
}
|
||||
@@ -86,7 +86,7 @@ export function serverUrlToKey(serverUrl: string): string {
|
||||
/**
|
||||
* Generate credential key for a specific account (serverUrl + userId).
|
||||
*/
|
||||
export function credentialKey(serverUrl: string, userId: string): string {
|
||||
function credentialKey(serverUrl: string, userId: string): string {
|
||||
const combined = `${serverUrl}:${userId}`;
|
||||
const encoded = btoa(combined).replace(/[^a-zA-Z0-9]/g, "_");
|
||||
return `${CREDENTIAL_KEY_PREFIX}${encoded}`;
|
||||
@@ -200,10 +200,7 @@ export async function hasAccountCredential(
|
||||
return stored !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all credentials for all accounts on all servers.
|
||||
*/
|
||||
export async function clearAllCredentials(): Promise<void> {
|
||||
async function _clearAllCredentials(): Promise<void> {
|
||||
const previousServers = getPreviousServers();
|
||||
|
||||
for (const server of previousServers) {
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import type {
|
||||
MediaSourceInfo,
|
||||
MediaStream,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
|
||||
abstract class StreamRankerStrategy {
|
||||
abstract streamType: string;
|
||||
|
||||
abstract rankStream(
|
||||
prevIndex: number,
|
||||
prevSource: MediaSourceInfo,
|
||||
mediaStreams: MediaStream[],
|
||||
trackOptions: any,
|
||||
): void;
|
||||
|
||||
protected rank(
|
||||
prevIndex: number,
|
||||
prevSource: MediaSourceInfo,
|
||||
mediaStreams: MediaStream[],
|
||||
trackOptions: any,
|
||||
): void {
|
||||
if (prevIndex === -1) {
|
||||
console.debug("AutoSet Subtitle - No Stream Set");
|
||||
trackOptions[`Default${this.streamType}StreamIndex`] = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!prevSource.MediaStreams || !mediaStreams) {
|
||||
console.debug(`AutoSet ${this.streamType} - No MediaStreams`);
|
||||
return;
|
||||
}
|
||||
|
||||
let bestStreamIndex = null;
|
||||
let bestStreamScore = 0;
|
||||
|
||||
const prevStream = prevSource.MediaStreams[prevIndex];
|
||||
|
||||
if (!prevStream) {
|
||||
console.debug(`AutoSet ${this.streamType} - No prevStream`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.debug(
|
||||
`AutoSet ${this.streamType} - Previous was ${prevStream.Index} - ${prevStream.DisplayTitle}`,
|
||||
);
|
||||
|
||||
let prevRelIndex = 0;
|
||||
for (const stream of prevSource.MediaStreams) {
|
||||
if (stream.Type !== this.streamType) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stream.Index === prevIndex) {
|
||||
break;
|
||||
}
|
||||
|
||||
prevRelIndex += 1;
|
||||
}
|
||||
|
||||
let newRelIndex = 0;
|
||||
for (const stream of mediaStreams) {
|
||||
if (stream.Type !== this.streamType) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let score = 0;
|
||||
|
||||
if (prevStream.Codec === stream.Codec) {
|
||||
score += 1;
|
||||
}
|
||||
if (prevRelIndex === newRelIndex) {
|
||||
score += 1;
|
||||
}
|
||||
if (
|
||||
prevStream.DisplayTitle &&
|
||||
prevStream.DisplayTitle === stream.DisplayTitle
|
||||
) {
|
||||
score += 2;
|
||||
}
|
||||
if (
|
||||
prevStream.Language &&
|
||||
prevStream.Language !== "und" &&
|
||||
prevStream.Language === stream.Language
|
||||
) {
|
||||
score += 2;
|
||||
}
|
||||
|
||||
console.debug(
|
||||
`AutoSet ${this.streamType} - Score ${score} for ${stream.Index} - ${stream.DisplayTitle}`,
|
||||
);
|
||||
if (score > bestStreamScore && score >= 3) {
|
||||
bestStreamScore = score;
|
||||
bestStreamIndex = stream.Index;
|
||||
}
|
||||
|
||||
newRelIndex += 1;
|
||||
}
|
||||
|
||||
if (bestStreamIndex != null) {
|
||||
console.debug(
|
||||
`AutoSet ${this.streamType} - Using ${bestStreamIndex} score ${bestStreamScore}.`,
|
||||
);
|
||||
trackOptions[`Default${this.streamType}StreamIndex`] = bestStreamIndex;
|
||||
} else {
|
||||
console.debug(
|
||||
`AutoSet ${this.streamType} - Threshold not met. Using default.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SubtitleStreamRanker extends StreamRankerStrategy {
|
||||
streamType = "Subtitle";
|
||||
|
||||
rankStream(
|
||||
prevIndex: number,
|
||||
prevSource: MediaSourceInfo,
|
||||
mediaStreams: MediaStream[],
|
||||
trackOptions: any,
|
||||
): void {
|
||||
super.rank(prevIndex, prevSource, mediaStreams, trackOptions);
|
||||
}
|
||||
}
|
||||
|
||||
class AudioStreamRanker extends StreamRankerStrategy {
|
||||
streamType = "Audio";
|
||||
|
||||
rankStream(
|
||||
prevIndex: number,
|
||||
prevSource: MediaSourceInfo,
|
||||
mediaStreams: MediaStream[],
|
||||
trackOptions: any,
|
||||
): void {
|
||||
super.rank(prevIndex, prevSource, mediaStreams, trackOptions);
|
||||
}
|
||||
}
|
||||
|
||||
class StreamRanker {
|
||||
private strategy: StreamRankerStrategy;
|
||||
|
||||
constructor(strategy: StreamRankerStrategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
setStrategy(strategy: StreamRankerStrategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
rankStream(
|
||||
prevIndex: number,
|
||||
prevSource: MediaSourceInfo,
|
||||
mediaStreams: MediaStream[],
|
||||
trackOptions: any,
|
||||
) {
|
||||
this.strategy.rankStream(prevIndex, prevSource, mediaStreams, trackOptions);
|
||||
}
|
||||
}
|
||||
|
||||
export { StreamRanker, SubtitleStreamRanker, AudioStreamRanker };
|
||||
Reference in New Issue
Block a user