Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

16.7 KB
Raw Blame
import { BlockList, isIP } from "node:net";
import { Jellyfin } from "@jellyfin/sdk";
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client/models";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api";
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,
  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";

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";
}

// Episodes only carry their own name, so the show name is used as the title and the episode as the subtitle.
export const getMediaReleaseTitle = (item: BaseItemDto): string => {
  if (item.Type === "Episode" && item.SeriesName) return item.SeriesName;
  return item.Name ?? "";
};

export const formatEpisodeSubtitle = (item: BaseItemDto): string | undefined => {
  // Without a series name the title stays the item name, so the previous tagline is kept as the subtitle.
  if (!item.SeriesName) return item.Taglines?.at(0);
  const name = item.Name ?? item.EpisodeTitle ?? "";
  const season = item.ParentIndexNumber;
  const episode = item.IndexNumber;
  if (season === undefined || season === null || episode === undefined || episode === null) {
    return name || undefined;
  }
  const code = `S${String(season).padStart(2, "0")}E${String(episode).padStart(2, "0")}`;
  return name ? `${code} – ${name}` : code;
};

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",
      version: "0.0.1",
    },
    deviceInfo: {
      name: "Homarr",
      id: "homarr",
    },
  });

  protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
    const api = await this.getApiAsync(input.axiosInstance);
    const systemApi = getSystemApi(api);
    await systemApi.getPingSystem();
    return { success: true };
  }

  public async getCurrentSessionsAsync(options: CurrentSessionsInput): Promise<StreamSession[]> {
    const api = await this.getApiAsync();
    const sessionApi = getSessionApi(api);
    const sessions = await sessionApi.getSessions();

    return sessions.data
      .filter((sessionInfo) => sessionInfo.UserId !== undefined)
      .filter((sessionInfo) => sessionInfo.DeviceId !== "homarr")
      .filter((sessionInfo) => !options.showOnlyPlaying || sessionInfo.NowPlayingItem !== undefined)
      .map((sessionInfo): StreamSession => {
        let currentlyPlaying: StreamSession["currentlyPlaying"] | null = null;

        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 ??
            (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 ?? "",
            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: {
              state: sessionInfo.PlayState?.IsPaused ? "paused" : "playing",
              positionMs,
              durationMs,
            },
            location: parseLocation(sessionInfo.RemoteEndPoint),
            metadata: {
              video: {
                resolution:
                  sessionInfo.NowPlayingItem.Width && sessionInfo.NowPlayingItem.Height
                    ? {
                        width: sessionInfo.NowPlayingItem.Width,
                        height: sessionInfo.NowPlayingItem.Height,
                      }
                    : null,
                frameRate: sessionInfo.TranscodingInfo?.Framerate ?? null,
              },
              audio: {
                channelCount: sessionInfo.TranscodingInfo?.AudioChannels ?? null,
                codec: sessionInfo.TranscodingInfo?.AudioCodec ?? null,
              },
              transcoding: {
                resolution:
                  sessionInfo.TranscodingInfo?.Width && sessionInfo.TranscodingInfo.Height
                    ? {
                        width: sessionInfo.TranscodingInfo.Width,
                        height: sessionInfo.TranscodingInfo.Height,
                      }
                    : null,
                target: {
                  audioCodec: sessionInfo.TranscodingInfo?.AudioCodec ?? null,
                  videoCodec: sessionInfo.TranscodingInfo?.VideoCodec ?? null,
                },
                container: sessionInfo.TranscodingInfo?.Container ?? null,
                isVideoDirect: sessionInfo.TranscodingInfo?.IsVideoDirect ?? true,
                isAudioDirect: sessionInfo.TranscodingInfo?.IsAudioDirect ?? true,
                containerChanged: sessionInfo.PlayState?.PlayMethod === "DirectStream",
              },
              bitrateKbps,
            },
          };
        }

        return {
          sessionId: `${sessionInfo.Id}`,
          sessionName: `${sessionInfo.Client} (${sessionInfo.DeviceName})`,
          user: {
            profilePictureUrl: this.externalUrl(`/Users/${sessionInfo.UserId}/Images/Primary`).toString(),
            userId: sessionInfo.UserId ?? "",
            username: sessionInfo.UserName ?? "",
          },
          currentlyPlaying,
        };
      });
  }

  public async getMediaReleasesAsync(): Promise<MediaRelease[]> {
    const apiClient = await this.getApiAsync();
    const userLibraryApi = getUserLibraryApi(apiClient);
    const userApi = getUserApi(apiClient);

    const users = await userApi.getUsers();
    const userId = users.data.at(0)?.Id;
    if (!userId) {
      throw new Error("No users found");
    }

    const result = await userLibraryApi.getLatestMedia({
      fields: ["CustomRating", "Studios", "Genres", "ChildCount", "DateCreated", "Overview", "Taglines"],
      userId,
      limit: 100,
      // Root-level grouping uses the first library's type and can omit items from other libraries.
      groupItems: false,
    });
    // Match Jellyfin's latest-media grouping without losing mixed-library results.
    // A single recent episode stays visible; batches use the series artwork and metadata.
    const episodeCounts = new Map<string, number>();
    for (const item of result.data) {
      if (item.Type !== "Episode" || !item.SeriesId) continue;
      episodeCounts.set(item.SeriesId, (episodeCounts.get(item.SeriesId) ?? 0) + 1);
    }
    const seriesIds = [...episodeCounts].filter(([, count]) => count > 1).map(([id]) => id);
    const seriesResults = await Promise.allSettled(
      seriesIds.map((itemId) => userLibraryApi.getItem({ userId, itemId })),
    );
    const series = new Map<string, BaseItemDto>();
    for (const seriesResult of seriesResults) {
      if (seriesResult.status !== "fulfilled") continue;
      const item = seriesResult.value.data;
      if (item.Type === "Series" && item.Id) series.set(item.Id, item);
    }
    const displayedSeries = new Set<string>();
    const items = result.data.flatMap((item) => {
      if (item.Type !== "Episode" || !item.SeriesId) return [item];
      const parent = series.get(item.SeriesId);
      // Keep playable episodes if the parent is missing or inaccessible.
      if (!parent) return [item];
      if (displayedSeries.has(item.SeriesId)) return [];
      displayedSeries.add(item.SeriesId);
      return [parent];
    });
    return items.map((item) => {
      const isEpisode = item.Type === "Episode";
      return {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        id: item.Id!,
        type: this.mapMediaReleaseType(item.Type),
        title: getMediaReleaseTitle(item),
        subtitle: isEpisode ? formatEpisodeSubtitle(item) : item.Taglines?.at(0),
        description: item.Overview ?? undefined,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        releaseDate: new Date(item.PremiereDate ?? item.DateCreated!),
        imageUrls: {
          poster: super
            .externalUrl(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`)
            .toString(),
          backdrop: this.getMediaReleaseBackdropUrl(item),
        },
        producer: item.Studios?.at(0)?.Name ?? undefined,
        rating: item.CommunityRating?.toFixed(1),
        tags: item.Genres ?? [],
        href: super.externalUrl(`/web/index.html#!/details?id=${item.Id}&serverId=${item.ServerId}`).toString(),
      };
    });
  }

  private getMediaReleaseBackdropUrl(item: BaseItemDto) {
    let itemId: string | undefined;
    if (item.BackdropImageTags?.length) itemId = item.Id;
    else if (item.ParentBackdropImageTags?.length) itemId = item.ParentBackdropItemId ?? undefined;
    if (!itemId) return undefined;
    return super.externalUrl(`/Items/${itemId}/Images/Backdrop/0?maxWidth=960&quality=70`).toString();
  }

  private mapMediaReleaseType(type: BaseItemKind | undefined): MediaType {
    switch (type) {
      case "Audio":
      case "AudioBook":
      case "MusicAlbum":
        return "music";
      case "Book":
        return "book";
      case "Episode":
      case "Series":
      case "Season":
        return "tv";
      case "Movie":
        return "movie";
      case "Video":
        return "video";
      default:
        return "unknown";
    }
  }

  /**
   * Constructs an ApiClient synchronously with an ApiKey or asynchronously
   * with a username and password.
   * @returns An instance of Api that has been authenticated
   */
  private async getApiAsync(fallbackInstance?: 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 [axiosInstance, accessToken] = await Promise.all([
      createAxiosCertificateInstanceAsync(),
      this.getAccessTokenAsync(),
    ]);
    return this.jellyfin.createApi(this.url("/").toString(), accessToken, axiosInstance);
  }
}

export const convertJellyfinType = (
  kind: BaseItemKind | undefined,
): Exclude<StreamSession["currentlyPlaying"], null>["type"] => {
  switch (kind) {
    case BaseItemKind.Audio:
    case BaseItemKind.MusicVideo:
      return "audio";
    case BaseItemKind.Episode:
    case BaseItemKind.Video:
      return "video";
    case BaseItemKind.Movie:
      return "movie";
    case BaseItemKind.TvChannel:
    case BaseItemKind.TvProgram:
    case BaseItemKind.LiveTvChannel:
    case BaseItemKind.LiveTvProgram:
    default:
      return "tv";
  }
};