Skip to content

Commit

Permalink
fix: javacript errors and mistakes
Browse files Browse the repository at this point in the history
  • Loading branch information
SeDemal committed Jul 31, 2024
1 parent 6700fce commit 33b5a85
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 82 deletions.
2 changes: 1 addition & 1 deletion packages/common/src/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const randomInt = (min: number, max: number) => {
export const humanFileSize = (size: number) => {
if (!Number.isInteger(size)) return NaN;
let count = 0;
while (true) {
while (count < siRanges.length) {
const tempSize = size / Math.pow(1024, count);
if (tempSize < 1024 || count === siRanges.length - 1) {
return tempSize.toFixed(Math.min(count, 1)) + siRanges[count];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class DelugeIntegration extends DownloadClientIntegration {
...(torrent as { completed_time: number } & typeof torrent),
id,
}));
const paused = torrents.find(({ state }) => this.getTorrentState(state) !== "paused") === undefined;
const paused = torrents.find(({ state }) => DelugeIntegration.getTorrentState(state) !== "paused") === undefined;
const status: DownloadClientStatus = {
paused,
rates: {
Expand All @@ -33,7 +33,7 @@ export class DelugeIntegration extends DownloadClientIntegration {
type,
};
const items = torrents.map((torrent): DownloadClientItem => {
const state = this.getTorrentState(torrent.state);
const state = DelugeIntegration.getTorrentState(torrent.state);
return {
type,
id: torrent.id,
Expand Down Expand Up @@ -96,7 +96,7 @@ export class DelugeIntegration extends DownloadClientIntegration {
});
}

private getTorrentState(state: string): DownloadClientItem["state"] {
private static getTorrentState(state: string): DownloadClientItem["state"] {
switch (state) {
case "Queued":
case "Checking":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class NzbGetIntegration extends DownloadClientIntegration {
};
const items = queue
.map((file): DownloadClientItem => {
const state = this.getNzbQueueState(file.Status);
const state = NzbGetIntegration.getNzbQueueState(file.Status);
return {
type,
id: file.NZBID.toString(),
Expand All @@ -42,7 +42,7 @@ export class NzbGetIntegration extends DownloadClientIntegration {
})
.concat(
history.map((file, index): DownloadClientItem => {
const state = this.getNzbHistoryState(file.ScriptStatus);
const state = NzbGetIntegration.getNzbHistoryState(file.ScriptStatus);
return {
type,
id: file.NZBID.toString(),
Expand Down Expand Up @@ -98,7 +98,7 @@ export class NzbGetIntegration extends DownloadClientIntegration {
return new NzbGetClient(url);
}

private getNzbQueueState(status: string): DownloadClientItem["state"] {
private static getNzbQueueState(status: string): DownloadClientItem["state"] {
switch (status) {
case "QUEUED":
return "queued";
Expand All @@ -109,7 +109,7 @@ export class NzbGetIntegration extends DownloadClientIntegration {
}
}

private getNzbHistoryState(status: string): DownloadClientItem["state"] {
private static getNzbHistoryState(status: string): DownloadClientItem["state"] {
switch (status) {
case "FAILURE":
return "failed";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ export class QBitTorrentIntegration extends DownloadClientIntegration {
({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }),
{ down: 0, up: 0 },
);
const paused = torrents.find(({ state }) => this.getTorrentState(state) !== "paused") === undefined;
const paused = torrents.find(({ state }) => QBitTorrentIntegration.getTorrentState(state) !== "paused") === undefined;
const status: DownloadClientStatus = { paused, rates, type };
const items = torrents.map((torrent): DownloadClientItem => {
const state = this.getTorrentState(torrent.state);
const state = QBitTorrentIntegration.getTorrentState(torrent.state);
return {
type,
id: torrent.hash,
Expand Down Expand Up @@ -77,7 +77,7 @@ export class QBitTorrentIntegration extends DownloadClientIntegration {
});
}

private getTorrentState(state: string): DownloadClientItem["state"] {
private static getTorrentState(state: string): DownloadClientItem["state"] {
switch (state) {
case "allocating":
case "checkingDL":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
};
const items = queue.slots
.map((slot): DownloadClientItem => {
const state = this.getNzbQueueState(slot.status);
const state = SabnzbdIntegration.getNzbQueueState(slot.status);
const times = slot.timeleft.split(":").reverse();
const time = dayjs
.duration({
Expand All @@ -52,7 +52,7 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
})
.concat(
history.slots.map((slot, index): DownloadClientItem => {
const state = this.getNzbHistoryState(slot.status);
const state = SabnzbdIntegration.getNzbHistoryState(slot.status);
return {
type,
id: slot.nzo_id,
Expand Down Expand Up @@ -109,12 +109,12 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
url.searchParams.append(key, value);
});
url.searchParams.append("apikey", this.getSecretValue("apiKey"));
return fetch(url)
return await fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
return response.json() as Promise<unknown>;
})
.catch((error) => {
if (error instanceof Error) {
Expand All @@ -125,7 +125,7 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
});
}

private getNzbQueueState(status: string): DownloadClientItem["state"] {
private static getNzbQueueState(status: string): DownloadClientItem["state"] {
switch (status) {
case "Queued":
return "queued";
Expand All @@ -136,7 +136,7 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
}
}

private getNzbHistoryState(status: string): DownloadClientItem["state"] {
private static getNzbHistoryState(status: string): DownloadClientItem["state"] {
switch (status) {
case "Completed":
return "completed";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export class TransmissionIntegration extends DownloadClientIntegration {
({ down, up }, { rateDownload, rateUpload }) => ({ down: down + rateDownload, up: up + rateUpload }),
{ down: 0, up: 0 },
);
const paused = torrents.find(({ status }) => this.getTorrentState(status) !== "paused") === undefined;
const paused = torrents.find(({ status }) => TransmissionIntegration.getTorrentState(status) !== "paused") === undefined;
const status: DownloadClientStatus = { paused, rates, type };
const items = torrents.map((torrent): DownloadClientItem => {
const state = this.getTorrentState(torrent.status);
const state = TransmissionIntegration.getTorrentState(torrent.status);
return {
type,
id: torrent.hashString,
Expand Down Expand Up @@ -78,7 +78,7 @@ export class TransmissionIntegration extends DownloadClientIntegration {
});
}

private getTorrentState(status: number): DownloadClientItem["state"] {
private static getTorrentState(status: number): DownloadClientItem["state"] {
switch (status) {
case 0:
return "paused";
Expand Down
56 changes: 32 additions & 24 deletions packages/widgets/src/downloads/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { useScopedI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";

//TODO:
// - NzbGet API not working I think
// - Data Subscription permission issues <- Need help
// - table tbody hide under thead and keep transparency <- Need help
// - Add integrations to shouldHide options <- Potential help needed
Expand Down Expand Up @@ -156,7 +157,7 @@ export default function DownloadClientsWidget({
(type === "torrent" &&
((progress === 1 &&
options.showCompletedTorrent &&
upSpeed! >= Number(options.activeTorrentThreshold) * 1024) ||
(upSpeed ?? 0) >= Number(options.activeTorrentThreshold) * 1024) ||
progress !== 1)) ||
(type === "usenet" && ((progress === 1 && options.showCompletedUsenet) || progress !== 1)),
)
Expand Down Expand Up @@ -199,7 +200,7 @@ export default function DownloadClientsWidget({
)
.reduce(
({ totalUp, totalDown }, { sent, size, progress }) => ({
totalUp: isTorrent ? totalUp! + sent! : undefined,
totalUp: isTorrent ? (totalUp ?? 0) + (sent ?? 0) : undefined,
totalDown: totalDown + size * progress,
}),
{ totalDown: 0, totalUp: isTorrent ? 0 : undefined },
Expand All @@ -211,7 +212,8 @@ export default function DownloadClientsWidget({
ratio: totalUp === undefined ? undefined : totalUp / totalDown,
...pair.data.status,
};
}).sort(({type: typeA},{type: typeB}) => typeA.length - typeB.length),
})
.sort(({ type: typeA }, { type: typeB }) => typeA.length - typeB.length),
[currentItems, integrationIds, options],
);

Expand Down Expand Up @@ -383,7 +385,7 @@ export default function DownloadClientsWidget({
sortUndefined: "last",
Cell: ({ cell }) => {
const downSpeed = cell.getValue<ExtendedDownloadClientItem["downSpeed"]>();
return <Text>{downSpeed !== undefined && humanFileSize(downSpeed) + "/s"}</Text>;
return <Text>{downSpeed !== undefined && humanFileSize(downSpeed)?.toString().concat("/s")}</Text>;
},
},
{
Expand Down Expand Up @@ -510,7 +512,7 @@ export default function DownloadClientsWidget({
sortUndefined: "last",
Cell: ({ cell }) => {
const upSpeed = cell.getValue<ExtendedDownloadClientItem["upSpeed"]>();
return upSpeed !== undefined && <Text>{humanFileSize(upSpeed) + "/s"}</Text>;
return upSpeed !== undefined && <Text>{humanFileSize(upSpeed)?.toString().concat("/s")}</Text>;
},
},
],
Expand Down Expand Up @@ -584,8 +586,8 @@ export default function DownloadClientsWidget({
.filter(({ integration: { kind } }) => ["qBittorrent", "deluge", "transmission"].includes(kind))
.reduce(
({ up, down }, { totalUp, totalDown }) => ({
up: up + totalUp!,
down: down + totalDown!,
up: up + (totalUp ?? 0),
down: down + (totalDown ?? 0),
}),
{ up: 0, down: 0 },
);
Expand Down Expand Up @@ -620,9 +622,9 @@ interface ItemInfoModalProps {
}

const ItemInfoModal = ({ items, currentIndex, opened, onClose }: ItemInfoModalProps) => {
const item = useMemo<ExtendedDownloadClientItem | undefined>(() => items[currentIndex], [currentIndex, opened]);
const item = useMemo<ExtendedDownloadClientItem | undefined>(() => items[currentIndex], [items, currentIndex, opened]);
const t = useScopedI18n("widget.downloads.states");
if (item === undefined) return;
if (item === undefined) return <></>;
return (
<Modal opened={opened} onClose={onClose} centered title={item.id} size="auto">
<Stack align="center">
Expand All @@ -636,11 +638,11 @@ const ItemInfoModal = ({ items, currentIndex, opened, onClose }: ItemInfoModalPr
<NormalizedLine itemKey="state" values={t(item.state)} />
<NormalizedLine
itemKey="upSpeed"
values={item.upSpeed === undefined ? undefined : humanFileSize(item.upSpeed) + "/s"}
values={item.upSpeed === undefined ? undefined : humanFileSize(item.upSpeed)?.toString().concat("/s")}
/>
<NormalizedLine
itemKey="downSpeed"
values={item.downSpeed === undefined ? undefined : humanFileSize(item.downSpeed) + "/s"}
values={item.downSpeed === undefined ? undefined : humanFileSize(item.downSpeed)?.toString().concat("/s")}
/>
<NormalizedLine itemKey="sent" values={item.sent === undefined ? undefined : humanFileSize(item.sent)} />
<NormalizedLine itemKey="received" values={humanFileSize(item.received)} />
Expand All @@ -652,7 +654,7 @@ const ItemInfoModal = ({ items, currentIndex, opened, onClose }: ItemInfoModalPr
)}
/>
<NormalizedLine itemKey="ratio" values={item.ratio} />
<NormalizedLine itemKey="added" values={item.added == undefined ? "unknown" : dayjs(item.added).format()} />
<NormalizedLine itemKey="added" values={item.added === undefined ? "unknown" : dayjs(item.added).format()} />
<NormalizedLine itemKey="time" values={dayjs().add(item.time).format()} />
<NormalizedLine itemKey="category" values={item.category} />
</Stack>
Expand All @@ -667,7 +669,7 @@ const NormalizedLine = ({
itemKey: Exclude<keyof ExtendedDownloadClientItem, "integration" | "actions" | "name" | "id">;
values?: number | string | string[];
}) => {
if (typeof values !== "number" && (values === undefined || values.length === 0)) return;
if (typeof values !== "number" && (values === undefined || values.length === 0)) return <></>;
const t = useScopedI18n("widget.downloads.items");
const tCommon = useScopedI18n("common");
const translatedKey = t(`${itemKey}.detailsTitle`);
Expand All @@ -686,7 +688,7 @@ const NormalizedLine = ({
{Array.isArray(values) ? (
<Stack>
{values.map((value) => (
<Text>{value}</Text>
<Text key={value}>{value}</Text>
))}
</Stack>
) : (
Expand All @@ -704,10 +706,10 @@ interface ClientsControlProps {
const ClientsControl = ({ clients, style }: ClientsControlProps) => {
const pausedIntegrations: string[] = [];
const activeIntegrations: string[] = [];
clients.map((client) =>
clients.forEach((client) =>
client.paused ? pausedIntegrations.push(client.integration.id) : activeIntegrations.push(client.integration.id),
);
const totalSpeed = humanFileSize(clients.reduce((count, { rates: { down } }) => count + down, 0)) + "/s";
const totalSpeed = humanFileSize(clients.reduce((count, { rates: { down } }) => count + down, 0))?.toString().concat("/s");
const { mutate: mutateResumeQueue } = clientApi.widget.downloads.resume.useMutation();
const { mutate: mutatePauseQueue } = clientApi.widget.downloads.pause.useMutation();
const [opened, { open, close }] = useDisclosure(false);
Expand Down Expand Up @@ -742,18 +744,24 @@ const ClientsControl = ({ clients, style }: ClientsControlProps) => {
<Stack gap={0} pt={5} h={60} justify="center" flex={1}>
{client.rates.up !== undefined ? (
<Group display="flex" justify="center" c="green" w="100%" gap={5}>
<Text flex={1} ta="right">{"↑ " + humanFileSize(client.rates.up) + "/s"}</Text>
<Text flex={1} ta="right">
{`↑ ${humanFileSize(client.rates.up)}/s`}
</Text>
<Text>{"-"}</Text>
<Text flex={1} ta="left">{humanFileSize(client.totalUp ?? 0)}</Text>
<Text flex={1} ta="left">
{humanFileSize(client.totalUp ?? 0)}
</Text>
</Group>
) : undefined}
<Text c="blue">
<Group display="flex" justify="center" c="blue" w="100%" gap={5}>
<Text flex={1} ta="right">{"↓ " + humanFileSize(client.rates.down) + "/s"}</Text>
<Text>{"-"}</Text>
<Text flex={1} ta="left">{humanFileSize(Math.floor(client.totalDown ?? 0))}</Text>
</Group>
</Text>
<Text flex={1} ta="right">
{`↓ ${humanFileSize(client.rates.down)}/s`}
</Text>
<Text>{"-"}</Text>
<Text flex={1} ta="left">
{humanFileSize(Math.floor(client.totalDown ?? 0))}
</Text>
</Group>
</Stack>
</Group>
</Paper>
Expand Down
3 changes: 2 additions & 1 deletion packages/widgets/src/downloads/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export const { definition, componentLoader, serverDataLoader } = createWidgetDef
step: 1,
}),
categoryFilter: factory.multiText({
//defaultValue: [] as string[];
defaultValue: [] as string[],
validate: z.string(),
}),
filterIsWhitelist: factory.switch({
defaultValue: false,
Expand Down
4 changes: 2 additions & 2 deletions packages/widgets/src/modals/widget-edit-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
z.object({
options: z.object(
objectEntries(widgetImports[innerProps.kind].definition.options).reduce(
(acc, [key, value]: [string, { validate?: z.ZodType<unknown> }]) => {
(acc, [key, value]: [string, { type: string, validate?: z.ZodType<unknown> }]) => {
if (value.validate) {
acc[key] = value.validate;
acc[key] = value.type === "multiText" ? z.array(value.validate).optional() : value.validate;
}

return acc;
Expand Down
Loading

0 comments on commit 33b5a85

Please sign in to comment.