Add useNet tile

This commit is contained in:
Meierschlumpf
2022-12-11 16:06:41 +01:00
parent c2571190f6
commit bbc02f38c1
13 changed files with 426 additions and 273 deletions

View File

@@ -0,0 +1,124 @@
import {
Badge,
Button,
Group,
Select,
Stack,
Tabs,
Text,
Title,
useMantineTheme,
} from '@mantine/core';
import { IconPlayerPause, IconPlayerPlay } from '@tabler/icons';
import { useEffect, useState } from 'react';
import { useElementSize } from '@mantine/hooks';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTranslation } from 'next-i18next';
import { useConfigContext } from '../../../../config/provider';
import { UsenetQueueList } from './UsenetQueueList';
import {
useGetUsenetInfo,
usePauseUsenetQueue,
useResumeUsenetQueue,
} from '../../../../tools/hooks/api';
import { humanFileSize } from '../../../../tools/humanFileSize';
import { ServiceIntegrationType } from '../../../../types/service';
import { HomarrCardWrapper } from '../HomarrCardWrapper';
import { BaseTileProps } from '../type';
import { UsenetHistoryList } from './UsenetHistoryList';
dayjs.extend(duration);
const downloadServiceTypes: ServiceIntegrationType['type'][] = ['sabnzbd', 'nzbGet'];
interface UseNetTileProps extends BaseTileProps {}
export const UseNetTile = ({ className }: UseNetTileProps) => {
const { t } = useTranslation('modules/usenet');
const { config } = useConfigContext();
const downloadServices =
config?.services.filter(
(x) => x.integration && downloadServiceTypes.includes(x.integration.type)
) ?? [];
const [selectedServiceId, setSelectedService] = useState<string | null>(downloadServices[0]?.id);
const { data } = useGetUsenetInfo({ serviceId: selectedServiceId! });
useEffect(() => {
if (!selectedServiceId && downloadServices.length) {
setSelectedService(downloadServices[0].id);
}
}, [downloadServices, selectedServiceId]);
const { mutate: pause } = usePauseUsenetQueue({ serviceId: selectedServiceId! });
const { mutate: resume } = useResumeUsenetQueue({ serviceId: selectedServiceId! });
if (downloadServices.length === 0) {
return (
<HomarrCardWrapper className={className}>
<Stack>
<Title order={3}>{t('card.errors.noDownloadClients.title')}</Title>
<Group>
<Text>{t('card.errors.noDownloadClients.text')}</Text>
</Group>
</Stack>
</HomarrCardWrapper>
);
}
if (!selectedServiceId) {
return null;
}
const { ref, width, height } = useElementSize();
const MIN_WIDTH_MOBILE = useMantineTheme().breakpoints.xs;
return (
<HomarrCardWrapper className={className}>
<Tabs keepMounted={false} defaultValue="queue">
<Tabs.List ref={ref} mb="md" style={{ flex: 1 }} grow>
<Tabs.Tab value="queue">{t('tabs.queue')}</Tabs.Tab>
<Tabs.Tab value="history">{t('tabs.history')}</Tabs.Tab>
{data && (
<Group position="right" ml="auto">
{width > MIN_WIDTH_MOBILE && (
<>
<Badge>{humanFileSize(data?.speed)}/s</Badge>
<Badge>
{t('info.sizeLeft')}: {humanFileSize(data?.sizeLeft)}
</Badge>
</>
)}
</Group>
)}
</Tabs.List>
{downloadServices.length > 1 && (
<Select
value={selectedServiceId}
onChange={setSelectedService}
ml="xs"
data={downloadServices.map((service) => ({ value: service.id, label: service.name }))}
/>
)}
<Tabs.Panel value="queue">
<UsenetQueueList serviceId={selectedServiceId} />
{!data ? null : data.paused ? (
<Button uppercase onClick={() => resume()} radius="xl" size="xs" fullWidth mt="sm">
<IconPlayerPlay size={12} style={{ marginRight: 5 }} /> {t('info.paused')}
</Button>
) : (
<Button uppercase onClick={() => pause()} radius="xl" size="xs" fullWidth mt="sm">
<IconPlayerPause size={12} style={{ marginRight: 5 }} />{' '}
{dayjs.duration(data.eta, 's').format('HH:mm')}
</Button>
)}
</Tabs.Panel>
<Tabs.Panel value="history" style={{ display: 'flex', flexDirection: 'column' }}>
<UsenetHistoryList serviceId={selectedServiceId} />
</Tabs.Panel>
</Tabs>
</HomarrCardWrapper>
);
};

View File

@@ -4,21 +4,23 @@ import {
Code, Code,
Group, Group,
Pagination, Pagination,
ScrollArea,
Skeleton, Skeleton,
Table, Table,
Text, Text,
Title, Title,
Tooltip, Tooltip,
} from '@mantine/core'; } from '@mantine/core';
import { useElementSize } from '@mantine/hooks';
import { IconAlertCircle } from '@tabler/icons'; import { IconAlertCircle } from '@tabler/icons';
import { AxiosError } from 'axios'; import { AxiosError } from 'axios';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { FunctionComponent, useState } from 'react'; import { FunctionComponent, useState } from 'react';
import { useGetUsenetHistory } from '../../tools/hooks/api'; import { useGetUsenetHistory } from '../../../../tools/hooks/api';
import { humanFileSize } from '../../tools/humanFileSize'; import { humanFileSize } from '../../../../tools/humanFileSize';
import { parseDuration } from '../../tools/parseDuration'; import { parseDuration } from '../../../../tools/parseDuration';
dayjs.extend(duration); dayjs.extend(duration);
@@ -32,6 +34,8 @@ export const UsenetHistoryList: FunctionComponent<UsenetHistoryListProps> = ({ s
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const { t } = useTranslation(['modules/usenet', 'common']); const { t } = useTranslation(['modules/usenet', 'common']);
const { ref, width, height } = useElementSize();
const durationBreakpoint = 400;
const { data, isLoading, isError, error } = useGetUsenetHistory({ const { data, isLoading, isError, error } = useGetUsenetHistory({
limit: PAGE_SIZE, limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE, offset: (page - 1) * PAGE_SIZE,
@@ -78,46 +82,47 @@ export const UsenetHistoryList: FunctionComponent<UsenetHistoryListProps> = ({ s
return ( return (
<> <>
<Table highlightOnHover style={{ tableLayout: 'fixed' }}> <ScrollArea style={{ flex: 1 }}>
<colgroup> <Table highlightOnHover style={{ tableLayout: 'fixed' }} ref={ref}>
<col span={1} /> <thead>
<col span={1} style={{ width: 100 }} /> <tr>
<col span={1} style={{ width: 200 }} /> <th>{t('modules/usenet:history.header.name')}</th>
</colgroup> <th style={{ width: 100 }}>{t('modules/usenet:history.header.size')}</th>
<thead> {durationBreakpoint < width ? (
<tr> <th style={{ width: 200 }}>{t('modules/usenet:history.header.duration')}</th>
<th>{t('modules/usenet:history.header.name')}</th> ) : null}
<th>{t('modules/usenet:history.header.size')}</th>
<th>{t('modules/usenet:history.header.duration')}</th>
</tr>
</thead>
<tbody>
{data.items.map((history) => (
<tr key={history.id}>
<td>
<Tooltip position="top" label={history.name}>
<Text
size="xs"
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{history.name}
</Text>
</Tooltip>
</td>
<td>
<Text size="xs">{humanFileSize(history.size)}</Text>
</td>
<td>
<Text size="xs">{parseDuration(history.time, t)}</Text>
</td>
</tr> </tr>
))} </thead>
</tbody> <tbody>
</Table> {data.items.map((history) => (
<tr key={history.id}>
<td>
<Tooltip position="top" label={history.name}>
<Text
size="xs"
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{history.name}
</Text>
</Tooltip>
</td>
<td>
<Text size="xs">{humanFileSize(history.size)}</Text>
</td>
{durationBreakpoint < width ? (
<td>
<Text size="xs">{parseDuration(history.time, t)}</Text>
</td>
) : null}
</tr>
))}
</tbody>
</Table>
</ScrollArea>
{totalPages > 1 && ( {totalPages > 1 && (
<Pagination <Pagination
size="sm" size="sm"

View File

@@ -0,0 +1,187 @@
import {
ActionIcon,
Alert,
Center,
Code,
Group,
Pagination,
Progress,
ScrollArea,
Skeleton,
Table,
Text,
Title,
Tooltip,
useMantineTheme,
} from '@mantine/core';
import { useElementSize } from '@mantine/hooks';
import { IconAlertCircle, IconPlayerPause, IconPlayerPlay } from '@tabler/icons';
import { AxiosError } from 'axios';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTranslation } from 'next-i18next';
import { FunctionComponent, useState } from 'react';
import { useGetUsenetDownloads } from '../../../../tools/hooks/api';
import { humanFileSize } from '../../../../tools/humanFileSize';
dayjs.extend(duration);
interface UsenetQueueListProps {
serviceId: string;
}
const PAGE_SIZE = 10;
export const UsenetQueueList: FunctionComponent<UsenetQueueListProps> = ({ serviceId }) => {
const theme = useMantineTheme();
const { t } = useTranslation('modules/usenet');
const progressbarBreakpoint = theme.breakpoints.xs;
const progressBreakpoint = 400;
const sizeBreakpoint = 300;
const { ref, width, height } = useElementSize();
const [page, setPage] = useState(1);
const { data, isLoading, isError, error } = useGetUsenetDownloads({
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
serviceId,
});
const totalPages = Math.ceil((data?.total || 1) / PAGE_SIZE);
if (isLoading) {
return (
<>
<Skeleton height={40} mt={10} />
<Skeleton height={40} mt={10} />
<Skeleton height={40} mt={10} />
</>
);
}
if (isError) {
return (
<Group position="center">
<Alert
icon={<IconAlertCircle size={16} />}
my="lg"
title={t('queue.error.title')}
color="red"
radius="md"
>
{t('queue.error.message')}
<Code mt="sm" block>
{(error as AxiosError)?.response?.data as string}
</Code>
</Alert>
</Group>
);
}
if (!data || data.items.length <= 0) {
return (
<Center style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Title order={3}>{t('queue.empty')}</Title>
</Center>
);
}
return (
<>
<ScrollArea style={{ flex: 1 }}>
<Table highlightOnHover style={{ tableLayout: 'fixed' }} ref={ref}>
<thead>
<tr>
<th style={{ width: 32 }} />
<th style={{ width: '75%' }}>{t('queue.header.name')}</th>
{sizeBreakpoint < width ? (
<th style={{ width: 100 }}>{t('queue.header.size')}</th>
) : null}
<th style={{ width: 60 }}>{t('queue.header.eta')}</th>
{progressBreakpoint < width ? (
<th style={{ width: progressbarBreakpoint > width ? 100 : 200 }}>
{t('queue.header.progress')}
</th>
) : null}
</tr>
</thead>
<tbody>
{data.items.map((nzb) => (
<tr key={nzb.id}>
<td>
{nzb.state === 'paused' ? (
<Tooltip label="NOT IMPLEMENTED">
<ActionIcon color="gray" variant="subtle" radius="xl" size="sm">
<IconPlayerPlay size="16" />
</ActionIcon>
</Tooltip>
) : (
<Tooltip label="NOT IMPLEMENTED">
<ActionIcon color="primary" variant="subtle" radius="xl" size="sm">
<IconPlayerPause size="16" />
</ActionIcon>
</Tooltip>
)}
</td>
<td>
<Tooltip position="top" label={nzb.name}>
<Text
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
size="xs"
color={nzb.state === 'paused' ? 'dimmed' : undefined}
>
{nzb.name}
</Text>
</Tooltip>
</td>
{sizeBreakpoint < width ? (
<td>
<Text size="xs">{humanFileSize(nzb.size)}</Text>
</td>
) : null}
<td>
{nzb.eta <= 0 ? (
<Text size="xs" color="dimmed">
{t('queue.paused')}
</Text>
) : (
<Text size="xs">{dayjs.duration(nzb.eta, 's').format('H:mm:ss')}</Text>
)}
</td>
{progressBreakpoint < width ? (
<td style={{ display: 'flex', alignItems: 'center' }}>
<Text mr="sm" style={{ whiteSpace: 'nowrap' }}>
{nzb.progress.toFixed(1)}%
</Text>
{width > progressbarBreakpoint ? (
<Progress
radius="lg"
color={nzb.eta > 0 ? theme.primaryColor : 'lightgrey'}
value={nzb.progress}
size="lg"
style={{ width: '100%' }}
/>
) : null}
</td>
) : null}
</tr>
))}
</tbody>
</Table>
</ScrollArea>
{totalPages > 1 && (
<Pagination
size="sm"
position="center"
mt="md"
total={totalPages}
page={page}
onChange={setPage}
/>
)}
</>
);
};

View File

@@ -3,6 +3,7 @@ import { CalendarTile } from './Calendar/CalendarTile';
import { ClockTile } from './Clock/ClockTile'; import { ClockTile } from './Clock/ClockTile';
import { EmptyTile } from './EmptyTile'; import { EmptyTile } from './EmptyTile';
import { ServiceTile } from './Service/ServiceTile'; import { ServiceTile } from './Service/ServiceTile';
import { UseNetTile } from './UseNet/UseNetTile';
import { WeatherTile } from './Weather/WeatherTile'; import { WeatherTile } from './Weather/WeatherTile';
/*import { CalendarTile } from './calendar'; /*import { CalendarTile } from './calendar';
import { ClockTile } from './clock'; import { ClockTile } from './clock';
@@ -63,7 +64,7 @@ export const Tiles: TileDefinitionProps = {
maxHeight: 12, maxHeight: 12,
}, },
useNet: { useNet: {
component: EmptyTile, //CalendarTile, component: UseNetTile, //CalendarTile,
minWidth: 4, minWidth: 4,
maxWidth: 12, maxWidth: 12,
minHeight: 5, minHeight: 5,

View File

@@ -17,11 +17,11 @@ import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration';
import { useElementSize } from '@mantine/hooks'; import { useElementSize } from '@mantine/hooks';
import { IModule } from '../ModuleTypes'; import { IModule } from '../ModuleTypes';
import { UsenetQueueList } from './UsenetQueueList'; import { UsenetQueueList } from '../../components/Dashboard/Tiles/UseNet/UsenetQueueList';
import { UsenetHistoryList } from './UsenetHistoryList';
import { useGetServiceByType } from '../../tools/hooks/useGetServiceByType'; import { useGetServiceByType } from '../../tools/hooks/useGetServiceByType';
import { useGetUsenetInfo, usePauseUsenetQueue, useResumeUsenetQueue } from '../../tools/hooks/api'; import { useGetUsenetInfo, usePauseUsenetQueue, useResumeUsenetQueue } from '../../tools/hooks/api';
import { humanFileSize } from '../../tools/humanFileSize'; import { humanFileSize } from '../../tools/humanFileSize';
import { UsenetHistoryList } from '../../components/Dashboard/Tiles/UseNet/UsenetHistoryList';
dayjs.extend(duration); dayjs.extend(duration);

View File

@@ -1,167 +0,0 @@
import {
ActionIcon,
Alert,
Center,
Code,
Group,
Pagination,
Progress,
Skeleton,
Table,
Text,
Title,
Tooltip,
useMantineTheme,
} from '@mantine/core';
import { IconAlertCircle, IconPlayerPause, IconPlayerPlay } from '@tabler/icons';
import { AxiosError } from 'axios';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTranslation } from 'next-i18next';
import { FunctionComponent, useState } from 'react';
import { useGetUsenetDownloads } from '../../tools/hooks/api';
import { humanFileSize } from '../../tools/humanFileSize';
dayjs.extend(duration);
interface UsenetQueueListProps {
serviceId: string;
}
const PAGE_SIZE = 10;
export const UsenetQueueList: FunctionComponent<UsenetQueueListProps> = ({ serviceId }) => {
const theme = useMantineTheme();
const { t } = useTranslation('modules/usenet');
const [page, setPage] = useState(1);
const { data, isLoading, isError, error } = useGetUsenetDownloads({
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
serviceId,
});
const totalPages = Math.ceil((data?.total || 1) / PAGE_SIZE);
if (isLoading) {
return (
<>
<Skeleton height={40} mt={10} />
<Skeleton height={40} mt={10} />
<Skeleton height={40} mt={10} />
</>
);
}
if (isError) {
return (
<Group position="center">
<Alert
icon={<IconAlertCircle size={16} />}
my="lg"
title={t('queue.error.title')}
color="red"
radius="md"
>
{t('queue.error.message')}
<Code mt="sm" block>
{(error as AxiosError)?.response?.data as string}
</Code>
</Alert>
</Group>
);
}
if (!data || data.items.length <= 0) {
return (
<Center style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Title order={3}>{t('queue.empty')}</Title>
</Center>
);
}
return (
<>
<Table highlightOnHover style={{ tableLayout: 'fixed' }}>
<thead>
<tr>
<th style={{ width: 50 }} />
<th style={{ width: '75%' }}>{t('queue.header.name')}</th>
<th style={{ width: 100 }}>{t('queue.header.size')}</th>
<th style={{ width: 100 }}>{t('queue.header.eta')}</th>
<th style={{ width: 200 }}>{t('queue.header.progress')}</th>
</tr>
</thead>
<tbody>
{data.items.map((nzb) => (
<tr key={nzb.id}>
<td>
{nzb.state === 'paused' ? (
<Tooltip label="NOT IMPLEMENTED">
<ActionIcon color="gray" variant="subtle" radius="xl" size="sm">
<IconPlayerPlay size="16" />
</ActionIcon>
</Tooltip>
) : (
<Tooltip label="NOT IMPLEMENTED">
<ActionIcon color="primary" variant="subtle" radius="xl" size="sm">
<IconPlayerPause size="16" />
</ActionIcon>
</Tooltip>
)}
</td>
<td>
<Tooltip position="top" label={nzb.name}>
<Text
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
size="xs"
color={nzb.state === 'paused' ? 'dimmed' : undefined}
>
{nzb.name}
</Text>
</Tooltip>
</td>
<td>
<Text size="xs">{humanFileSize(nzb.size)}</Text>
</td>
<td>
{nzb.eta <= 0 ? (
<Text size="xs" color="dimmed">
{t('queue.paused')}
</Text>
) : (
<Text size="xs">{dayjs.duration(nzb.eta, 's').format('H:mm:ss')}</Text>
)}
</td>
<td style={{ display: 'flex', alignItems: 'center' }}>
<Text mr="sm" style={{ whiteSpace: 'nowrap' }}>
{nzb.progress.toFixed(1)}%
</Text>
<Progress
radius="lg"
color={nzb.eta > 0 ? theme.primaryColor : 'lightgrey'}
value={nzb.progress}
size="lg"
style={{ width: '100%' }}
/>
</td>
</tr>
))}
</tbody>
</Table>
{totalPages > 1 && (
<Pagination
size="sm"
position="center"
mt="md"
total={totalPages}
page={page}
onChange={setPage}
/>
)}
</>
);
};

View File

@@ -4,11 +4,11 @@ import duration from 'dayjs/plugin/duration';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { Client } from 'sabnzbd-api'; import { Client } from 'sabnzbd-api';
import { UsenetHistoryItem } from '../../../../modules'; import { UsenetHistoryItem } from '../../../../modules';
import { getConfig } from '../../../../tools/getConfig';
import { getServiceById } from '../../../../tools/hooks/useGetServiceByType'; import { getServiceById } from '../../../../tools/hooks/useGetServiceByType';
import { Config } from '../../../../tools/types'; import { Config } from '../../../../tools/types';
import { NzbgetHistoryItem } from './nzbget/types'; import { NzbgetHistoryItem } from './nzbget/types';
import { NzbgetClient } from './nzbget/nzbget-client'; import { NzbgetClient } from './nzbget/nzbget-client';
import { getConfig } from '../../../../tools/config/getConfig';
dayjs.extend(duration); dayjs.extend(duration);
@@ -26,24 +26,24 @@ export interface UsenetHistoryResponse {
async function Get(req: NextApiRequest, res: NextApiResponse) { async function Get(req: NextApiRequest, res: NextApiResponse) {
try { try {
const configName = getCookie('config-name', { req }); const configName = getCookie('config-name', { req });
const { config }: { config: Config } = getConfig(configName?.toString() ?? 'default').props; const config = getConfig(configName?.toString() ?? 'default');
const { limit, offset, serviceId } = req.query as any as UsenetHistoryRequestParams; const { limit, offset, serviceId } = req.query as any as UsenetHistoryRequestParams;
const service = getServiceById(config, serviceId); const service = config.services.find((x) => x.id === serviceId);
if (!service) { if (!service) {
throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`); throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`);
} }
let response: UsenetHistoryResponse; let response: UsenetHistoryResponse;
switch (service.type) { switch (service.integration?.type) {
case 'NZBGet': { case 'nzbGet': {
const url = new URL(service.url); const url = new URL(service.url);
const options = { const options = {
host: url.hostname, host: url.hostname,
port: url.port, port: url.port,
login: service.username, login: service.integration.properties.username,
hash: service.password, hash: service.integration.properties.password,
}; };
const nzbGet = NzbgetClient(options); const nzbGet = NzbgetClient(options);
@@ -76,14 +76,17 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
}; };
break; break;
} }
case 'Sabnzbd': { case 'sabnzbd': {
const { origin } = new URL(service.url); const { origin } = new URL(service.url);
if (!service.apiKey) { if (!service.integration.properties.apiKey) {
throw new Error(`API Key for service "${service.name}" is missing`); throw new Error(`API Key for service "${service.name}" is missing`);
} }
const history = await new Client(origin, service.apiKey).history(offset, limit); const history = await new Client(origin, service.integration.properties.apiKey).history(
offset,
limit
);
const items: UsenetHistoryItem[] = history.slots.map((slot) => ({ const items: UsenetHistoryItem[] = history.slots.map((slot) => ({
id: slot.nzo_id, id: slot.nzo_id,
@@ -99,7 +102,7 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
break; break;
} }
default: default:
throw new Error(`Service type "${service.type}" unrecognized.`); throw new Error(`Service type "${service.integration?.type}" unrecognized.`);
} }
return res.status(200).json(response); return res.status(200).json(response);

View File

@@ -3,11 +3,11 @@ import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { Client } from 'sabnzbd-api'; import { Client } from 'sabnzbd-api';
import { getConfig } from '../../../../tools/getConfig';
import { getServiceById } from '../../../../tools/hooks/useGetServiceByType'; import { getServiceById } from '../../../../tools/hooks/useGetServiceByType';
import { Config } from '../../../../tools/types'; import { Config } from '../../../../tools/types';
import { NzbgetStatus } from './nzbget/types'; import { NzbgetStatus } from './nzbget/types';
import { NzbgetClient } from './nzbget/nzbget-client'; import { NzbgetClient } from './nzbget/nzbget-client';
import { getConfig } from '../../../../tools/config/getConfig';
dayjs.extend(duration); dayjs.extend(duration);
@@ -25,24 +25,24 @@ export interface UsenetInfoResponse {
async function Get(req: NextApiRequest, res: NextApiResponse) { async function Get(req: NextApiRequest, res: NextApiResponse) {
try { try {
const configName = getCookie('config-name', { req }); const configName = getCookie('config-name', { req });
const { config }: { config: Config } = getConfig(configName?.toString() ?? 'default').props; const config = getConfig(configName?.toString() ?? 'default');
const { serviceId } = req.query as any as UsenetInfoRequestParams; const { serviceId } = req.query as any as UsenetInfoRequestParams;
const service = getServiceById(config, serviceId); const service = config.services.find((x) => x.id === serviceId);
if (!service) { if (!service) {
throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`); throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`);
} }
let response: UsenetInfoResponse; let response: UsenetInfoResponse;
switch (service.type) { switch (service.integration?.type) {
case 'NZBGet': { case 'nzbGet': {
const url = new URL(service.url); const url = new URL(service.url);
const options = { const options = {
host: url.hostname, host: url.hostname,
port: url.port, port: url.port,
login: service.username, login: service.integration.properties.username,
hash: service.password, hash: service.integration.properties.password,
}; };
const nzbGet = NzbgetClient(options); const nzbGet = NzbgetClient(options);
@@ -71,14 +71,14 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
}; };
break; break;
} }
case 'Sabnzbd': { case 'sabnzbd': {
if (!service.apiKey) { if (!service.integration.properties.apiKey) {
throw new Error(`API Key for service "${service.name}" is missing`); throw new Error(`API Key for service "${service.name}" is missing`);
} }
const { origin } = new URL(service.url); const { origin } = new URL(service.url);
const queue = await new Client(origin, service.apiKey).queue(0, -1); const queue = await new Client(origin, service.integration.properties.apiKey).queue(0, -1);
const [hours, minutes, seconds] = queue.timeleft.split(':'); const [hours, minutes, seconds] = queue.timeleft.split(':');
const eta = dayjs.duration({ const eta = dayjs.duration({
@@ -96,7 +96,7 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
break; break;
} }
default: default:
throw new Error(`Service type "${service.type}" unrecognized.`); throw new Error(`Service type "${service.integration?.type}" unrecognized.`);
} }
return res.status(200).json(response); return res.status(200).json(response);

View File

@@ -3,9 +3,7 @@ import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { Client } from 'sabnzbd-api'; import { Client } from 'sabnzbd-api';
import { getConfig } from '../../../../tools/getConfig'; import { getConfig } from '../../../../tools/config/getConfig';
import { getServiceById } from '../../../../tools/hooks/useGetServiceByType';
import { Config } from '../../../../tools/types';
import { NzbgetClient } from './nzbget/nzbget-client'; import { NzbgetClient } from './nzbget/nzbget-client';
dayjs.extend(duration); dayjs.extend(duration);
@@ -17,24 +15,24 @@ export interface UsenetPauseRequestParams {
async function Post(req: NextApiRequest, res: NextApiResponse) { async function Post(req: NextApiRequest, res: NextApiResponse) {
try { try {
const configName = getCookie('config-name', { req }); const configName = getCookie('config-name', { req });
const { config }: { config: Config } = getConfig(configName?.toString() ?? 'default').props; const config = getConfig(configName?.toString() ?? 'default');
const { serviceId } = req.query as any as UsenetPauseRequestParams; const { serviceId } = req.query as any as UsenetPauseRequestParams;
const service = getServiceById(config, serviceId); const service = config.services.find((x) => x.id === serviceId);
if (!service) { if (!service) {
throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`); throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`);
} }
let result; let result;
switch (service.type) { switch (service.integration?.type) {
case 'NZBGet': { case 'nzbGet': {
const url = new URL(service.url); const url = new URL(service.url);
const options = { const options = {
host: url.hostname, host: url.hostname,
port: url.port, port: url.port,
login: service.username, login: service.integration.properties.username,
hash: service.password, hash: service.integration.properties.password,
}; };
const nzbGet = NzbgetClient(options); const nzbGet = NzbgetClient(options);
@@ -50,18 +48,18 @@ async function Post(req: NextApiRequest, res: NextApiResponse) {
}); });
break; break;
} }
case 'Sabnzbd': { case 'sabnzbd': {
if (!service.apiKey) { if (!service.integration.properties.apiKey) {
throw new Error(`API Key for service "${service.name}" is missing`); throw new Error(`API Key for service "${service.name}" is missing`);
} }
const { origin } = new URL(service.url); const { origin } = new URL(service.url);
result = await new Client(origin, service.apiKey).queuePause(); result = await new Client(origin, service.integration.properties.apiKey).queuePause();
break; break;
} }
default: default:
throw new Error(`Service type "${service.type}" unrecognized.`); throw new Error(`Service type "${service.integration?.type}" unrecognized.`);
} }
return res.status(200).json(result); return res.status(200).json(result);

View File

@@ -4,9 +4,7 @@ import duration from 'dayjs/plugin/duration';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { Client } from 'sabnzbd-api'; import { Client } from 'sabnzbd-api';
import { UsenetQueueItem } from '../../../../modules'; import { UsenetQueueItem } from '../../../../modules';
import { getConfig } from '../../../../tools/getConfig'; import { getConfig } from '../../../../tools/config/getConfig';
import { getServiceById } from '../../../../tools/hooks/useGetServiceByType';
import { Config } from '../../../../tools/types';
import { NzbgetClient } from './nzbget/nzbget-client'; import { NzbgetClient } from './nzbget/nzbget-client';
import { NzbgetQueueItem, NzbgetStatus } from './nzbget/types'; import { NzbgetQueueItem, NzbgetStatus } from './nzbget/types';
@@ -26,24 +24,24 @@ export interface UsenetQueueResponse {
async function Get(req: NextApiRequest, res: NextApiResponse) { async function Get(req: NextApiRequest, res: NextApiResponse) {
try { try {
const configName = getCookie('config-name', { req }); const configName = getCookie('config-name', { req });
const { config }: { config: Config } = getConfig(configName?.toString() ?? 'default').props; const config = getConfig(configName?.toString() ?? 'default');
const { limit, offset, serviceId } = req.query as any as UsenetQueueRequestParams; const { limit, offset, serviceId } = req.query as any as UsenetQueueRequestParams;
const service = getServiceById(config, serviceId); const service = config.services.find((x) => x.id === serviceId);
if (!service) { if (!service) {
throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`); throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`);
} }
let response: UsenetQueueResponse; let response: UsenetQueueResponse;
switch (service.type) { switch (service.integration?.type) {
case 'NZBGet': { case 'nzbGet': {
const url = new URL(service.url); const url = new URL(service.url);
const options = { const options = {
host: url.hostname, host: url.hostname,
port: url.port, port: url.port,
login: service.username, login: service.integration.properties.username,
hash: service.password, hash: service.integration.properties.password,
}; };
const nzbGet = NzbgetClient(options); const nzbGet = NzbgetClient(options);
@@ -92,13 +90,16 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
}; };
break; break;
} }
case 'Sabnzbd': { case 'sabnzbd': {
if (!service.apiKey) { if (!service.integration.properties.apiKey) {
throw new Error(`API Key for service "${service.name}" is missing`); throw new Error(`API Key for service "${service.name}" is missing`);
} }
const { origin } = new URL(service.url); const { origin } = new URL(service.url);
const queue = await new Client(origin, service.apiKey).queue(offset, limit); const queue = await new Client(origin, service.integration.properties.apiKey).queue(
offset,
limit
);
const items: UsenetQueueItem[] = queue.slots.map((slot) => { const items: UsenetQueueItem[] = queue.slots.map((slot) => {
const [hours, minutes, seconds] = slot.timeleft.split(':'); const [hours, minutes, seconds] = slot.timeleft.split(':');
@@ -125,7 +126,7 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
break; break;
} }
default: default:
throw new Error(`Service type "${service.type}" unrecognized.`); throw new Error(`Service type "${service.integration?.type}" unrecognized.`);
} }
return res.status(200).json(response); return res.status(200).json(response);

View File

@@ -3,7 +3,7 @@ import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { Client } from 'sabnzbd-api'; import { Client } from 'sabnzbd-api';
import { getConfig } from '../../../../tools/getConfig'; import { getConfig } from '../../../../tools/config/getConfig';
import { getServiceById } from '../../../../tools/hooks/useGetServiceByType'; import { getServiceById } from '../../../../tools/hooks/useGetServiceByType';
import { Config } from '../../../../tools/types'; import { Config } from '../../../../tools/types';
import { NzbgetClient } from './nzbget/nzbget-client'; import { NzbgetClient } from './nzbget/nzbget-client';
@@ -18,24 +18,24 @@ export interface UsenetResumeRequestParams {
async function Post(req: NextApiRequest, res: NextApiResponse) { async function Post(req: NextApiRequest, res: NextApiResponse) {
try { try {
const configName = getCookie('config-name', { req }); const configName = getCookie('config-name', { req });
const { config }: { config: Config } = getConfig(configName?.toString() ?? 'default').props; const config = getConfig(configName?.toString() ?? 'default');
const { serviceId } = req.query as any as UsenetResumeRequestParams; const { serviceId } = req.query as any as UsenetResumeRequestParams;
const service = getServiceById(config, serviceId); const service = config.services.find((x) => x.id === serviceId);
if (!service) { if (!service) {
throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`); throw new Error(`Service with ID "${req.query.serviceId}" could not be found.`);
} }
let result; let result;
switch (service.type) { switch (service.integration?.type) {
case 'NZBGet': { case 'nzbGet': {
const url = new URL(service.url); const url = new URL(service.url);
const options = { const options = {
host: url.hostname, host: url.hostname,
port: url.port, port: url.port,
login: service.username, login: service.integration.properties.username,
hash: service.password, hash: service.integration.properties.password,
}; };
const nzbGet = NzbgetClient(options); const nzbGet = NzbgetClient(options);
@@ -51,18 +51,18 @@ async function Post(req: NextApiRequest, res: NextApiResponse) {
}); });
break; break;
} }
case 'Sabnzbd': { case 'sabnzbd': {
if (!service.apiKey) { if (!service.integration.properties.apiKey) {
throw new Error(`API Key for service "${service.name}" is missing`); throw new Error(`API Key for service "${service.name}" is missing`);
} }
const { origin } = new URL(service.url); const { origin } = new URL(service.url);
result = await new Client(origin, service.apiKey).queueResume(); result = await new Client(origin, service.integration.properties.apiKey).queueResume();
break; break;
} }
default: default:
throw new Error(`Service type "${service.type}" unrecognized.`); throw new Error(`Service type "${service.integration?.type}" unrecognized.`);
} }
return res.status(200).json(result); return res.status(200).json(result);

View File

@@ -24,11 +24,12 @@ interface ServiceAppearanceType {
iconUrl: string; iconUrl: string;
} }
type ServiceIntegrationType = export type ServiceIntegrationType =
| ServiceIntegrationApiKeyType | ServiceIntegrationApiKeyType
| ServiceIntegrationPasswordType | ServiceIntegrationPasswordType
| ServiceIntegrationUsernamePasswordType; | ServiceIntegrationUsernamePasswordType;
// TODO: add nzbGet somewhere
export interface ServiceIntegrationApiKeyType { export interface ServiceIntegrationApiKeyType {
type: 'readarr' | 'radarr' | 'sonarr' | 'lidarr' | 'sabnzbd' | 'jellyseerr' | 'overseerr'; type: 'readarr' | 'radarr' | 'sonarr' | 'lidarr' | 'sabnzbd' | 'jellyseerr' | 'overseerr';
properties: { properties: {
@@ -44,7 +45,7 @@ interface ServiceIntegrationPasswordType {
} }
interface ServiceIntegrationUsernamePasswordType { interface ServiceIntegrationUsernamePasswordType {
type: 'qBittorrent' | 'transmission'; type: 'qBittorrent' | 'transmission' | 'nzbGet';
properties: { properties: {
username?: string; username?: string;
password?: string; password?: string;