Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/app/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export type Lang = keyof typeof langs
export type RawDictionary = typeof en.dict
export type Dictionary = i18n.Flatten<RawDictionary>

// English dictionary cache for fallback
// English dictionary cache for fallback.
let enDictCache: Dictionary | null = null

const fetchEnDict = async (): Promise<Dictionary> => {
Expand All @@ -50,22 +50,18 @@ const fetchEnDict = async (): Promise<Dictionary> => {
return enDictCache
}

// Fetch and flatten the dictionary, with English fallback
// Fetch and flatten the dictionary, with English fallback for new keys.
const fetchDictionary = async (locale: Lang): Promise<Dictionary> => {
try {
const dict: RawDictionary = (await import(`~/lang/${locale}/entry.ts`)).dict
const flatDict = i18n.flatten(dict)

// If not English, merge with English as fallback (English keys underneath, locale on top)
if (locale !== "en") {
const enDict = await fetchEnDict()
return { ...enDict, ...flatDict } as Dictionary
}

return flatDict
} catch (err) {
console.error(`Error loading dictionary for locale: ${locale}`, err)
// Fallback to English if the requested locale fails to load
if (locale !== "en") {
return await fetchEnDict()
}
Expand Down
12 changes: 12 additions & 0 deletions src/lang/en/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@
"decompress_upload": "Upload extracted files into target storage",
"done": "Completed",
"undone": "Running",
"running_count": "Running: {{count}}",
"waiting_count": "Waiting: {{count}}",
"show_running_only": "Show running only",
"show_all_undone": "Show all unfinished",
"copy_queue_status": "Copy workers: {{count}}",
"copy_queue_paused": "Copy queue paused",
"pause_copy_queue": "Pause queued copies",
"resume_copy_queue": "Resume with {{count}} workers",
"pause_copy_queue_help": "Running files will finish; only queued copy tasks are paused.",
"copy_queue_paused_success": "Queued copy tasks paused",
"copy_queue_resumed_success": "Copy queue resumed with {{count}} workers",
"invalid_copy_worker_setting": "Invalid copy worker setting",
"clear_succeeded": "Clear Succeeded",
"retry": "Retry",
"retry_failed": "Retry Failed",
Expand Down
165 changes: 146 additions & 19 deletions src/pages/manage/tasks/Copy.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,156 @@
import { useManageTitle, useT } from "~/hooks"
import { Button, HStack, Text, VStack } from "@hope-ui/solid"
import { createMemo, createSignal, Show } from "solid-js"
import { useFetch, useManageTitle, useT } from "~/hooks"
import { me } from "~/store"
import { PEmptyResp, PResp, SettingItem, UserRole } from "~/types"
import { handleResp, notify, r } from "~/utils"
import { TypeTasks } from "./Tasks"
import { getPath } from "./helper"

const copyWorkersSettingKey = "copy_task_threads_num"
const resumeWorkersStorageKey = "openlist-copy-resume-workers"
const defaultResumeWorkers = 3

const validPositiveWorkers = (value: number) =>
Number.isInteger(value) && value >= 1 && value <= 32

const getRememberedWorkers = () => {
try {
const value = Number(localStorage.getItem(resumeWorkersStorageKey))
return validPositiveWorkers(value) ? value : defaultResumeWorkers
} catch (_) {
return defaultResumeWorkers
}
}

const rememberWorkers = (value: number) => {
if (!validPositiveWorkers(value)) return
try {
localStorage.setItem(resumeWorkersStorageKey, value.toString())
} catch (_) {
// The control remains usable when browser storage is unavailable.
}
}

const CopyQueueControl = () => {
const t = useT()
const [setting, setSetting] = createSignal<SettingItem>()
const [workers, setWorkers] = createSignal<number>()
const [resumeWorkers, setResumeWorkers] = createSignal(getRememberedWorkers())
const [loadSettingLoading, loadSetting] = useFetch((): PResp<SettingItem> =>
r.get(`/admin/setting/get?key=${copyWorkersSettingKey}`),
)
const [saveSettingLoading, saveSetting] = useFetch(
(item: SettingItem): PEmptyResp => r.post("/admin/setting/save", [item]),
)

const updateFromSetting = (item: SettingItem) => {
const value = Number(item.value)
if (!Number.isInteger(value) || value < 0 || value > 32) {
notify.error(t("tasks.invalid_copy_worker_setting"))
setSetting(undefined)
setWorkers(undefined)
return
}
setSetting(item)
setWorkers(value)
if (validPositiveWorkers(value)) {
setResumeWorkers(value)
rememberWorkers(value)
}
}

const refresh = async () => {
const resp = await loadSetting()
handleResp(resp, updateFromSetting)
}

const paused = createMemo(() => workers() === 0)
const toggleQueue = async () => {
const item = setting()
const currentWorkers = workers()
if (item === undefined || currentWorkers === undefined) return
const nextWorkers = currentWorkers === 0 ? resumeWorkers() : 0
if (nextWorkers !== 0 && !validPositiveWorkers(nextWorkers)) {
notify.error(t("tasks.invalid_copy_worker_setting"))
return
}
const updated = { ...item, value: nextWorkers.toString() }
const resp = await saveSetting(updated)
handleResp(resp, () => {
updateFromSetting(updated)
notify.success(
nextWorkers === 0
? t("tasks.copy_queue_paused_success")
: t("tasks.copy_queue_resumed_success", { count: nextWorkers }),
)
})
}

refresh()

return (
<VStack w="$full" alignItems="start" spacing="$1">
<HStack gap="$2" flexWrap="wrap">
<Text fontWeight="bold">
{paused()
? t("tasks.copy_queue_paused")
: t("tasks.copy_queue_status", { count: workers() ?? "-" })}
</Text>
<Button
size="sm"
colorScheme={paused() ? "success" : "warning"}
loading={saveSettingLoading()}
disabled={setting() === undefined}
onClick={toggleQueue}
>
{paused()
? t("tasks.resume_copy_queue", { count: resumeWorkers() })
: t("tasks.pause_copy_queue")}
</Button>
<Button
size="sm"
colorScheme="neutral"
loading={loadSettingLoading()}
onClick={refresh}
>
{t("global.refresh")}
</Button>
</HStack>
<Text size="sm" color="$neutral10">
{t("tasks.pause_copy_queue_help")}
</Text>
</VStack>
)
}

const Copy = () => {
const t = useT()
useManageTitle("manage.sidemenu.copy")
return (
<TypeTasks
type="copy"
canRetry
nameAnalyzer={{
regex:
/^(?:copy|merge) \[(.*\/([^\/]*))]\((.*\/([^\/]*))\) to \[(.+)]\((.+)\)$/,
title: (matches) => {
if (matches[4] !== "") return matches[4]
return matches[2] === "" ? "/" : matches[2]
},
attrs: {
[t(`tasks.attr.copy.src`)]: (matches) =>
getPath(matches[1], matches[3]),
[t(`tasks.attr.copy.dst`)]: (matches) =>
getPath(matches[5], matches[6]),
},
}}
/>
<VStack w="$full" alignItems="start" spacing="$4">
<Show when={me().role === UserRole.ADMIN}>
<CopyQueueControl />
</Show>
<TypeTasks
type="copy"
canRetry
nameAnalyzer={{
regex:
/^(?:copy|merge) \[(.*\/([^\/]*))]\((.*\/([^\/]*))\) to \[(.+)]\((.+)\)$/,
title: (matches) => {
if (matches[4] !== "") return matches[4]
return matches[2] === "" ? "/" : matches[2]
},
attrs: {
[t(`tasks.attr.copy.src`)]: (matches) =>
getPath(matches[1], matches[3]),
[t(`tasks.attr.copy.dst`)]: (matches) =>
getPath(matches[5], matches[6]),
},
}}
/>
</VStack>
)
}

Expand Down
5 changes: 3 additions & 2 deletions src/pages/manage/tasks/Task.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const TaskState = (props: { state: number }) => {
)
}

export type TaskOrderBy = "name" | "creator" | "state" | "progress"
export type TaskOrderBy = "name" | "creator" | "state" | "progress" | "end_time"

export interface TaskCol {
name: TaskOrderBy | "speed" | "operation"
Expand Down Expand Up @@ -151,7 +151,7 @@ export const Task = (props: TaskAttribute & TasksProps & TaskLocalSetter) => {
}
return `${delta.toFixed(2)} ${units[unit_i]}`
}
if (props.done) {
if (props.done === "done") {
if (
props.start_time !== props.end_time &&
props.progress > 0 &&
Expand All @@ -162,6 +162,7 @@ export const Task = (props: TaskAttribute & TasksProps & TaskLocalSetter) => {
speedText = parseSpeedText(timeDelta, lengthDelta)
}
} else if (
props.done === "undone" &&
props.prevProgress !== undefined &&
props.prevFetchTime !== undefined
) {
Expand Down
Loading