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
@@ -0,0 +1,30 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const count = z.number().finite().int().nonnegative();
|
||||
const statsSchema = z.object({ push_approved_count: count, push_rejected_count: count }).passthrough();
|
||||
const listSchema = z.array(z.unknown());
|
||||
|
||||
export const autobrrStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "approvedPushes", label: "Approved pushes", unit: "count" },
|
||||
{ key: "rejectedPushes", label: "Rejected pushes", unit: "count" },
|
||||
{ key: "filters", label: "Filters", unit: "count" },
|
||||
{ key: "indexers", label: "Indexers", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const [stats, filters, indexers] = await Promise.all([
|
||||
context.requestAsync("/api/release/stats", { signal: context.signal }),
|
||||
context.requestAsync("/api/filters", { signal: context.signal }),
|
||||
context.requestAsync("/api/release/indexers", { signal: context.signal }),
|
||||
]);
|
||||
const parsedStats = statsSchema.parse(stats);
|
||||
return {
|
||||
approvedPushes: parsedStats.push_approved_count,
|
||||
rejectedPushes: parsedStats.push_rejected_count,
|
||||
filters: listSchema.parse(filters).length,
|
||||
indexers: listSchema.parse(indexers).length,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const upstreamSchema = z
|
||||
.object({
|
||||
num_requests: countSchema,
|
||||
fails: countSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const upstreamsSchema = z.array(upstreamSchema);
|
||||
|
||||
const statsSchema = z.object({
|
||||
upstreams: countSchema,
|
||||
requests: countSchema,
|
||||
requestsFailed: countSchema,
|
||||
});
|
||||
|
||||
export const caddyStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
transport: "axios",
|
||||
metrics: [
|
||||
{ key: "upstreams", label: "Upstreams", unit: "count" },
|
||||
{ key: "requests", label: "Active requests", unit: "count" },
|
||||
{ key: "requestsFailed", label: "Failed requests", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/reverse_proxy/upstreams", {
|
||||
method: "GET",
|
||||
signal: context.signal,
|
||||
});
|
||||
const upstreams = upstreamsSchema.parse(response);
|
||||
|
||||
return statsSchema.parse({
|
||||
upstreams: upstreams.length,
|
||||
requests: upstreams.reduce((total, upstream) => total + upstream.num_requests, 0),
|
||||
requestsFailed: upstreams.reduce((total, upstream) => total + upstream.fails, 0),
|
||||
});
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const watchSchema = z
|
||||
.object({
|
||||
last_changed: z.number().finite(),
|
||||
viewed: z.boolean(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const watchesSchema = z.record(z.string(), watchSchema);
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { "x-api-key": context.secret("apiKey") },
|
||||
});
|
||||
|
||||
export const changedetectionStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "diffsDetected", label: "Diffs detected", unit: "count" },
|
||||
{ key: "totalObserved", label: "Total observed", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v1/watch", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const watches = watchesSchema.parse(response);
|
||||
|
||||
return {
|
||||
diffsDetected: Object.values(watches).filter((watch) => watch.last_changed > 0 && !watch.viewed).length,
|
||||
totalObserved: Object.keys(watches).length,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const fileflowsStatusSchema = z.object({
|
||||
queue: z.number().finite().int().nonnegative(),
|
||||
processing: z.number().finite().int().nonnegative(),
|
||||
processed: z.number().finite().int().nonnegative(),
|
||||
time: z
|
||||
.string()
|
||||
.nullish()
|
||||
.transform((value) => value ?? null),
|
||||
});
|
||||
|
||||
export const fileflowsStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "queue", label: "Queued", unit: "count" },
|
||||
{ key: "processing", label: "Processing", unit: "count" },
|
||||
{ key: "processed", label: "Processed", unit: "count" },
|
||||
{ key: "time", label: "Processing time", unit: "text" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/status", { signal: context.signal });
|
||||
return fileflowsStatusSchema.parse(response);
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const statsSchema = z
|
||||
.object({
|
||||
cameras: z.record(z.string(), z.unknown()).default({}),
|
||||
service: z.object({ uptime: z.number().finite().nonnegative(), version: z.string() }).passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const frigateStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "cameras", label: "Cameras", unit: "count" },
|
||||
{ key: "uptime", label: "Uptime", unit: "seconds" },
|
||||
{ key: "version", label: "Version", unit: "text" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const stats = statsSchema.parse(await context.requestAsync("/api/stats", { signal: context.signal }));
|
||||
return { cameras: Object.keys(stats.cameras).length, uptime: stats.service.uptime, version: stats.service.version };
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const endpointResultSchema = z
|
||||
.object({
|
||||
success: z.boolean(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const endpointSchema = z
|
||||
.object({
|
||||
results: z.array(endpointResultSchema),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const endpointsSchema = z.union([z.array(endpointSchema), z.record(z.string(), endpointSchema)]);
|
||||
|
||||
export const gatusStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "up", label: "Up", unit: "count" },
|
||||
{ key: "down", label: "Down", unit: "count" },
|
||||
{ key: "unknown", label: "Unknown", unit: "count" },
|
||||
{ key: "total", label: "Total", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v1/endpoints/statuses", {
|
||||
signal: context.signal,
|
||||
});
|
||||
const endpoints = Object.values(endpointsSchema.parse(response));
|
||||
|
||||
const up = endpoints.filter((endpoint) => endpoint.results.at(-1)?.success === true).length;
|
||||
const down = endpoints.filter((endpoint) => endpoint.results.at(-1)?.success === false).length;
|
||||
|
||||
return {
|
||||
up,
|
||||
down,
|
||||
unknown: endpoints.length - up - down,
|
||||
total: endpoints.length,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const checkSchema = z
|
||||
.object({
|
||||
status: z.enum(["new", "up", "grace", "down", "paused"]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const checksResponseSchema = z
|
||||
.object({
|
||||
checks: z.array(checkSchema),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { "X-Api-Key": context.secret("apiKey") },
|
||||
});
|
||||
|
||||
export const healthchecksStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "checksUp", label: "Up checks", unit: "count" },
|
||||
{ key: "checksDown", label: "Down checks", unit: "count" },
|
||||
{ key: "checksGrace", label: "Checks in grace", unit: "count" },
|
||||
{ key: "checksNew", label: "New checks", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v3/checks/", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const checks = checksResponseSchema.parse(response).checks;
|
||||
|
||||
return {
|
||||
checksUp: countSchema.parse(checks.filter((check) => check.status === "up").length),
|
||||
checksDown: countSchema.parse(checks.filter((check) => check.status === "down").length),
|
||||
checksGrace: countSchema.parse(checks.filter((check) => check.status === "grace").length),
|
||||
checksNew: countSchema.parse(checks.filter((check) => check.status === "new").length),
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,77 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsFetchContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().nonnegative().int();
|
||||
|
||||
const groupStatsResponseSchema = z
|
||||
.object({
|
||||
totalItems: countSchema,
|
||||
totalLocations: countSchema,
|
||||
totalLabels: countSchema.optional(),
|
||||
totalTags: countSchema.optional(),
|
||||
totalWithWarranty: countSchema,
|
||||
totalItemPrice: z.number().finite().nonnegative(),
|
||||
totalUsers: countSchema,
|
||||
})
|
||||
.passthrough()
|
||||
.refine((stats) => stats.totalLabels !== undefined || stats.totalTags !== undefined, {
|
||||
message: "Expected a labels or tags count",
|
||||
});
|
||||
|
||||
export const homeboxStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "items", label: "Items", unit: "count" },
|
||||
{ key: "locations", label: "Locations", unit: "count" },
|
||||
{ key: "labels", label: "Labels", unit: "count" },
|
||||
{ key: "itemsWithWarranty", label: "Items with warranty", unit: "count" },
|
||||
{ key: "totalValue", label: "Total value", unit: "text" },
|
||||
{ key: "users", label: "Users", unit: "count" },
|
||||
],
|
||||
|
||||
getHttpAuthenticationAsync,
|
||||
|
||||
async fetchAsync(context) {
|
||||
const authentication = await getHttpAuthenticationAsync(context);
|
||||
|
||||
const response = await context.requestAsync("/api/v1/groups/statistics", {
|
||||
headers: authentication.headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = groupStatsResponseSchema.parse(response);
|
||||
const group = z.object({ currency: z.string().min(1) }).parse(
|
||||
await context.requestAsync("/api/v1/groups", {
|
||||
headers: authentication.headers,
|
||||
signal: context.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
items: stats.totalItems,
|
||||
locations: stats.totalLocations,
|
||||
labels: stats.totalLabels ?? stats.totalTags ?? 0,
|
||||
itemsWithWarranty: stats.totalWithWarranty,
|
||||
totalValue: `${group.currency} ${stats.totalItemPrice}`,
|
||||
users: stats.totalUsers,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
|
||||
async function getHttpAuthenticationAsync(context: StatsFetchContext) {
|
||||
try {
|
||||
const loginResponse = await context.requestAsync("/api/v1/users/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
username: context.secret("username"),
|
||||
password: context.secret("password"),
|
||||
}).toString(),
|
||||
signal: context.signal,
|
||||
});
|
||||
const login = z.object({ token: z.string().min(1) }).safeParse(loginResponse);
|
||||
if (!login.success) throw new Error("Homebox authentication failed");
|
||||
return { headers: { Authorization: login.data.token }, redactValues: [login.data.token] };
|
||||
} catch {
|
||||
throw new Error("Homebox authentication failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().nonnegative();
|
||||
const viewsResponseSchema = z
|
||||
.object({
|
||||
Audio: countSchema,
|
||||
Movie: countSchema,
|
||||
Series: countSchema,
|
||||
Other: countSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { "X-API-Token": context.secret("apiKey") },
|
||||
});
|
||||
|
||||
export const jellystatStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "songs", label: "Song plays (30 days)", unit: "count" },
|
||||
{ key: "movies", label: "Movie plays (30 days)", unit: "count" },
|
||||
{ key: "episodes", label: "Episode plays (30 days)", unit: "count" },
|
||||
{ key: "other", label: "Other plays (30 days)", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const params = new URLSearchParams({ days: "30" });
|
||||
const response = await context.requestAsync(`/stats/getViewsByLibraryType?${params.toString()}`, {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const views = viewsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
songs: views.Audio,
|
||||
movies: views.Movie,
|
||||
episodes: views.Series,
|
||||
other: views.Other,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const karakeepStatsResponseSchema = z
|
||||
.object({
|
||||
numBookmarks: z.number().finite().nonnegative(),
|
||||
numFavorites: z.number().finite().nonnegative(),
|
||||
numArchived: z.number().finite().nonnegative(),
|
||||
numHighlights: z.number().finite().nonnegative(),
|
||||
numLists: z.number().finite().nonnegative(),
|
||||
numTags: z.number().finite().nonnegative(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { Authorization: `Bearer ${context.secret("apiKey")}` },
|
||||
});
|
||||
|
||||
export const karakeepStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "bookmarks", label: "Bookmarks", unit: "count" },
|
||||
{ key: "favorites", label: "Favorites", unit: "count" },
|
||||
{ key: "archived", label: "Archived", unit: "count" },
|
||||
{ key: "highlights", label: "Highlights", unit: "count" },
|
||||
{ key: "lists", label: "Lists", unit: "count" },
|
||||
{ key: "tags", label: "Tags", unit: "count" },
|
||||
],
|
||||
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v1/users/me/stats", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = karakeepStatsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
bookmarks: stats.numBookmarks,
|
||||
favorites: stats.numFavorites,
|
||||
archived: stats.numArchived,
|
||||
highlights: stats.numHighlights,
|
||||
lists: stats.numLists,
|
||||
tags: stats.numTags,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().nonnegative().int();
|
||||
const librarySchema = z.object({ unavailable: z.boolean().optional() }).passthrough();
|
||||
const pageSchema = z.object({ totalElements: countSchema }).passthrough();
|
||||
|
||||
export const komgaStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "libraries", label: "Libraries", unit: "count" },
|
||||
{ key: "series", label: "Series", unit: "count" },
|
||||
{ key: "books", label: "Books", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const headers = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
const [librariesResponse, seriesResponse, booksResponse] = await Promise.all([
|
||||
context.requestAsync("/api/v1/libraries", { headers, signal: context.signal }),
|
||||
context.requestAsync("/api/v1/series/list", { method: "POST", headers, body: "{}", signal: context.signal }),
|
||||
context.requestAsync("/api/v1/books/list", { method: "POST", headers, body: "{}", signal: context.signal }),
|
||||
]);
|
||||
const libraries = z.array(librarySchema).parse(librariesResponse);
|
||||
const series = pageSchema.parse(seriesResponse);
|
||||
const books = pageSchema.parse(booksResponse);
|
||||
|
||||
return {
|
||||
libraries: libraries.filter((library) => !library.unavailable).length,
|
||||
series: series.totalElements,
|
||||
books: books.totalElements,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,82 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const collectionSchema = z.object({
|
||||
_count: z.object({
|
||||
links: countSchema,
|
||||
}),
|
||||
});
|
||||
|
||||
const collectionEnvelopeSchema = z.union([
|
||||
z.array(collectionSchema),
|
||||
z.object({ response: z.array(collectionSchema) }),
|
||||
z.object({ data: z.object({ collections: z.array(collectionSchema) }) }),
|
||||
]);
|
||||
|
||||
const tagSchema = z.record(z.string(), z.unknown());
|
||||
const tagEnvelopeSchema = z.union([
|
||||
// Prefer the paginated envelope when v1 also includes a legacy response field.
|
||||
z.object({ data: z.object({ tags: z.array(tagSchema), nextCursor: z.union([countSchema, z.string()]).nullish() }) }),
|
||||
z.object({ response: z.array(tagSchema) }),
|
||||
z.array(tagSchema),
|
||||
]);
|
||||
|
||||
const statsSchema = z.object({
|
||||
links: countSchema,
|
||||
collections: countSchema,
|
||||
tags: countSchema,
|
||||
});
|
||||
|
||||
function collectionList(value: unknown) {
|
||||
const parsed = collectionEnvelopeSchema.parse(value);
|
||||
if (Array.isArray(parsed)) return parsed;
|
||||
if ("response" in parsed) return parsed.response;
|
||||
return parsed.data.collections;
|
||||
}
|
||||
|
||||
function tagPage(value: unknown) {
|
||||
const parsed = tagEnvelopeSchema.parse(value);
|
||||
if (Array.isArray(parsed)) return { tags: parsed, nextCursor: null };
|
||||
if ("data" in parsed) return parsed.data;
|
||||
return { tags: parsed.response, nextCursor: null };
|
||||
}
|
||||
|
||||
export const linkwardenStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "links", label: "Links", unit: "count" },
|
||||
{ key: "collections", label: "Collections", unit: "count" },
|
||||
{ key: "tags", label: "Tags", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const [collectionsResponse, tagsResponse] = await Promise.all([
|
||||
context.requestAsync("/api/v1/collections", { signal: context.signal }),
|
||||
context.requestAsync("/api/v1/tags", { signal: context.signal }),
|
||||
]);
|
||||
const collections = collectionList(collectionsResponse);
|
||||
let page = tagPage(tagsResponse);
|
||||
let tagCount = page.tags.length;
|
||||
const visited = new Set<string>();
|
||||
while (page.nextCursor != null) {
|
||||
context.signal.throwIfAborted();
|
||||
const cursor = String(page.nextCursor);
|
||||
if (visited.has(cursor) || visited.size >= 1000)
|
||||
throw new Error("Invalid or excessive Linkwarden tag pagination");
|
||||
visited.add(cursor);
|
||||
page = tagPage(
|
||||
await context.requestAsync(`/api/v1/tags?cursor=${encodeURIComponent(cursor)}`, {
|
||||
signal: context.signal,
|
||||
}),
|
||||
);
|
||||
tagCount += page.tags.length;
|
||||
}
|
||||
|
||||
return statsSchema.parse({
|
||||
links: collections.reduce((total, collection) => total + collection._count.links, 0),
|
||||
collections: collections.length,
|
||||
tags: tagCount,
|
||||
});
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const nonNegativeFiniteNumber = z.number().finite().nonnegative();
|
||||
const handledCount = nonNegativeFiniteNumber.int();
|
||||
|
||||
const storageMetricsSchema = z.object({
|
||||
cleanupTotals: z.object({
|
||||
itemsHandled: handledCount,
|
||||
episodesHandled: handledCount,
|
||||
moviesHandled: handledCount,
|
||||
}),
|
||||
collectionSummary: z.object({
|
||||
activeSizeBytes: nonNegativeFiniteNumber,
|
||||
}),
|
||||
});
|
||||
|
||||
export const maintainerrStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "itemsHandled", label: "Items handled", unit: "count" },
|
||||
{ key: "episodesHandled", label: "Episodes handled", unit: "count" },
|
||||
{ key: "moviesHandled", label: "Movies handled", unit: "count" },
|
||||
{ key: "reclaimable", label: "Reclaimable storage", unit: "bytes" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/storage-metrics", { signal: context.signal });
|
||||
const metrics = storageMetricsSchema.parse(response);
|
||||
|
||||
return {
|
||||
itemsHandled: metrics.cleanupTotals.itemsHandled,
|
||||
episodesHandled: metrics.cleanupTotals.episodesHandled,
|
||||
moviesHandled: metrics.cleanupTotals.moviesHandled,
|
||||
reclaimable: metrics.collectionSummary.activeSizeBytes,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const mealieStatsResponseSchema = z
|
||||
.object({
|
||||
totalRecipes: z.number().finite().int().nonnegative(),
|
||||
totalUsers: z.number().finite().int().nonnegative(),
|
||||
totalCategories: z.number().finite().int().nonnegative(),
|
||||
totalTags: z.number().finite().int().nonnegative(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { Authorization: `Bearer ${context.secret("apiKey")}` },
|
||||
});
|
||||
|
||||
export const mealieStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "recipes", label: "Recipes", unit: "count" },
|
||||
{ key: "users", label: "Users", unit: "count" },
|
||||
{ key: "categories", label: "Categories", unit: "count" },
|
||||
{ key: "tags", label: "Tags", unit: "count" },
|
||||
],
|
||||
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/households/statistics", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = mealieStatsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
recipes: stats.totalRecipes,
|
||||
users: stats.totalUsers,
|
||||
categories: stats.totalCategories,
|
||||
tags: stats.totalTags,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const minifluxCountersSchema = z.object({
|
||||
reads: z.record(z.string(), countSchema),
|
||||
unreads: z.record(z.string(), countSchema),
|
||||
});
|
||||
|
||||
const sumValues = (values: Record<string, number>) => Object.values(values).reduce((total, value) => total + value, 0);
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { "X-Auth-Token": context.secret("apiKey") },
|
||||
});
|
||||
|
||||
export const minifluxStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "read", label: "Read", unit: "count" },
|
||||
{ key: "unread", label: "Unread", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/v1/feeds/counters", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const counters = minifluxCountersSchema.parse(response);
|
||||
|
||||
return {
|
||||
read: sumValues(counters.reads),
|
||||
unread: sumValues(counters.unreads),
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const totalSchema = z.union([z.number().finite().int().nonnegative(), z.string().regex(/^\d+$/)]).transform(Number);
|
||||
const totalsSchema = z.tuple([totalSchema, totalSchema, totalSchema, totalSchema, totalSchema]).rest(totalSchema);
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { Authorization: `Bearer ${context.secret("apiKey")}` },
|
||||
});
|
||||
|
||||
export const netalertxStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "total", label: "Total devices", unit: "count" },
|
||||
{ key: "connected", label: "Connected devices", unit: "count" },
|
||||
{ key: "newDevices", label: "New devices", unit: "count" },
|
||||
{ key: "downAlerts", label: "Down alerts", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/devices/totals", {
|
||||
headers: getHttpAuthentication(context).headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const totals = totalsSchema.parse(response);
|
||||
return { total: totals[0], connected: totals[1], newDevices: totals[3], downAlerts: totals[4] };
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const infoSchema = z
|
||||
.object({
|
||||
alarms: z
|
||||
.object({
|
||||
warning: countSchema,
|
||||
critical: countSchema,
|
||||
})
|
||||
.passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const netdataStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "warnings", label: "Warnings", unit: "count" },
|
||||
{ key: "criticals", label: "Criticals", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v1/info", {
|
||||
signal: context.signal,
|
||||
});
|
||||
const info = infoSchema.parse(response);
|
||||
|
||||
return {
|
||||
warnings: info.alarms.warning,
|
||||
criticals: info.alarms.critical,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsFetchContext, StatsProvider } from "../types";
|
||||
|
||||
const plantitStatsResponseSchema = z
|
||||
.object({
|
||||
diaryEntryCount: z.number().finite().int().nonnegative(),
|
||||
plantCount: z.number().finite().int().nonnegative(),
|
||||
imageCount: z.number().finite().int().nonnegative(),
|
||||
botanicalInfoCount: z.number().finite().int().nonnegative(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const plantitLoginResponseSchema = z.object({
|
||||
jwt: z.object({ value: z.string().min(1) }),
|
||||
});
|
||||
|
||||
export const plantitStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "plants", label: "Plants", unit: "count" },
|
||||
{ key: "species", label: "Species", unit: "count" },
|
||||
{ key: "photos", label: "Photos", unit: "count" },
|
||||
{ key: "events", label: "Events", unit: "count" },
|
||||
],
|
||||
|
||||
getHttpAuthenticationAsync,
|
||||
|
||||
async fetchAsync(context) {
|
||||
const authentication = await getHttpAuthenticationAsync(context);
|
||||
const response = await context.requestAsync("/api/stats", {
|
||||
headers: authentication.headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = plantitStatsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
plants: stats.plantCount,
|
||||
species: stats.botanicalInfoCount,
|
||||
photos: stats.imageCount,
|
||||
events: stats.diaryEntryCount,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
|
||||
async function getHttpAuthenticationAsync(context: StatsFetchContext) {
|
||||
try {
|
||||
const loginResponse = await context.requestAsync("/api/authentication/login", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
username: context.secret("username"),
|
||||
password: context.secret("password"),
|
||||
}),
|
||||
signal: context.signal,
|
||||
});
|
||||
const login = plantitLoginResponseSchema.safeParse(loginResponse);
|
||||
if (!login.success) throw new Error("Plant-it authentication failed");
|
||||
const token = login.data.jwt.value;
|
||||
return { headers: { Authorization: `Bearer ${token}` }, redactValues: [token] };
|
||||
} catch {
|
||||
throw new Error("Plant-it authentication failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const targetsResponseSchema = z
|
||||
.object({
|
||||
status: z.literal("success"),
|
||||
data: z
|
||||
.object({
|
||||
activeTargets: z.array(
|
||||
z
|
||||
.object({
|
||||
health: z.string(),
|
||||
})
|
||||
.passthrough(),
|
||||
),
|
||||
droppedTargets: z.array(z.unknown()),
|
||||
})
|
||||
.passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (context.hasSecret("username") && context.hasSecret("password")) {
|
||||
headers.Authorization = `Basic ${Buffer.from(`${context.secret("username")}:${context.secret("password")}`, "utf8").toString("base64")}`;
|
||||
}
|
||||
|
||||
return { headers };
|
||||
};
|
||||
|
||||
export const prometheusStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "total", label: "Targets", unit: "count" },
|
||||
{ key: "up", label: "Up", unit: "count" },
|
||||
{ key: "down", label: "Down", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const { headers } = getHttpAuthentication(context);
|
||||
|
||||
const response = await context.requestAsync("/api/v1/targets", {
|
||||
headers,
|
||||
signal: context.signal,
|
||||
});
|
||||
const targets = targetsResponseSchema.parse(response).data.activeTargets;
|
||||
|
||||
return {
|
||||
total: countSchema.parse(targets.length),
|
||||
up: countSchema.parse(targets.filter((target) => target.health === "up").length),
|
||||
down: countSchema.parse(targets.filter((target) => target.health === "down").length),
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
const bytesSchema = z.number().finite().nonnegative();
|
||||
|
||||
const statsResponseSchema = z
|
||||
.object({
|
||||
PLATFORMS: countSchema,
|
||||
ROMS: countSchema,
|
||||
SAVES: countSchema,
|
||||
STATES: countSchema,
|
||||
SCREENSHOTS: countSchema,
|
||||
FILESIZE: bytesSchema.optional(),
|
||||
TOTAL_FILESIZE_BYTES: bytesSchema.optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.refine((stats) => stats.FILESIZE !== undefined || stats.TOTAL_FILESIZE_BYTES !== undefined, {
|
||||
message: "Expected FILESIZE or TOTAL_FILESIZE_BYTES",
|
||||
});
|
||||
|
||||
export const rommStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "platforms", label: "Platforms", unit: "count" },
|
||||
{ key: "roms", label: "ROMs", unit: "count" },
|
||||
{ key: "saves", label: "Saves", unit: "count" },
|
||||
{ key: "states", label: "States", unit: "count" },
|
||||
{ key: "screenshots", label: "Screenshots", unit: "count" },
|
||||
{ key: "totalFileSize", label: "Total file size", unit: "bytes" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/stats", { signal: context.signal });
|
||||
const stats = statsResponseSchema.parse(response);
|
||||
const totalFileSize = stats.FILESIZE ?? stats.TOTAL_FILESIZE_BYTES;
|
||||
if (totalFileSize === undefined) throw new Error("RomM stats did not include a file size");
|
||||
|
||||
return {
|
||||
platforms: stats.PLATFORMS,
|
||||
roms: stats.ROMS,
|
||||
saves: stats.SAVES,
|
||||
states: stats.STATES,
|
||||
screenshots: stats.SCREENSHOTS,
|
||||
totalFileSize,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
const summarySchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
summary: z.record(
|
||||
z.string(),
|
||||
z.object({
|
||||
device: z.object({ archived: z.boolean(), device_status: z.number().int() }).passthrough(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.passthrough();
|
||||
const settingsSchema = z
|
||||
.object({
|
||||
settings: z.object({ metrics: z.object({ status_threshold: z.number().int() }).passthrough() }).passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const status = { passed: 0, failedSmart: 1, failedScrutiny: 2, failedBoth: 3 } as const;
|
||||
|
||||
export const scrutinyStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "passed", label: "Passed devices", unit: "count" },
|
||||
{ key: "failed", label: "Failed devices", unit: "count" },
|
||||
{ key: "unknown", label: "Unknown devices", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const [summaryResponse, settingsResponse] = await Promise.all([
|
||||
context.requestAsync("/api/summary", { signal: context.signal }),
|
||||
context.requestAsync("/api/settings", { signal: context.signal }),
|
||||
]);
|
||||
const summary = summarySchema.parse(summaryResponse);
|
||||
const threshold = settingsSchema.parse(settingsResponse).settings.metrics.status_threshold;
|
||||
const devices = Object.values(summary.data.summary).filter(({ device }) => !device.archived);
|
||||
const failed = devices.filter(({ device }) => {
|
||||
if (threshold === status.failedBoth)
|
||||
return device.device_status > status.passed && device.device_status <= status.failedBoth;
|
||||
return device.device_status === threshold || device.device_status === status.failedBoth;
|
||||
}).length;
|
||||
const unknown = devices.filter(
|
||||
({ device }) => device.device_status < status.passed || device.device_status > status.failedBoth,
|
||||
).length;
|
||||
|
||||
return {
|
||||
passed: countSchema.parse(devices.length - failed - unknown),
|
||||
failed: countSchema.parse(failed),
|
||||
unknown: countSchema.parse(unknown),
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const spoolSchema = z.object({
|
||||
id: z.number().finite().int().nonnegative(),
|
||||
remaining_weight: z.number().finite().nonnegative().nullish(),
|
||||
archived: z.boolean(),
|
||||
});
|
||||
|
||||
const spoolListSchema = z.array(spoolSchema);
|
||||
|
||||
export const spoolmanStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "spools", label: "Spools", unit: "count" },
|
||||
{ key: "remainingWeight", label: "Remaining weight", unit: "grams" },
|
||||
],
|
||||
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/api/v1/spool", { signal: context.signal });
|
||||
const spools = spoolListSchema.parse(response).filter((spool) => !spool.archived);
|
||||
|
||||
let remainingWeight: number | null = 0;
|
||||
for (const spool of spools) {
|
||||
if (spool.remaining_weight == null) {
|
||||
remainingWeight = null;
|
||||
break;
|
||||
}
|
||||
remainingWeight += spool.remaining_weight;
|
||||
}
|
||||
|
||||
return {
|
||||
spools: spools.length,
|
||||
remainingWeight,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,81 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
const measurementSchema = z.number().finite().nonnegative();
|
||||
|
||||
const statsSchema = z
|
||||
.object({
|
||||
scene_count: countSchema,
|
||||
scenes_size: measurementSchema,
|
||||
scenes_duration: measurementSchema,
|
||||
image_count: countSchema,
|
||||
images_size: measurementSchema,
|
||||
gallery_count: countSchema,
|
||||
performer_count: countSchema,
|
||||
studio_count: countSchema,
|
||||
tag_count: countSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
const responseSchema = z
|
||||
.object({
|
||||
data: z.object({ stats: statsSchema }).strict(),
|
||||
errors: z.never().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const query = `query {
|
||||
stats {
|
||||
scene_count
|
||||
scenes_size
|
||||
scenes_duration
|
||||
image_count
|
||||
images_size
|
||||
gallery_count
|
||||
performer_count
|
||||
studio_count
|
||||
tag_count
|
||||
}
|
||||
}`;
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { ApiKey: context.secret("apiKey") },
|
||||
});
|
||||
|
||||
export const stashStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "scenes", label: "Scenes", unit: "count" },
|
||||
{ key: "sceneBytes", label: "Scene size", unit: "bytes" },
|
||||
{ key: "sceneDuration", label: "Scene duration", unit: "seconds" },
|
||||
{ key: "images", label: "Images", unit: "count" },
|
||||
{ key: "imageBytes", label: "Image size", unit: "bytes" },
|
||||
{ key: "galleries", label: "Galleries", unit: "count" },
|
||||
{ key: "performers", label: "Performers", unit: "count" },
|
||||
{ key: "studios", label: "Studios", unit: "count" },
|
||||
{ key: "tags", label: "Tags", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/graphql", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...getHttpAuthentication(context).headers },
|
||||
body: JSON.stringify({ query }),
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = responseSchema.parse(response).data.stats;
|
||||
|
||||
return {
|
||||
scenes: stats.scene_count,
|
||||
sceneBytes: stats.scenes_size,
|
||||
sceneDuration: stats.scenes_duration,
|
||||
images: stats.image_count,
|
||||
imageBytes: stats.images_size,
|
||||
galleries: stats.gallery_count,
|
||||
performers: stats.performer_count,
|
||||
studios: stats.studio_count,
|
||||
tags: stats.tag_count,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const nonNegativeFiniteNumberSchema = z.number().finite().nonnegative();
|
||||
|
||||
const statusSchema = z
|
||||
.object({
|
||||
numActiveSessions: nonNegativeFiniteNumberSchema,
|
||||
numConnections: nonNegativeFiniteNumberSchema,
|
||||
bytesProxied: nonNegativeFiniteNumberSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const syncthingRelayStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "numActiveSessions", label: "Active sessions", unit: "count" },
|
||||
{ key: "numConnections", label: "Connections", unit: "count" },
|
||||
{ key: "bytesProxied", label: "Bytes proxied", unit: "bytes" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/status", { signal: context.signal });
|
||||
const status = statusSchema.parse(response);
|
||||
|
||||
return {
|
||||
numActiveSessions: status.numActiveSessions,
|
||||
numConnections: status.numConnections,
|
||||
bytesProxied: status.bytesProxied,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const count = z.number().int().nonnegative();
|
||||
const space = z.object({ user_count: count, recipe_count: count });
|
||||
const spaces = z.union([z.array(space), z.object({ results: z.array(space) })]);
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { Authorization: `Bearer ${context.secret("apiKey")}` },
|
||||
});
|
||||
|
||||
export const tandoorStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "users", label: "Users in first space", unit: "count" },
|
||||
{ key: "recipes", label: "Recipes in first space", unit: "count" },
|
||||
{ key: "keywords", label: "Keywords", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const headers = getHttpAuthentication(context).headers;
|
||||
const [spaceResponse, keywordResponse] = await Promise.all([
|
||||
context.requestAsync("/api/space/", { headers, signal: context.signal }),
|
||||
context.requestAsync("/api/keyword/?page=1&page_size=1", { headers, signal: context.signal }),
|
||||
]);
|
||||
const parsed = spaces.parse(spaceResponse);
|
||||
let first: z.infer<typeof space> | undefined;
|
||||
if (Array.isArray(parsed)) first = parsed[0];
|
||||
else first = parsed.results[0];
|
||||
return {
|
||||
users: first?.user_count ?? null,
|
||||
recipes: first?.recipe_count ?? null,
|
||||
keywords: z.object({ count }).parse(keywordResponse).count,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const triliumStatsResponseSchema = z
|
||||
.object({
|
||||
version: z.object({ app: z.string().min(1) }).passthrough(),
|
||||
database: z.object({ activeNotes: z.number().finite().int().nonnegative() }).passthrough(),
|
||||
statistics: z.object({ databaseSizeBytes: z.number().finite().nonnegative() }).passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const triliumStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "version", label: "Version", unit: "text" },
|
||||
{ key: "notesCount", label: "Notes", unit: "count" },
|
||||
{ key: "dbSize", label: "Database size", unit: "bytes" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const response = await context.requestAsync("/etapi/metrics?format=json", {
|
||||
signal: context.signal,
|
||||
});
|
||||
const stats = triliumStatsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
version: stats.version.app,
|
||||
notesCount: stats.database.activeNotes,
|
||||
dbSize: stats.statistics.databaseSizeBytes,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsAuthenticationContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().nonnegative().int();
|
||||
const collectionStatsSchema = z.object({ doc_count: countSchema }).passthrough();
|
||||
const downloadStatsSchema = z
|
||||
.object({ pending: countSchema.nullable().transform((value) => value ?? 0) })
|
||||
.passthrough();
|
||||
|
||||
const getHttpAuthentication = (context: StatsAuthenticationContext) => ({
|
||||
headers: { Authorization: `Token ${context.secret("apiKey")}` },
|
||||
});
|
||||
|
||||
export const tubearchivistStatsProvider = {
|
||||
getHttpAuthentication,
|
||||
metrics: [
|
||||
{ key: "pendingDownloads", label: "Pending downloads", unit: "count" },
|
||||
{ key: "videos", label: "Videos", unit: "count" },
|
||||
{ key: "channels", label: "Channels", unit: "count" },
|
||||
{ key: "playlists", label: "Playlists", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const headers = getHttpAuthentication(context).headers;
|
||||
const [downloadsResponse, videosResponse, channelsResponse, playlistsResponse] = await Promise.all([
|
||||
context.requestAsync("/api/stats/download/", { headers, signal: context.signal }),
|
||||
context.requestAsync("/api/stats/video/", { headers, signal: context.signal }),
|
||||
context.requestAsync("/api/stats/channel/", { headers, signal: context.signal }),
|
||||
context.requestAsync("/api/stats/playlist/", { headers, signal: context.signal }),
|
||||
]);
|
||||
|
||||
return {
|
||||
pendingDownloads: downloadStatsSchema.parse(downloadsResponse).pending ?? 0,
|
||||
videos: collectionStatsSchema.parse(videosResponse).doc_count,
|
||||
channels: collectionStatsSchema.parse(channelsResponse).doc_count,
|
||||
playlists: collectionStatsSchema.parse(playlistsResponse).doc_count,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().int().nonnegative();
|
||||
|
||||
const workersResponseSchema = z
|
||||
.object({
|
||||
workers_status: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
idle: z.boolean(),
|
||||
})
|
||||
.passthrough(),
|
||||
)
|
||||
.min(0),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const pendingResponseSchema = z
|
||||
.object({
|
||||
recordsTotal: countSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const unmanicStatsProvider = {
|
||||
getHttpAuthentication: () => ({ headers: {} }),
|
||||
metrics: [
|
||||
{ key: "activeWorkers", label: "Active workers", unit: "count" },
|
||||
{ key: "totalWorkers", label: "Total workers", unit: "count" },
|
||||
{ key: "recordsTotal", label: "Pending records", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const workersResponse = await context.requestAsync("/unmanic/api/v2/workers/status", {
|
||||
method: "GET",
|
||||
signal: context.signal,
|
||||
});
|
||||
const pendingResponse = await context.requestAsync("/unmanic/api/v2/pending/tasks", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
start: 0,
|
||||
length: 0,
|
||||
search_value: "",
|
||||
status: "all",
|
||||
order_by: "priority",
|
||||
order_direction: "desc",
|
||||
library_ids: [],
|
||||
}),
|
||||
signal: context.signal,
|
||||
});
|
||||
const workers = workersResponseSchema.parse(workersResponse).workers_status;
|
||||
const pending = pendingResponseSchema.parse(pendingResponse);
|
||||
|
||||
return {
|
||||
activeWorkers: workers.filter((worker) => !worker.idle).length,
|
||||
totalWorkers: workers.length,
|
||||
recordsTotal: pending.recordsTotal,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,86 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsFetchContext, StatsProvider } from "../types";
|
||||
|
||||
const countSchema = z.number().finite().nonnegative();
|
||||
|
||||
const statsResponseSchema = z
|
||||
.object({
|
||||
status: z.literal(true),
|
||||
// xTeVe omits zero-valued fields because its Go response uses `omitempty`.
|
||||
"streams.all": countSchema.optional().default(0),
|
||||
"streams.active": countSchema.optional().default(0),
|
||||
"streams.xepg": countSchema.optional().default(0),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const loginResponseSchema = z
|
||||
.object({
|
||||
status: z.literal(true),
|
||||
token: z.string().min(1),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getLoginTokenAsync = async (context: StatsFetchContext): Promise<string | undefined> => {
|
||||
const hasUsername = context.hasSecret("username");
|
||||
const hasPassword = context.hasSecret("password");
|
||||
if (!hasUsername && !hasPassword) return undefined;
|
||||
if (!hasUsername || !hasPassword) throw new Error("xTeVe authentication failed");
|
||||
|
||||
try {
|
||||
const loginResponse = await context.requestAsync("/api/", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
cmd: "login",
|
||||
username: context.secret("username"),
|
||||
password: context.secret("password"),
|
||||
}),
|
||||
signal: context.signal,
|
||||
});
|
||||
const login = loginResponseSchema.safeParse(loginResponse);
|
||||
if (!login.success) throw new Error("xTeVe authentication failed");
|
||||
return login.data.token;
|
||||
} catch {
|
||||
throw new Error("xTeVe authentication failed");
|
||||
}
|
||||
};
|
||||
|
||||
export const xteveStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "streamsAll", label: "All streams", unit: "count" },
|
||||
{ key: "streamsActive", label: "Active streams", unit: "count" },
|
||||
{ key: "streamsXepg", label: "XEPG streams", unit: "count" },
|
||||
],
|
||||
async getHttpAuthenticationAsync(context: StatsFetchContext) {
|
||||
const token = await getLoginTokenAsync(context);
|
||||
if (token === undefined) return { headers: {} };
|
||||
return {
|
||||
headers: {},
|
||||
body: { type: "jsonField" as const, name: "token", value: token },
|
||||
redactValues: [token],
|
||||
};
|
||||
},
|
||||
async fetchAsync(context) {
|
||||
const init = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: context.signal,
|
||||
} as const;
|
||||
|
||||
const token = await getLoginTokenAsync(context);
|
||||
const payload: { cmd: "status"; token?: string } = token ? { cmd: "status", token } : { cmd: "status" };
|
||||
|
||||
const response = await context.requestAsync("/api/", {
|
||||
...init,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const stats = statsResponseSchema.parse(response);
|
||||
|
||||
return {
|
||||
streamsAll: stats["streams.all"],
|
||||
streamsActive: stats["streams.active"],
|
||||
streamsXepg: stats["streams.xepg"],
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { StatsProvider } from "../types";
|
||||
|
||||
const finiteNumberSchema = z.number().finite().nonnegative();
|
||||
|
||||
const countResponseSchema = z.array(
|
||||
z
|
||||
.object({
|
||||
count: finiteNumberSchema,
|
||||
})
|
||||
.passthrough(),
|
||||
);
|
||||
|
||||
const artistsResponseSchema = z.array(
|
||||
z
|
||||
.object({
|
||||
artists: z.array(z.unknown()),
|
||||
})
|
||||
.passthrough(),
|
||||
);
|
||||
|
||||
const allTimeStart = "2006-04-23T00:00:00.000Z";
|
||||
|
||||
const endpointPath = (endpoint: string) => {
|
||||
const params = new URLSearchParams({
|
||||
start: allTimeStart,
|
||||
timeSplit: "all",
|
||||
});
|
||||
return `/spotify/${endpoint}?${params.toString()}` as `/${string}`;
|
||||
};
|
||||
|
||||
export const yourSpotifyStatsProvider = {
|
||||
metrics: [
|
||||
{ key: "songs", label: "Songs listened", unit: "count" },
|
||||
{ key: "time", label: "Listening time", unit: "seconds" },
|
||||
{ key: "artists", label: "Artists listened", unit: "count" },
|
||||
],
|
||||
async fetchAsync(context) {
|
||||
const [songsResponse, timeResponse, artistsResponse] = await Promise.all([
|
||||
context.requestAsync(endpointPath("songs_per"), { signal: context.signal }),
|
||||
context.requestAsync(endpointPath("time_per"), { signal: context.signal }),
|
||||
context.requestAsync(endpointPath("different_artists_per"), { signal: context.signal }),
|
||||
]);
|
||||
|
||||
const songs = countResponseSchema.parse(songsResponse)[0]?.count ?? 0;
|
||||
const timeMilliseconds = countResponseSchema.parse(timeResponse)[0]?.count ?? 0;
|
||||
const artists = artistsResponseSchema.parse(artistsResponse)[0]?.artists.length ?? 0;
|
||||
|
||||
return {
|
||||
songs,
|
||||
time: timeMilliseconds / 1000,
|
||||
artists,
|
||||
};
|
||||
},
|
||||
} satisfies StatsProvider;
|
||||
Reference in new issue
Block a user