feat: Tracearr integration (#5060)

This commit is contained in:
StrandedTurtle authored and GitHub committed 2026-03-13 19:19:43 +01:00
1 parent d3c2ad134f
commit f68600150a
22 files changed
+1095 -3

No files matched your search

@@ -0,0 +1,220 @@
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { ImageProxy } from "@homarr/image-proxy";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import { tracearrHealthResponseSchema } from "./tracearr-types";
import type {
TracearrDashboardData,
TracearrHealthResponse,
TracearrHistoryResponse,
TracearrStatsResponse,
TracearrStreamsResponse,
TracearrViolationsResponse,
} from "./tracearr-types";
export class TracearrIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const healthUrl = this.url("/api/v1/public/health");
const healthResponse = await input.fetchAsync(healthUrl, {
headers: this.getAuthHeaders(),
});
if (!healthResponse.ok) {
throw new ResponseError(healthResponse);
}
return { success: true };
}
/**
* GET /api/v1/public/health
* Check server connectivity and status
*/
public async getHealthAsync(): Promise<TracearrHealthResponse> {
const url = this.url("/api/v1/public/health");
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
return tracearrHealthResponseSchema.parse(await response.json());
}
/**
* GET /api/v1/public/stats
* Dashboard statistics with optional server filter
*/
public async getStatsAsync(serverId?: string): Promise<TracearrStatsResponse> {
const url = this.url("/api/v1/public/stats", { serverId });
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
return (await response.json()) as TracearrStatsResponse;
}
/**
* GET /api/v1/public/streams
* Active playback sessions with codec and quality details
*/
public async getStreamsAsync(serverId?: string): Promise<TracearrStreamsResponse> {
const url = this.url("/api/v1/public/streams", { serverId });
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
const json = (await response.json()) as TracearrStreamsResponse;
const imageProxy = new ImageProxy();
return {
...json,
data: await Promise.all(
json.data.map(async (stream) => {
if (stream.userAvatarUrl) {
stream.userAvatarUrl = await this.proxyImageAsync(imageProxy, stream.userAvatarUrl, stream.id, "avatar");
}
if (stream.posterUrl) {
stream.posterUrl = await this.proxyImageAsync(imageProxy, stream.posterUrl, stream.id, "poster");
}
return stream;
}),
),
};
}
/**
* GET /api/v1/public/violations
* Recent rule violations with optional pagination
*/
public async getViolationsAsync(pageSize = 5): Promise<TracearrViolationsResponse> {
const url = this.url("/api/v1/public/violations", {
page: "1",
pageSize: String(pageSize),
});
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
const json = (await response.json()) as TracearrViolationsResponse;
const imageProxy = new ImageProxy();
return {
...json,
data: await Promise.all(
json.data.map(async (violation) => {
violation.user.avatarUrl = await this.proxyImageAsync(
imageProxy,
violation.user.avatarUrl,
violation.user.id,
"avatar",
);
return violation;
}),
),
};
}
/**
* GET /api/v1/public/history
* Session history with optional pagination
*/
public async getHistoryAsync(pageSize = 10): Promise<TracearrHistoryResponse> {
const url = this.url("/api/v1/public/history", {
page: "1",
pageSize: String(pageSize),
});
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
const json = (await response.json()) as TracearrHistoryResponse;
const imageProxy = new ImageProxy();
return {
...json,
data: await Promise.all(
json.data.map(async (session) => {
session.user.avatarUrl = await this.proxyImageAsync(
imageProxy,
session.user.avatarUrl,
session.user.id,
"avatar",
);
return session;
}),
),
};
}
/**
* Get combined dashboard data (stats + streams + violations + history)
* Uses Promise.allSettled for optional endpoints so failures don't break the dashboard.
*/
public async getDashboardDataAsync(): Promise<TracearrDashboardData> {
const [stats, streams] = await Promise.all([this.getStatsAsync(), this.getStreamsAsync()]);
const [violationsResult, historyResult] = await Promise.allSettled([
this.getViolationsAsync(),
this.getHistoryAsync(),
]);
return {
stats,
streams,
violations: violationsResult.status === "fulfilled" ? violationsResult.value : null,
recentActivity: historyResult.status === "fulfilled" ? historyResult.value : null,
};
}
private getAuthHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${this.getSecretValue("apiKey")}`,
};
}
private async proxyImageAsync(
imageProxy: ImageProxy,
url: string | null | undefined,
uniqueId: string,
discriminator: string,
): Promise<string | null> {
if (!url) return null;
try {
// ImageProxy doesn't support fallback urls so we need to remove them
const cleanUrl = url.replace(/&fallback=[^&]+/, "").replace(/\?fallback=[^&]+&?/, "?");
// Build the full URL, then inject _uid as the FIRST query param.
// This is critical because ImageProxy uses bcrypt which truncates at 72 bytes.
// Without this, all long avatar/poster URLs from the same session hash identically
// since they share the same first 72+ bytes.
const baseUrl = this.url(cleanUrl as `/${string}`).toString();
const prefix = `_uid=${discriminator}_${uniqueId}&`;
const fullUrl = baseUrl.includes("?") ? baseUrl.replace("?", `?${prefix}`) : `${baseUrl}?${prefix}`;
return await imageProxy.createImageAsync(fullUrl, this.getAuthHeaders());
} catch {
return null;
}
}
}
@@ -0,0 +1,233 @@
import { z } from "zod";
export const tracearrServerStatusSchema = z.object({
id: z.string(),
name: z.string(),
type: z.union([z.literal("plex"), z.literal("jellyfin"), z.literal("emby")]),
online: z.boolean(),
activeStreams: z.number(),
});
export type TracearrServerStatus = z.infer<typeof tracearrServerStatusSchema>;
export const tracearrHealthResponseSchema = z.object({
status: z.literal("ok"),
timestamp: z.string(),
servers: z.array(tracearrServerStatusSchema),
});
export type TracearrHealthResponse = z.infer<typeof tracearrHealthResponseSchema>;
export interface TracearrStatsResponse {
activeStreams: number;
totalUsers: number;
totalSessions: number;
recentViolations: number;
timestamp: string;
}
export interface TracearrSourceVideoDetails {
bitrate?: number;
framerate?: string;
dynamicRange?: string;
aspectRatio?: number;
profile?: string;
level?: string;
colorSpace?: string;
colorDepth?: number;
}
export interface TracearrSourceAudioDetails {
bitrate?: number;
channelLayout?: string;
language?: string;
sampleRate?: number;
}
export interface TracearrStreamVideoDetails {
bitrate?: number;
width?: number;
height?: number;
framerate?: string;
dynamicRange?: string;
}
export interface TracearrStreamAudioDetails {
bitrate?: number;
channels?: number;
language?: string;
}
export interface TracearrTranscodeInfo {
containerDecision: "directplay" | "copy" | "transcode";
sourceContainer?: string;
streamContainer?: string;
hwRequested?: boolean;
hwDecoding?: string;
hwEncoding?: string;
speed?: number;
throttled?: boolean;
reasons?: string[];
}
export interface TracearrSubtitleInfo {
decision?: string;
codec?: string;
language?: string;
forced?: boolean;
}
export interface TracearrStream {
id: string;
serverId: string;
serverName: string;
username: string;
userThumb: string | null;
userAvatarUrl: string | null;
mediaTitle: string;
mediaType: "movie" | "episode" | "track" | "live" | "photo" | "unknown";
showTitle: string | null;
seasonNumber: number | null;
episodeNumber: number | null;
year: number | null;
thumbPath: string | null;
posterUrl: string | null;
durationMs: number | null;
state: "playing" | "paused" | "stopped";
progressMs: number;
startedAt: string;
isTranscode: boolean | null;
videoDecision: "directplay" | "copy" | "transcode" | null;
audioDecision: "directplay" | "copy" | "transcode" | null;
bitrate: number | null;
sourceVideoCodec: string | null;
sourceAudioCodec: string | null;
sourceAudioChannels: number | null;
sourceVideoWidth: number | null;
sourceVideoHeight: number | null;
sourceVideoDetails: TracearrSourceVideoDetails | null;
sourceAudioDetails: TracearrSourceAudioDetails | null;
streamVideoCodec: string | null;
streamAudioCodec: string | null;
streamVideoDetails: TracearrStreamVideoDetails | null;
streamAudioDetails: TracearrStreamAudioDetails | null;
transcodeInfo: TracearrTranscodeInfo | null;
subtitleInfo: TracearrSubtitleInfo | null;
resolution: string | null;
sourceVideoCodecDisplay: string | null;
sourceAudioCodecDisplay: string | null;
audioChannelsDisplay: string | null;
streamVideoCodecDisplay: string | null;
streamAudioCodecDisplay: string | null;
device: string | null;
player: string | null;
product: string | null;
platform: string | null;
}
export interface TracearrServerStreamSummary {
serverId: string;
serverName: string;
total: number;
transcodes: number;
directStreams: number;
directPlays: number;
totalBitrate: string;
}
export interface TracearrStreamsSummary {
total: number;
transcodes: number;
directStreams: number;
directPlays: number;
totalBitrate: string;
byServer: TracearrServerStreamSummary[];
}
export interface TracearrStreamsResponse {
data: TracearrStream[];
summary: TracearrStreamsSummary;
}
export interface TracearrViolation {
id: string;
serverId: string;
serverName: string;
severity: "low" | "medium" | "high";
acknowledged: boolean;
data: Record<string, string>;
createdAt: string;
rule: {
id: string;
type: string;
name: string;
};
user: {
id: string;
username: string;
thumbUrl: string | null;
avatarUrl: string | null;
};
}
export interface TracearrViolationsResponse {
data: TracearrViolation[];
meta: {
total: number;
page: number;
pageSize: number;
};
}
export interface TracearrHistorySession {
id: string;
serverId: string;
serverName: string;
state: "playing" | "paused" | "stopped";
mediaType: "movie" | "episode" | "track" | "live" | "photo" | "unknown";
mediaTitle: string;
showTitle: string | null;
seasonNumber: number | null;
episodeNumber: number | null;
year: number | null;
thumbPath: string | null;
posterUrl: string | null;
durationMs: number;
progressMs: number;
totalDurationMs: number;
startedAt: string;
stoppedAt: string | null;
watched: boolean;
segmentCount: number;
device: string | null;
player: string | null;
product: string | null;
platform: string | null;
isTranscode: boolean;
videoDecision: "directplay" | "copy" | "transcode" | null;
audioDecision: "directplay" | "copy" | "transcode" | null;
bitrate: number | null;
resolution: string | null;
user: {
id: string;
username: string;
thumbUrl: string | null;
avatarUrl: string | null;
};
}
export interface TracearrHistoryResponse {
data: TracearrHistorySession[];
meta: {
total: number;
page: number;
pageSize: number;
};
}
export interface TracearrDashboardData {
stats: TracearrStatsResponse;
streams: TracearrStreamsResponse;
violations: TracearrViolationsResponse | null;
recentActivity: TracearrHistoryResponse | null;
}