feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { Jellyfin } from "@jellyfin/sdk";
|
||||
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
|
||||
@@ -6,23 +7,108 @@ import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
|
||||
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
|
||||
import type { AxiosInstance } from "axios";
|
||||
|
||||
import { createAxiosCertificateInstanceAsync } from "@homarr/core/infrastructure/http";
|
||||
import {
|
||||
createAxiosCertificateInstanceAsync,
|
||||
fetchWithTrustedCertificatesAsync,
|
||||
} from "@homarr/core/infrastructure/http";
|
||||
|
||||
import { createKeyedFingerprint } from "@homarr/common/server";
|
||||
|
||||
import { HandleIntegrationErrors } from "../base/errors/decorator";
|
||||
import { integrationAxiosHttpErrorHandler } from "../base/errors/http";
|
||||
import type { IntegrationTestingInput } from "../base/integration";
|
||||
import { Integration } from "../base/integration";
|
||||
import type { IntegrationHttpAuthentication } from "../http-auth";
|
||||
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||
import type { IMediaServerIntegration } from "../interfaces/media-server/media-server-integration";
|
||||
import type { CurrentSessionsInput, StreamSession } from "../interfaces/media-server/media-server-types";
|
||||
import type { IMediaReleasesIntegration, MediaRelease, MediaType } from "../types";
|
||||
|
||||
function ticksToMs(ticks: number | null | undefined): number | null {
|
||||
return ticks ? Math.round(ticks / 10_000) : null;
|
||||
export function ticksToMs(ticks: number | null | undefined): number | null {
|
||||
return ticks == null ? null : Math.round(ticks / 10_000);
|
||||
}
|
||||
|
||||
// Unlike Plex, Jellyfin doesn't report a session's network location directly - only the
|
||||
// client's RemoteEndPoint (an IP, optionally with a port). Classify it ourselves.
|
||||
const privateAddresses = new BlockList();
|
||||
privateAddresses.addSubnet("10.0.0.0", 8, "ipv4");
|
||||
privateAddresses.addSubnet("172.16.0.0", 12, "ipv4");
|
||||
privateAddresses.addSubnet("192.168.0.0", 16, "ipv4");
|
||||
privateAddresses.addSubnet("127.0.0.0", 8, "ipv4");
|
||||
privateAddresses.addSubnet("169.254.0.0", 16, "ipv4");
|
||||
privateAddresses.addSubnet("fc00::", 7, "ipv6");
|
||||
privateAddresses.addSubnet("fe80::", 10, "ipv6");
|
||||
privateAddresses.addAddress("::1", "ipv6");
|
||||
|
||||
export function extractHost(remoteEndPoint: string): string {
|
||||
if (remoteEndPoint.startsWith("[")) {
|
||||
const end = remoteEndPoint.indexOf("]");
|
||||
return end === -1 ? remoteEndPoint : remoteEndPoint.slice(1, end);
|
||||
}
|
||||
// A bare IPv6 address (no brackets, no port) has more than one colon.
|
||||
const isIPv4WithPort = remoteEndPoint.split(":").length === 2;
|
||||
return isIPv4WithPort ? remoteEndPoint.slice(0, remoteEndPoint.lastIndexOf(":")) : remoteEndPoint;
|
||||
}
|
||||
|
||||
export function parseLocation(remoteEndPoint: string | null | undefined): "lan" | "wan" | null {
|
||||
if (!remoteEndPoint) return null;
|
||||
let host = extractHost(remoteEndPoint);
|
||||
let family = isIP(host);
|
||||
// A dual-stack server can report an IPv4 client as an IPv4-mapped IPv6 address
|
||||
// (e.g. "::ffff:192.168.1.5") - unwrap it so the IPv4 private ranges still apply.
|
||||
if (family === 6 && host.toLowerCase().startsWith("::ffff:") && isIP(host.slice(7)) === 4) {
|
||||
host = host.slice(7);
|
||||
family = 4;
|
||||
}
|
||||
if (!family) return null;
|
||||
return privateAddresses.check(host, family === 4 ? "ipv4" : "ipv6") ? "lan" : "wan";
|
||||
}
|
||||
|
||||
const authorizationPrefix = 'MediaBrowser Client="Homarr", Device="Homarr", DeviceId="homarr", Version="0.0.1"';
|
||||
const pendingAuthentications = new Map<string, Promise<string>>();
|
||||
|
||||
@HandleIntegrationErrors([integrationAxiosHttpErrorHandler])
|
||||
export class JellyfinIntegration extends Integration implements IMediaServerIntegration, IMediaReleasesIntegration {
|
||||
public override async getHttpAuthenticationAsync(): Promise<IntegrationHttpAuthentication> {
|
||||
const accessToken = await this.getAccessTokenAsync();
|
||||
return {
|
||||
headers: { Authorization: `${authorizationPrefix}, Token="${accessToken}"` },
|
||||
redactValues: [accessToken],
|
||||
};
|
||||
}
|
||||
|
||||
private async getAccessTokenAsync(): Promise<string> {
|
||||
if (this.hasSecretValue("apiKey")) return this.getSecretValue("apiKey");
|
||||
const username = this.getSecretValue("username");
|
||||
const password = this.getSecretValue("password");
|
||||
const identity = createKeyedFingerprint(JSON.stringify([this.url("/").toString(), username, password]));
|
||||
const existing = pendingAuthentications.get(identity);
|
||||
if (existing) return await existing;
|
||||
|
||||
const authenticate = async () => {
|
||||
const response = await fetchWithTrustedCertificatesAsync(this.url("/Users/AuthenticateByName"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: authorizationPrefix },
|
||||
body: JSON.stringify({ Username: username, Pw: password }),
|
||||
redirect: "error",
|
||||
}).catch(() => {
|
||||
throw new Error("Jellyfin authentication failed");
|
||||
});
|
||||
if (!response.ok) throw new Error("Jellyfin authentication failed");
|
||||
const result = (await response.json().catch(() => null)) as { AccessToken?: unknown } | null;
|
||||
if (typeof result?.AccessToken !== "string" || result.AccessToken.length === 0)
|
||||
throw new Error("Jellyfin authentication failed");
|
||||
return result.AccessToken;
|
||||
};
|
||||
const pending = authenticate();
|
||||
pendingAuthentications.set(identity, pending);
|
||||
try {
|
||||
return await pending;
|
||||
} finally {
|
||||
pendingAuthentications.delete(identity);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly jellyfin: Jellyfin = new Jellyfin({
|
||||
clientInfo: {
|
||||
name: "Homarr",
|
||||
@@ -56,15 +142,27 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
|
||||
if (sessionInfo.NowPlayingItem) {
|
||||
const positionMs = ticksToMs(sessionInfo.PlayState?.PositionTicks);
|
||||
const durationMs = ticksToMs(sessionInfo.NowPlayingItem.RunTimeTicks);
|
||||
// Jellyfin only reliably fills in MediaSources[].Bitrate for a transcoding session -
|
||||
// /Sessions has no `fields` selector to force it, so fall back to summing the individual
|
||||
// media streams' own bitrates (populated from the source file's metadata) for direct play.
|
||||
const mediaStreamsBitrateBps = sessionInfo.NowPlayingItem.MediaStreams?.reduce(
|
||||
(sum, stream) => sum + (stream.BitRate ?? 0),
|
||||
0,
|
||||
);
|
||||
const bitrateBps =
|
||||
sessionInfo.TranscodingInfo?.Bitrate ?? sessionInfo.NowPlayingItem.MediaSources?.[0]?.Bitrate ?? null;
|
||||
sessionInfo.TranscodingInfo?.Bitrate ??
|
||||
sessionInfo.NowPlayingItem.MediaSources?.[0]?.Bitrate ??
|
||||
(mediaStreamsBitrateBps || null);
|
||||
const bitrateKbps = bitrateBps !== null ? Math.round(bitrateBps / 1000) : null;
|
||||
const isEpisode = sessionInfo.NowPlayingItem.Type === BaseItemKind.Episode;
|
||||
|
||||
currentlyPlaying = {
|
||||
type: convertJellyfinType(sessionInfo.NowPlayingItem.Type),
|
||||
name: sessionInfo.NowPlayingItem.SeriesName ?? sessionInfo.NowPlayingItem.Name ?? "",
|
||||
seasonName: sessionInfo.NowPlayingItem.SeasonName ?? "",
|
||||
episodeName: sessionInfo.NowPlayingItem.EpisodeTitle,
|
||||
seasonNumber: isEpisode ? (sessionInfo.NowPlayingItem.ParentIndexNumber ?? null) : null,
|
||||
episodeName: isEpisode ? sessionInfo.NowPlayingItem.EpisodeTitle : null,
|
||||
episodeNumber: isEpisode ? (sessionInfo.NowPlayingItem.IndexNumber ?? null) : null,
|
||||
albumName: sessionInfo.NowPlayingItem.Album ?? "",
|
||||
episodeCount: sessionInfo.NowPlayingItem.EpisodeCount,
|
||||
playback: {
|
||||
@@ -72,7 +170,7 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
|
||||
positionMs,
|
||||
durationMs,
|
||||
},
|
||||
location: null,
|
||||
location: parseLocation(sessionInfo.RemoteEndPoint),
|
||||
metadata: {
|
||||
video: {
|
||||
resolution:
|
||||
@@ -187,18 +285,20 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
|
||||
* @returns An instance of Api that has been authenticated
|
||||
*/
|
||||
private async getApiAsync(fallbackInstance?: AxiosInstance) {
|
||||
const axiosInstance = fallbackInstance ?? (await createAxiosCertificateInstanceAsync());
|
||||
if (this.hasSecretValue("apiKey")) {
|
||||
const apiKey = this.getSecretValue("apiKey");
|
||||
return this.jellyfin.createApi(this.url("/").toString(), apiKey, axiosInstance);
|
||||
// Testing supplies a confined Axios client; keep all its traffic on that
|
||||
// client. Normal query work shares only the in-flight authentication token.
|
||||
if (fallbackInstance) {
|
||||
if (this.hasSecretValue("apiKey"))
|
||||
return this.jellyfin.createApi(this.url("/").toString(), this.getSecretValue("apiKey"), fallbackInstance);
|
||||
const api = this.jellyfin.createApi(this.url("/").toString(), undefined, fallbackInstance);
|
||||
await api.authenticateUserByName(this.getSecretValue("username"), this.getSecretValue("password"));
|
||||
return api;
|
||||
}
|
||||
|
||||
const apiClient = this.jellyfin.createApi(this.url("/").toString(), undefined, axiosInstance);
|
||||
// Authentication state is stored internally in the Api class, so now
|
||||
// requests that require authentication can be made normally.
|
||||
// see https://typescript-sdk.jellyfin.org/#usage
|
||||
await apiClient.authenticateUserByName(this.getSecretValue("username"), this.getSecretValue("password"));
|
||||
return apiClient;
|
||||
const [axiosInstance, accessToken] = await Promise.all([
|
||||
createAxiosCertificateInstanceAsync(),
|
||||
this.getAccessTokenAsync(),
|
||||
]);
|
||||
return this.jellyfin.createApi(this.url("/").toString(), accessToken, axiosInstance);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user