Implements Sonarr callbacks

This commit is contained in:
2023-09-21 15:10:49 +02:00
parent 19a4e7514d
commit 4d419b77c0
7 changed files with 125 additions and 5 deletions

View File

@@ -1,5 +1,85 @@
import type { ServiceConfig } from '$lib/config';
import type { ServiceHandler } from '../service';
export const handle: ServiceHandler = () => {
return { logo: 'https://cdn.rawgit.com/Sonarr/Sonarr/develop/Logo/Sonarr.svg' };
interface Status {
warnings: number;
errors: number;
}
function buildStatus(statuses: any[]): Status {
let warnings = 0;
let errors = 0;
for (const status of statuses) {
switch (status.type) {
case 'warning':
warnings += 1;
break;
case 'error':
errors += 1;
break;
}
}
return { warnings, errors };
}
interface Queue {
nextDate?: Date;
total: number;
}
function recordEstimatedCompletionTime(record: any): number {
if (record.estimatedCompletionTime == undefined) {
return Infinity;
}
return new Date(record.estimatedCompletionTime).getTime();
}
function buildQueue(queue: any): Queue {
if (queue?.records?.length === 0) {
return { total: 0 };
}
let nextTime: number = recordEstimatedCompletionTime(queue.records[0]);
for (let i = 1; i < queue.records.length; i++) {
const recordTime = recordEstimatedCompletionTime(queue.records[i]);
if (recordTime < nextTime) {
nextTime = recordTime;
}
}
return {
total: queue.records.length,
nextDate: nextTime != Infinity ? new Date(nextTime) : undefined
};
}
export const handle: ServiceHandler = async (config: ServiceConfig) => {
const res = {
logo: 'https://cdn.rawgit.com/Sonarr/Sonarr/develop/Logo/Sonarr.svg',
subtitle: 'TV Show tracker'
};
const params = '?apikey=' + config.api_key;
const requests = [
fetch(config.url + '/api/v3/health' + params),
fetch(config.url + '/api/v3/queue' + params + '&includeUnknownSeriesItems=true')
];
const [health, queue] = await Promise.allSettled(requests);
res.status = 'online';
if (health.status != 'fulfilled') {
console.warn("Could not fetch '" + config.url + "' status: " + health.value);
res.status = 'offline';
} else if (health.value.ok == true) {
res.health = buildStatus(await health.value.json());
}
if (queue.status != 'fulfilled') {
console.warn("Could not fetch '" + config.url + "' queue: " + queue.value);
res.status = 'offline';
} else if (queue.value.ok == true) {
res.queue = buildQueue(await queue.value.json());
}
return res;
};