Skip to content

A full-featured download manager.

feat(torrent): create torrent files from local files and folders (#2306)

a0666660909514d00fa8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 758d7ce8..823de430 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -69,7 +69,7 @@ jobs:
# hydrate dist/. The notice contract needs the runtime license payload;
# the package installer is idempotent when dist/ already matches.
- name: Ensure Electron runtime payload
- run: node node_modules/electron/install.js
+ run: node scripts/ensure-electron-runtime.mjs --retry-download
- name: i18n catalog and translation contract
run: pnpm run check:i18n
@@ -129,7 +129,7 @@ jobs:
MOTRIX_SKIP_ELECTRON_REBUILD: '1'
MOTRIX_SKIP_ENGINE_FETCH: '1'
- name: Ensure Electron runtime payload
- run: node node_modules/electron/install.js
+ run: node scripts/ensure-electron-runtime.mjs --retry-download
- name: Setup Rust for native test fixtures
uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
@@ -409,9 +409,11 @@ jobs:
# Electron does not hydrate dist/ during pnpm install. build:legal
# and the electron-builder smoke both require that runtime payload.
- name: Ensure Electron runtime payload
- run: node node_modules/electron/install.js
+ run: node scripts/ensure-electron-runtime.mjs --retry-download
- name: Fetch target aria2
+ env:
+ MOTRIX_ENGINE_FETCH_TIMEOUT_MS: '90000'
run: >-
pnpm run fetch:engine
--platform ${{ matrix.platform }}
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index 3978fab5..5161ec93 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -110,7 +110,7 @@ jobs:
# dist/ anyway. The notice contract needs dist/LICENSE and
# dist/LICENSES.chromium.html, so fetch the runtime explicitly.
- name: Fetch Electron runtime for the notice contract
- run: node node_modules/electron/install.js
+ run: node scripts/ensure-electron-runtime.mjs --retry-download
- name: Third-party notice contract
run: pnpm --config.verify-deps-before-run=false run check:third-party-notices
diff --git a/.github/workflows/snap.yml b/.github/workflows/snap.yml
index ae09007c..94359895 100644
--- a/.github/workflows/snap.yml
+++ b/.github/workflows/snap.yml
@@ -142,7 +142,7 @@ jobs:
# Electron does not declare a postinstall script, so pnpm install
# does not hydrate dist/ with the runtime and license payload.
- name: Ensure Electron runtime payload
- run: node node_modules/electron/install.js
+ run: node scripts/ensure-electron-runtime.mjs --retry-download
- name: Fetch target aria2
run: >-
diff --git a/docs/docker-server.md b/docs/docker-server.md
index 073369ff..6b0c848d 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -477,7 +477,7 @@ CLI/agent and browser-Extension pairing remain operator-approved workflows.
## Logo menu in the Web UI
-Open the **Motrix** logo at the upper left for About, Settings, Task, Help,
+Open the **Motrix** logo at the upper left for About, Settings, File, Task, Help,
and **Sign out**. Narrow screens show one menu level at a time; use **Back**,
Left Arrow, or Escape to return to the parent level.
@@ -486,6 +486,11 @@ Left Arrow, or Escape to return to the parent level.
browser, supports multiple files, and lets you review each before submitting.
The download destination is a path on the Server. See [torrent upload
size](#torrent-upload-size) for the configurable request limit.
+- **File → Create Torrent File…** creates a BitTorrent v1 torrent from a file
+ or folder on the Server. Choose a source inside the configured download roots
+ that your account can read, then select **Create**. **Save .torrent** downloads
+ the metainfo to your browser. Enable **Start seeding after saving** to verify
+ and seed the original files on the Server; otherwise no download task is added.
- Pause, resume, remove, and queue commands apply to the committed selection
in the current filtered downloads list. **Select all tasks** includes rows
outside the visible viewport. Changing the selection or filter cancels a
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index cb229475..ef4a2a9c 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -419,13 +419,17 @@ CLI/agent 与浏览器扩展配对都仍然需要 operator 审批。
## Web 界面的 Logo 菜单
-点击左上角的 **Motrix** Logo,可打开关于、设置、任务、帮助和**退出登录**。
+点击左上角的 **Motrix** Logo,可打开关于、设置、文件、任务、帮助和**退出登录**。
窄屏一次显示一级菜单;点击**返回**、按左方向键或 Escape 可返回上一级。
- **新建任务**打开链接表单,**新建 BT 任务**打开种子表单。
**打开种子文件**读取浏览器所在设备上的 `.torrent` 文件,支持多选,
提交前可逐个检查。下载保存路径属于 Server。请求体大小可配置,
详见本文的种子上传大小说明。
+- **文件 → 创建种子文件…** 可从服务器上的文件或目录创建 BitTorrent v1 种子。
+ 在配置的下载根目录内选择当前账号可读取的来源,点击**创建**。
+ **保存 .torrent** 会将种子下载到浏览器所在设备。勾选**保存后使用原文件做种**时,
+ Server 会校验并使用原文件做种;不勾选则只导出种子,不新增下载任务。
- 暂停、继续、移除和队列调整作用于当前筛选列表中已确认的选择。
**全选任务**包含视口外的行;选择或筛选变化会取消尚未执行的选择操作。
- **全部暂停**和**全部继续**作用于整个实例。**清理已停止任务记录**会确认
diff --git a/e2e/create-torrent.spec.ts b/e2e/create-torrent.spec.ts
new file mode 100644
index 00000000..6bdb2fb4
--- /dev/null
+++ b/e2e/create-torrent.spec.ts
@@ -0,0 +1,281 @@
+import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { parseTorrent } from '@motrix/torrent'
+import {
+ ADD_TASK_COLLAPSED_HEIGHT,
+ TASK_FORM_WIDTH,
+} from '@shared/constants/add-task'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { DownloadTask } from '@shared/types/task'
+import {
+ expect,
+ findAddTaskWindow,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+
+test('File → Create Torrent saves and seeds the selected original folder', async ({
+ electronApp,
+ mainWindow,
+ userDataDir,
+}, testInfo) => {
+ test.setTimeout(90_000)
+ await waitForEngineReady(mainWindow)
+ await mainWindow.evaluate(
+ (channel) =>
+ window.motrix.invoke(channel, { engine: { seedRatio: 0, seedTime: 0 } }),
+ Commands.UpdateSettings
+ )
+ await electronApp.evaluate(({ Menu, BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((w) =>
+ w.webContents.getURL().includes('w=main')
+ )
+ const item = Menu.getApplicationMenu()?.getMenuItemById('menubar.task.new')
+ if (!main || !item) throw Error('New Task menu unavailable')
+ item.click({}, main, main.webContents)
+ })
+ const add = await findAddTaskWindow(electronApp)
+ const cancel = add.getByRole('button', { name: 'Cancel', exact: true })
+ await expect(cancel).toBeVisible()
+ await expect
+ .poll(() => add.evaluate(() => [innerWidth, innerHeight]))
+ .toEqual([TASK_FORM_WIDTH, ADD_TASK_COLLAPSED_HEIGHT])
+ const taskSize = await add.evaluate(() => ({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }))
+ const taskAdvanced = await add
+ .getByRole('button', { name: 'Advanced', exact: true })
+ .boundingBox()
+ const taskFooter = await add
+ .locator('[data-slot="add-task-form-footer"]')
+ .boundingBox()
+ await cancel.click()
+ const source = path.join(await realpath(userDataDir), 'shared')
+ const payload = Buffer.concat([
+ Buffer.alloc(32768, 1),
+ Buffer.alloc(32768, 2),
+ Buffer.from('tail'),
+ ])
+ await mkdir(path.join(source, 'nested'), { recursive: true })
+ await writeFile(path.join(source, 'nested', 'payload.bin'), payload)
+ const output = path.join(userDataDir, 'shared.torrent')
+ const nextWindow = electronApp.waitForEvent('window', {
+ predicate: async (win) => {
+ await win.waitForLoadState('domcontentloaded')
+ return win.url().includes('w=create-torrent')
+ },
+ })
+ await electronApp.evaluate(
+ ({ Menu, BrowserWindow, dialog }, { source, output }) => {
+ dialog.showOpenDialog = async (
+ arg: Electron.BaseWindow | Electron.OpenDialogOptions,
+ options?: Electron.OpenDialogOptions
+ ) => {
+ const opts = options ?? (arg as Electron.OpenDialogOptions)
+ if (opts.properties?.join() !== 'openDirectory')
+ throw new Error('Expected directory-only picker')
+ return { canceled: false, filePaths: [source] }
+ }
+ dialog.showSaveDialog = async () => ({
+ canceled: false,
+ filePath: output,
+ })
+ const main = BrowserWindow.getAllWindows().find((w) =>
+ w.webContents.getURL().includes('w=main')
+ )
+ const menu = Menu.getApplicationMenu()?.getMenuItemById(
+ 'menubar.file.createTorrent'
+ )
+ if (!main || !menu?.enabled)
+ throw new Error('Create torrent menu is unavailable')
+ menu.click({}, main, main.webContents)
+ },
+ { source, output }
+ )
+ const creator = await nextWindow
+ await creator.getByRole('button', { name: 'Select folder' }).waitFor()
+ await expect
+ .poll(() =>
+ creator.evaluate(() => ({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }))
+ )
+ .toEqual(taskSize)
+ expect(
+ (
+ await creator
+ .getByRole('button', { name: 'Advanced', exact: true })
+ .boundingBox()
+ )?.height
+ ).toBe(taskAdvanced?.height)
+ expect((await creator.locator('footer').boundingBox())?.height).toBe(
+ taskFooter?.height
+ )
+ await creator.screenshot({
+ path: testInfo.outputPath('creator-form.png'),
+ scale: 'css',
+ })
+ await creator.getByRole('button', { name: 'Select folder' }).click()
+ await creator
+ .getByLabel('Trackers', { exact: true })
+ .fill('http://127.0.0.1:1/announce')
+ await creator.getByRole('switch', { name: 'Private torrent' }).click()
+ await creator
+ .getByRole('switch', { name: 'Start seeding after saving' })
+ .click()
+ await creator.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(creator.getByRole('textbox', { name: 'Trackers' })).toHaveCount(
+ 0
+ )
+ await creator.getByRole('button', { name: 'Save .torrent' }).click()
+ await expect(creator.getByRole('status')).toContainText(
+ 'The seeding task was submitted.'
+ )
+ const parsed = parseTorrent(new Uint8Array(await readFile(output)))
+ expect(parsed.private).toBe(true)
+ expect(parsed.v1?.multiFile).toBe(true)
+ expect(parsed.v1?.pieces.length).toBe(3)
+ if (parsed.identity.kind === 'v2') throw new Error('Expected a v1 torrent')
+ const infoHash = parsed.identity.sha1
+ const getTasks = () =>
+ mainWindow.evaluate(
+ async (channel) =>
+ (await window.motrix.invoke(channel)) as DownloadTask[],
+ Queries.ListTasks
+ )
+ await expect
+ .poll(
+ async () =>
+ (await getTasks()).find((task) => task.infoHash === infoHash)?.status,
+ { timeout: 30_000 }
+ )
+ .toBe('seeding')
+ expect(
+ (await getTasks()).find((task) => task.infoHash === infoHash)?.finalPath
+ ).toBe(source)
+ expect(await readFile(path.join(source, 'nested', 'payload.bin'))).toEqual(
+ payload
+ )
+})
+
+test('cancelled export can be edited and saved without creating a task', async ({
+ electronApp,
+ mainWindow,
+ userDataDir,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await mainWindow.evaluate(
+ (channel) => window.motrix.invoke(channel, { app: { language: 'zh-CN' } }),
+ Commands.UpdateSettings
+ )
+ const source = path.join(userDataDir, 'example.txt')
+ const output = path.join(userDataDir, 'export.torrent')
+ await writeFile(source, 'local source')
+ const pending = electronApp.waitForEvent('window', {
+ predicate: async (win) => {
+ await win.waitForLoadState('domcontentloaded')
+ return win.url().includes('w=create-torrent')
+ },
+ })
+ await electronApp.evaluate(
+ ({ Menu, BrowserWindow, dialog }, { source, output }) => {
+ let first = true
+ dialog.showOpenDialog = async (
+ arg: Electron.BaseWindow | Electron.OpenDialogOptions,
+ opts?: Electron.OpenDialogOptions
+ ) => {
+ if (
+ (opts ?? (arg as Electron.OpenDialogOptions)).properties?.join() !==
+ 'openFile'
+ )
+ throw new Error('Expected file-only picker')
+ return { canceled: false, filePaths: [source] }
+ }
+ dialog.showSaveDialog = async () => {
+ if (first) {
+ first = false
+ return { canceled: true, filePath: '' }
+ }
+ return { canceled: false, filePath: output }
+ }
+ const win = BrowserWindow.getAllWindows().find((w) =>
+ w.webContents.getURL().includes('w=main')
+ )
+ const item = Menu.getApplicationMenu()?.getMenuItemById(
+ 'menubar.file.createTorrent'
+ )
+ if (!win || !item?.enabled) throw new Error('Missing create command')
+ item.click({}, win, win.webContents)
+ },
+ { source, output }
+ )
+ const creator = await pending
+ await creator.getByRole('button', { name: '选择文件', exact: true }).waitFor()
+ await creator.screenshot({
+ path: testInfo.outputPath('creator-zh-CN.png'),
+ scale: 'css',
+ })
+ await creator.getByRole('button', { name: '高级' }).click()
+ await expect
+ .poll(() =>
+ creator.evaluate(() => {
+ const field = document.getElementById('creator-piece')
+ const footer = document.querySelector('footer')
+ return (
+ !!field &&
+ !!footer &&
+ field.getBoundingClientRect().bottom <=
+ footer.getBoundingClientRect().top
+ )
+ })
+ )
+ .toBe(true)
+ await creator.screenshot({
+ path: testInfo.outputPath('creator-advanced-zh-CN.png'),
+ scale: 'css',
+ })
+ const pieces = creator.getByRole('combobox', { name: '分块大小' })
+ await pieces.click()
+ await creator.getByRole('option').last().click()
+ await creator.getByRole('button', { name: '选择文件', exact: true }).click()
+ // An invalid URL in a collapsed group must be visible and keyboard-accessible
+ // when the user tries to create the torrent.
+ const webSeeds = creator.getByRole('textbox', { name: 'Web 种子' })
+ await webSeeds.fill('ftp://example.invalid/resource')
+ await creator.getByRole('button', { name: '高级' }).click()
+ await creator.getByRole('button', { name: '创建', exact: true }).click()
+ await expect(webSeeds).toBeFocused()
+ await expect(webSeeds).toHaveAttribute('aria-invalid', 'true')
+ await webSeeds.fill('')
+ await expect(creator.getByRole('alert')).toHaveCount(0)
+ await creator.getByLabel('备注', { exact: true }).fill('first description')
+ await creator.getByRole('button', { name: '创建', exact: true }).click()
+ await creator.getByRole('button', { name: '保存 .torrent' }).click()
+ await expect(
+ creator.getByRole('button', { name: '编辑', exact: true })
+ ).toBeEnabled()
+ await expect(readFile(output)).rejects.toMatchObject({ code: 'ENOENT' })
+ await creator.getByRole('button', { name: '编辑', exact: true }).click()
+ await creator
+ .getByLabel('备注', { exact: true })
+ .fill('corrected description')
+ await creator.getByRole('button', { name: '创建', exact: true }).click()
+ await creator.getByRole('button', { name: '保存 .torrent' }).waitFor()
+ await creator.screenshot({
+ path: testInfo.outputPath('creator-result-zh-CN.png'),
+ scale: 'css',
+ })
+ await creator.getByRole('button', { name: '保存 .torrent' }).click()
+ await expect(creator.getByRole('status')).toContainText('种子已保存')
+ const metadata = parseTorrent(new Uint8Array(await readFile(output)))
+ expect(metadata.comment).toBe('corrected description')
+ expect(metadata.pieceLength).toBe(16 * 1024 ** 2)
+ const tasks = await mainWindow.evaluate(
+ async (channel) => (await window.motrix.invoke(channel)) as DownloadTask[],
+ Queries.ListTasks
+ )
+ expect(tasks).toHaveLength(0)
+})
diff --git a/e2e/server-torrent/create-torrent.browser.ts b/e2e/server-torrent/create-torrent.browser.ts
new file mode 100644
index 00000000..ea1d7bca
--- /dev/null
+++ b/e2e/server-torrent/create-torrent.browser.ts
@@ -0,0 +1,271 @@
+import { spawn } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseTorrent } from '@motrix/torrent'
+import { expect, test } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../../src/core/settings/migrations'
+import {
+ ADD_TASK_COLLAPSED_HEIGHT,
+ TASK_FORM_WIDTH,
+} from '../../src/shared/constants/add-task'
+import { getFreePort } from '../helpers/free-port'
+
+test('create on the server, download in the browser, and seed the original folder', async ({
+ page,
+}, info) => {
+ const repo = fileURLToPath(new URL('../../', import.meta.url))
+ const root = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'motrix-web-creator-'))
+ )
+ const data = path.join(root, 'data'),
+ allowed = path.join(root, 'downloads'),
+ content = path.join(allowed, 'collection')
+ await mkdir(data, { recursive: true })
+ await mkdir(content, { recursive: true })
+ const payload = Buffer.alloc(65540, 77)
+ await writeFile(path.join(content, 'disc.bin'), payload)
+ await writeFile(path.join(allowed, 'single.bin'), 'local server data')
+ await writeFile(
+ path.join(data, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { language: 'en-US', defaultSaveDir: allowed },
+ onboarding: { disclaimerAccepted: true },
+ tracker: { autoSync: false },
+ engine: { rpcPort: await getFreePort(), seedRatio: 0, seedTime: 0 },
+ })
+ )
+ const port = await getFreePort(),
+ token = randomUUID()
+ const origin = `http://127.0.0.1:${port}`,
+ base = `${origin}/motrix`
+ const server = spawn(
+ process.execPath,
+ [path.join(repo, 'dist/server/index.mjs')],
+ {
+ cwd: repo,
+ env: {
+ ...process.env,
+ PORT: String(port),
+ MOTRIX_DATA_DIR: data,
+ MOTRIX_DEFAULT_SAVE_DIR: allowed,
+ MOTRIX_ALLOWED_SAVE_DIRS: allowed,
+ MOTRIX_MDXP_PORT: '0',
+ MOTRIX_MDXP_HOST: '127.0.0.1',
+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'false',
+ MOTRIX_PUBLIC_URL: origin,
+ MOTRIX_WEB_BASE_PATH: '/motrix',
+ MOTRIX_OPERATOR_TOKEN: token,
+ MOTRIX_ARIA2_BIN: path.join(
+ repo,
+ 'extra',
+ process.platform,
+ process.arch,
+ process.platform === 'win32' ? 'aria2c.exe' : 'aria2c'
+ ),
+ MOTRIX_RENDERER_DIR: path.join(repo, 'dist/renderer-web'),
+ MOTRIX_BUILTIN_PLUGIN_DIR: path.join(repo, 'dist/builtin-plugins'),
+ NODE_ENV: 'production',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+ )
+ let logs = ''
+ const append = (chunk: Buffer) => {
+ logs = (logs + chunk.toString()).slice(-24000)
+ }
+ server.stdout.on('data', append)
+ server.stderr.on('data', append)
+ const exited = new Promise<void>((resolve) =>
+ server.once('exit', () => resolve())
+ )
+ try {
+ await expect
+ .poll(
+ async () => {
+ if (server.exitCode !== null) throw Error(logs)
+ try {
+ return (await page.request.get(`${base}/healthz`)).ok()
+ } catch {
+ return false
+ }
+ },
+ { timeout: 25000 }
+ )
+ .toBe(true)
+ expect(
+ (
+ await page.request.post(`${base}/rpc/auth/login`, {
+ data: { token },
+ headers: { origin },
+ })
+ ).ok()
+ ).toBe(true)
+ await page.goto(`${base}/`)
+ const openFileMenu = async (label: string) => {
+ await page.getByRole('button', { name: 'Motrix', exact: true }).click()
+ await page.getByRole('menuitem', { name: 'File', exact: true }).hover()
+ await page.getByRole('menuitem', { name: label, exact: true }).click()
+ }
+ await openFileMenu('New Task…')
+ const add = page.getByRole('dialog', { name: 'New Task' })
+ await expect(add).toBeVisible()
+ const size = () => add.boundingBox()
+ await expect
+ .poll(async () => Math.round((await size())?.height ?? 0))
+ .toBe(ADD_TASK_COLLAPSED_HEIGHT)
+ await expect
+ .poll(async () => Math.round((await size())?.width ?? 0))
+ .toBe(TASK_FORM_WIDTH)
+ const addAdvanced = await add
+ .getByRole('button', { name: 'Advanced', exact: true })
+ .boundingBox()
+ const addFooter = await add
+ .locator('[data-slot="add-task-form-footer"]')
+ .boundingBox()
+ await add.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await openFileMenu('Create Torrent File…')
+ const maker = page.getByRole('dialog', { name: 'Create torrent' })
+ await expect
+ .poll(async () => Math.round((await maker.boundingBox())?.height ?? 0))
+ .toBe(ADD_TASK_COLLAPSED_HEIGHT)
+ await expect
+ .poll(async () => Math.round((await maker.boundingBox())?.width ?? 0))
+ .toBe(TASK_FORM_WIDTH)
+ expect(
+ (
+ await maker
+ .getByRole('button', { name: 'Advanced', exact: true })
+ .boundingBox()
+ )?.height
+ ).toBe(addAdvanced?.height)
+ expect((await maker.locator('footer').boundingBox())?.height).toBe(
+ addFooter?.height
+ )
+ await maker.screenshot({ path: info.outputPath('server-creator.png') })
+ await maker.getByRole('button', { name: 'Advanced', exact: true }).click()
+ await expect(maker.getByLabel('Comment', { exact: true })).toBeVisible()
+ await maker.getByRole('button', { name: 'Advanced', exact: true }).click()
+ await maker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ const picker = page.getByTestId('web-directory-picker')
+ await picker.getByRole('option', { name: /collection/ }).click()
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await maker
+ .getByRole('textbox', { name: 'Trackers', exact: true })
+ .fill('http://127.0.0.1:1/announce')
+ await maker.getByRole('switch', { name: 'Private torrent' }).click()
+ await maker
+ .getByRole('switch', { name: 'Start seeding after saving' })
+ .click()
+ await maker.getByRole('button', { name: 'Create', exact: true }).click()
+ const download = page.waitForEvent('download')
+ await maker
+ .getByRole('button', { name: 'Save .torrent', exact: true })
+ .click()
+ const file = await download
+ expect(file.suggestedFilename()).toBe('collection.torrent')
+ const downloaded = await file.path()
+ if (!downloaded) throw new Error('Torrent download has no local artifact')
+ const parsed = parseTorrent(new Uint8Array(await readFile(downloaded)))
+ expect(parsed.v1?.multiFile).toBe(true)
+ expect(parsed.v1?.pieces.length).toBe(3)
+ expect(parsed.private).toBe(true)
+ await expect(maker.getByRole('status')).toContainText(
+ 'The seeding task was submitted.'
+ )
+ const tasks = async () =>
+ (
+ await page.request.post(`${base}/rpc/query/query%3AlistTasks`, {
+ data: { args: [] },
+ })
+ ).json()
+ await expect
+ .poll(
+ async () =>
+ (await tasks()).find(
+ (t: { finalPath: string }) => t.finalPath === content
+ )?.status,
+ { timeout: 30000 }
+ )
+ .toBe('seeding')
+ expect(await readFile(path.join(content, 'disc.bin'))).toEqual(payload)
+ await maker
+ .getByRole('button', { name: 'Close', exact: true })
+ .last()
+ .click()
+ await openFileMenu('Create Torrent File…')
+ await maker
+ .getByRole('button', { name: 'Select file', exact: true })
+ .click()
+ await picker.getByRole('option', { name: /single.bin/ }).click()
+ await picker
+ .getByRole('button', { name: 'Select file', exact: true })
+ .click()
+ await maker.getByRole('button', { name: 'Create', exact: true }).click()
+ const download2 = page.waitForEvent('download')
+ await maker
+ .getByRole('button', { name: 'Save .torrent', exact: true })
+ .click()
+ expect((await download2).suggestedFilename()).toBe('single.bin.torrent')
+ await expect(maker.getByRole('status')).toContainText('Download requested')
+ expect(await tasks()).toHaveLength(1)
+ await maker
+ .getByRole('button', { name: 'Close', exact: true })
+ .last()
+ .click()
+ await page.setViewportSize({ width: 390, height: 600 })
+ await page.getByRole('button', { name: 'Motrix', exact: true }).click()
+ await page.getByRole('menuitem', { name: 'File', exact: true }).click()
+ await page
+ .getByRole('menuitem', { name: 'Create Torrent File…', exact: true })
+ .click()
+ await expect
+ .poll(async () => Math.round((await maker.boundingBox())?.width ?? 0))
+ .toBe(358)
+ await maker.getByRole('button', { name: 'Advanced', exact: true }).click()
+ await expect(
+ maker.getByRole('button', { name: 'Create', exact: true })
+ ).toBeInViewport()
+ await page.request.post(`${base}/rpc/command/command%3AupdateSettings`, {
+ data: { args: [{ app: { language: 'zh-CN' } }] },
+ headers: { origin },
+ })
+ const localized = page.getByRole('dialog', { name: '创建种子' })
+ await localized.getByRole('button', { name: '高级', exact: true }).waitFor()
+ await localized.screenshot({
+ path: info.outputPath('server-narrow-zh.png'),
+ })
+ await page.setViewportSize({ width: 1024, height: 768 })
+ await localized.getByRole('button', { name: '高级', exact: true }).click()
+ await expect
+ .poll(async () =>
+ Math.round((await localized.boundingBox())?.height ?? 0)
+ )
+ .toBe(ADD_TASK_COLLAPSED_HEIGHT)
+ await localized.screenshot({
+ path: info.outputPath('server-creator-zh.png'),
+ })
+ } finally {
+ if (server.exitCode === null && server.signalCode === null) {
+ server.kill('SIGTERM')
+ const timeout = setTimeout(() => server.kill('SIGKILL'), 5000)
+ await exited
+ clearTimeout(timeout)
+ }
+ await rm(root, { recursive: true, force: true })
+ }
+})
diff --git a/e2e/server-torrent/playwright.config.ts b/e2e/server-torrent/playwright.config.ts
new file mode 100644
index 00000000..846235c2
--- /dev/null
+++ b/e2e/server-torrent/playwright.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from '@playwright/test'
+export default defineConfig({
+ testDir: '.',
+ testMatch: '*.browser.ts',
+ workers: 1,
+ timeout: 90_000,
+ expect: { timeout: 12_000 },
+ retries: 0,
+ outputDir: '../../output/playwright/test-results/server-torrent',
+ use: {
+ viewport: { width: 1024, height: 768 },
+ headless: true,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+})
diff --git a/scripts/ensure-electron-runtime.mjs b/scripts/ensure-electron-runtime.mjs
index 5dce4d04..34a78919 100644
--- a/scripts/ensure-electron-runtime.mjs
+++ b/scripts/ensure-electron-runtime.mjs
@@ -5,6 +5,7 @@ import { randomUUID } from 'node:crypto'
import { existsSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
const require = createRequire(import.meta.url)
@@ -189,6 +190,7 @@ export function ensureElectronRuntime(options = {}) {
const hadPathFile = fs.existsSync(pathFile)
let distBackup = null
let pathBackup = null
+ let transientDownloadError = false
try {
// Electron's installer returns early when dist/version + the binary
@@ -199,8 +201,12 @@ export function ensureElectronRuntime(options = {}) {
const result = spawn(process.execPath, [installerPath], {
env: options.env ?? process.env,
- stdio: 'inherit',
+ stdio: options.onTransientDownloadFailure
+ ? ['inherit', 'inherit', 'pipe']
+ : 'inherit',
+ encoding: 'utf8',
})
+ if (result.stderr) logError(result.stderr.trimEnd())
if (result.error) {
throw result.error
}
@@ -208,6 +214,10 @@ export function ensureElectronRuntime(options = {}) {
throw new Error(`Electron installer was killed by ${result.signal}`)
}
if (result.status !== 0) {
+ transientDownloadError =
+ /HTTPError: Response code (?:408|429|500|502|503|504)\b|\b(?:EAI_AGAIN|ECONNRESET|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_SOCKET)\b/.test(
+ result.stderr ?? ''
+ )
const error = new Error(
`Electron installer exited with status ${result.status ?? 'unknown'}`
)
@@ -250,14 +260,40 @@ export function ensureElectronRuntime(options = {}) {
logError(
`[ensure-electron-runtime] repair failed: ${error?.message ?? error}`
)
+ if (transientDownloadError && restoreErrors.length === 0)
+ options.onTransientDownloadFailure?.()
return Number.isInteger(error?.exitCode) ? error.exitCode : 1
}
}
+// Retry the pinned package installer only after the previous attempt restored
+// its starting state. Integrity, extraction, and local filesystem errors stay fatal.
+export async function ensureElectronRuntimeForCi(options = {}) {
+ const delays = [5_000, 15_000, 30_000]
+ for (let attempt = 0; ; attempt++) {
+ let retry = false
+ const status = ensureElectronRuntime({
+ ...options,
+ onTransientDownloadFailure: () => {
+ retry = true
+ },
+ })
+ if (!retry || attempt === delays.length) return status
+ const ms = delays[attempt]
+ const log = options.log ?? console.log
+ log(
+ `[ensure-electron-runtime] transient download failure; retry ${attempt + 2}/${delays.length + 1} in ${ms / 1000}s`
+ )
+ await (options.sleep ?? delay)(ms)
+ }
+}
+
const invokedAsMain =
process.argv[1] != null &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
if (invokedAsMain) {
- process.exit(ensureElectronRuntime())
+ process.exitCode = process.argv.includes('--retry-download')
+ ? await ensureElectronRuntimeForCi()
+ : ensureElectronRuntime()
}
diff --git a/scripts/vite-desktop-locales.ts b/scripts/vite-app-locales.ts
similarity index 74%
rename from scripts/vite-desktop-locales.ts
rename to scripts/vite-app-locales.ts
index eed8e565..8556e748 100644
--- a/scripts/vite-desktop-locales.ts
+++ b/scripts/vite-app-locales.ts
@@ -1,16 +1,25 @@
import type { Plugin } from 'vite'
-/** Keep Server-only and renderer-only catalogs out of the desktop main bundle. */
-export function desktopLocaleProjection(localeDirectory: string): Plugin {
+// The operator-admin catalog belongs to the Server CLI, never to the app UI.
+export function appLocaleProjection(
+ localeDirectory: string,
+ host: 'main' | 'renderer'
+): Plugin {
const prefix = `${localeDirectory.replaceAll('\\', '/')}/`
return {
- name: 'desktop-locale-projection',
+ name: `${host}-locale-projection`,
enforce: 'pre',
transform(source, id) {
const file = id.split('?')[0]?.replaceAll('\\', '/')
if (!file?.startsWith(prefix) || !file.endsWith('.json')) return null
const catalog = JSON.parse(source) as Record<string, unknown>
delete catalog.operatorAdmin
+ if (host === 'renderer')
+ return { code: JSON.stringify(catalog), map: null }
+ const creator = catalog.createTorrent as
+ | Record<string, unknown>
+ | undefined
+ if (creator) catalog.createTorrent = { menuLabel: creator.menuLabel }
const settings = catalog.settings as Record<string, unknown> | undefined
const integration = settings?.integration as
| Record<string, unknown>
diff --git a/src/core/legacy-import/http-activation.integration.test.ts b/src/core/legacy-import/http-activation.integration.test.ts
index 3fc6f90b..1b0f2f64 100644
--- a/src/core/legacy-import/http-activation.integration.test.ts
+++ b/src/core/legacy-import/http-activation.integration.test.ts
@@ -478,13 +478,15 @@ describe.skipIf(!binaryPath)('real native HTTP migration activation', () => {
it('quarantines same-inode edits to old bytes despite a valid native binding and real progress', async () => {
const f = await nativeFixture({ holdDownload: true })
- const { adapter } = await f.start()
+ const { adapter, rpc } = await f.start()
const resume = adapter.resumeTask.bind(adapter)
+ const paused = vi.fn()
const resumeSpy = vi
.spyOn(adapter, 'resumeTask')
.mockImplementationOnce(async (gid) => {
await resume(gid)
await progressed(adapter, gid)
+ rpc.onDownloadPause(paused)
await adapter.pauseTask(gid)
throw new Error('Lost resume response')
})
@@ -494,6 +496,11 @@ describe.skipIf(!binaryPath)('real native HTTP migration activation', () => {
const intent = legacyHttpActivationSchema.parse(
f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation
)
+ // The pause RPC can return before aria2 flushes its last range to disk.
+ await vi.waitFor(
+ () => expect(paused).toHaveBeenCalledWith({ gid: intent.engineTaskId }),
+ { timeout: 10_000 }
+ )
const bytes = await readFile(f.target)
bytes[LEGACY_HTTP_COMPLETED - 1] ^= 255
await writeFile(f.target, bytes)
diff --git a/src/core/torrent/create-torrent.aria2.integration.test.ts b/src/core/torrent/create-torrent.aria2.integration.test.ts
new file mode 100644
index 00000000..99860440
--- /dev/null
+++ b/src/core/torrent/create-torrent.aria2.integration.test.ts
@@ -0,0 +1,122 @@
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import type { Aria2RawStatus } from '@core/engine/aria2/types'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import {
+ type Aria2Handle,
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ connectAdapter,
+ spawnAria2ForTest,
+} from '../../test-utils/aria2'
+import { createTorrent } from './create-torrent'
+
+// End-to-end oracle for the create-torrent feature (#459): the metainfo we
+// build must be accepted by a real aria2, hash-identify the SAME info hash,
+// and recognize the already-present source data (checksum passes, no
+// re-download) — the exact loop "create → add → seed" users will run.
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'create-torrent roundtrip with real aria2',
+ () => {
+ let directory: string
+ let handle: Aria2Handle
+ let wired: Awaited<ReturnType<typeof connectAdapter>>
+
+ beforeEach(async () => {
+ directory = await mkdtemp(
+ path.join(tmpdir(), 'motrix-create-torrent-aria2-')
+ )
+ handle = await spawnAria2ForTest({ baseDir: directory })
+ wired = await connectAdapter(handle)
+ })
+
+ afterEach(async () => {
+ wired.disconnect()
+ await handle.kill()
+ await rm(directory, { recursive: true, force: true })
+ })
+
+ it('adds and hash-checks the created metainfo against existing data', async () => {
+ const payload = 'aria2 create-torrent integration payload\n'.repeat(2081)
+ const sourceFile = path.join(directory, 'payload.bin')
+ await writeFile(sourceFile, payload)
+
+ const result = await createTorrent({
+ sourcePath: sourceFile,
+ pieceLength: 16 * 1024,
+ })
+ expect(result.totalSize).toBe(payload.length)
+
+ const gid = await wired.adapter.addTorrent({
+ metadata: result.bytes,
+ saveDir: directory,
+ checkIntegrity: true,
+ seedRatio: 0,
+ seedTime: 0,
+ })
+ expect(gid).toMatch(/^[0-9a-fA-F]{16}$/)
+
+ // Poll until the checksum pass settles. With the data already on
+ // disk, aria2 finishes hashing almost immediately; completedLength
+ // reaching totalSize proves the data was accepted, not re-downloaded.
+ const deadline = Date.now() + 15_000
+ let raw: Aria2RawStatus | null = null
+ while (Date.now() < deadline) {
+ const current = (await wired.rpc.tellStatus(gid)) as Aria2RawStatus
+ if (
+ current.completedLength === current.totalLength &&
+ ['active', 'complete', 'seeding', 'waiting'].includes(current.status)
+ ) {
+ raw = current
+ break
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ expect(raw).not.toBeNull()
+ expect(raw!.infoHash).toBe(result.infoHash)
+ expect(raw!.totalLength).toBe(String(payload.length))
+
+ // The source file must be untouched by the hash-check.
+ expect(await readFile(sourceFile, 'utf8')).toBe(payload)
+ })
+
+ it('adds a multi-file folder torrent and recognizes all files', async () => {
+ const folder = path.join(directory, 'bundle')
+ await mkdir(folder)
+ await writeFile(path.join(folder, 'a.txt'), 'alpha\n')
+ await writeFile(path.join(folder, 'b.txt'), 'beta\n')
+
+ const result = await createTorrent({
+ sourcePath: folder,
+ pieceLength: 16 * 1024,
+ })
+ expect(result.fileCount).toBe(2)
+
+ const gid = await wired.adapter.addTorrent({
+ metadata: result.bytes,
+ saveDir: directory,
+ checkIntegrity: true,
+ seedRatio: 0,
+ seedTime: 0,
+ })
+ const deadline = Date.now() + 15_000
+ let raw: Aria2RawStatus | null = null
+ while (Date.now() < deadline) {
+ const current = (await wired.rpc.tellStatus(gid)) as Aria2RawStatus
+ if (
+ current.completedLength === current.totalLength &&
+ ['active', 'complete', 'seeding', 'waiting'].includes(current.status)
+ ) {
+ raw = current
+ break
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ expect(raw).not.toBeNull()
+ expect(raw!.infoHash).toBe(result.infoHash)
+ expect(Number(raw!.totalLength)).toBe(11)
+ expect((await stat(path.join(folder, 'a.txt'))).isFile()).toBe(true)
+ })
+ }
+)
diff --git a/src/core/torrent/create-torrent.test.ts b/src/core/torrent/create-torrent.test.ts
new file mode 100644
index 00000000..c124958b
--- /dev/null
+++ b/src/core/torrent/create-torrent.test.ts
@@ -0,0 +1,241 @@
+import { createHash } from 'node:crypto'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { encode, parseTorrent } from '@motrix/torrent'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import {
+ collectSourceFiles,
+ createTorrent,
+ isValidPieceLength,
+ suggestPieceLength,
+} from './create-torrent'
+
+const sha1 = (data: string | Uint8Array) =>
+ createHash('sha1').update(data).digest('hex')
+
+describe('collectSourceFiles', () => {
+ let dir: string
+ beforeAll(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'motrix-create-torrent-'))
+ await writeFile(path.join(dir, 'single.bin'), 'abc')
+ })
+ afterAll(async () => {
+ await rm(dir, { recursive: true, force: true })
+ })
+
+ it('maps a single file to a one-entry list', async () => {
+ const result = await collectSourceFiles(path.join(dir, 'single.bin'))
+ expect(result.name).toBe('single.bin')
+ expect(result.files).toHaveLength(1)
+ expect(result.totalSize).toBe(3)
+ })
+})
+
+describe('createTorrent', () => {
+ let dir: string
+ beforeAll(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'motrix-create-torrent-'))
+ await writeFile(path.join(dir, 'payload.bin'), 'abc')
+ })
+ afterAll(async () => {
+ await rm(dir, { recursive: true, force: true })
+ })
+
+ it('hashes a known payload: pieces = SHA-1("abc")', async () => {
+ const result = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ })
+ // 'abc' → a9993e364706816aba3e25717850c26c9cd0d89d (FIPS vector)
+ const abcDigest = createHash('sha1').update('abc').digest()
+ expect(Buffer.from(result.bytes).indexOf(abcDigest)).toBeGreaterThan(-1)
+ expect(result.pieceCount).toBe(1)
+ expect(result.totalSize).toBe(3)
+ // infoHash = SHA-1 of the exact info dict the encoder produced
+ const info = {
+ length: 3,
+ name: 'payload.bin',
+ 'piece length': 16 * 1024,
+ pieces: createHash('sha1').update('abc').digest(),
+ }
+ expect(result.infoHash).toBe(sha1(encode(info)))
+ })
+
+ it('emits progress covering the full size', async () => {
+ const seen: Array<[number, number]> = []
+ await createTorrent(
+ { sourcePath: path.join(dir, 'payload.bin'), pieceLength: 16 * 1024 },
+ { onProgress: (processed, total) => seen.push([processed, total]) }
+ )
+ expect(seen.at(-1)).toEqual([3, 3])
+ expect(seen.every(([, total]) => total === 3)).toBe(true)
+ })
+
+ it('includes announce/announce-list, comment, and private flags', async () => {
+ const result = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ trackers: ['https://tracker.example/announce', 'udp://t2.example:1337'],
+ comment: 'made by tests',
+ private: true,
+ })
+ const raw = Buffer.from(result.bytes).toString('latin1')
+ expect(raw).toContain('8:announce32:https://tracker.example/announce')
+ expect(raw).toContain('13:announce-list')
+ expect(raw).toContain('7:comment13:made by tests')
+ expect(parseTorrent(result.bytes).private).toBe(true)
+ })
+
+ it('omits announce entirely for DHT-only torrents', async () => {
+ const result = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ })
+ expect(Buffer.from(result.bytes).toString('latin1')).not.toContain(
+ 'announce'
+ )
+ })
+
+ it('concatenates pieces across file boundaries in sorted order', async () => {
+ const folder = path.join(dir, 'multi')
+ await mkdir(folder)
+ await writeFile(path.join(folder, 'a.bin'), 'hello ')
+ await writeFile(path.join(folder, 'b.bin'), 'world')
+ const result = await createTorrent({
+ sourcePath: folder,
+ pieceLength: 16 * 1024,
+ })
+ // One piece spanning both files = sha1('hello world')
+ const helloWorldDigest = createHash('sha1').update('hello world').digest()
+ expect(Buffer.from(result.bytes).indexOf(helloWorldDigest)).toBeGreaterThan(
+ -1
+ )
+ expect(result.fileCount).toBe(2)
+ const raw = Buffer.from(result.bytes).toString('latin1')
+ expect(raw).toContain('6:lengthi6e4:pathl5:a.bine')
+ expect(raw).toContain('6:lengthi5e4:pathl5:b.bine')
+ })
+
+ it('is deterministic apart from the creation date', async () => {
+ const a = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ comment: 'x',
+ })
+ const b = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ comment: 'x',
+ })
+ expect(a.infoHash).toBe(b.infoHash)
+ expect(parseTorrent(a.bytes).infoBytes).toEqual(
+ parseTorrent(b.bytes).infoBytes
+ )
+ })
+
+ it('produces bytes that parse-torrent reads back with matching infohash', async () => {
+ const result = await createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 16 * 1024,
+ trackers: ['https://tracker.example/announce'],
+ comment: 'roundtrip',
+ })
+ const parsed = parseTorrent(new Uint8Array(result.bytes))
+ expect(parsed.identity).toMatchObject({ sha1: result.infoHash })
+ expect(parsed.name).toBe('payload.bin')
+ expect(parsed.v1?.length).toBe(3n)
+ expect(parsed.announce).toBe('https://tracker.example/announce')
+ })
+
+ it('handles a zero-byte file with an empty pieces string', async () => {
+ await writeFile(path.join(dir, 'empty.bin'), '')
+ const result = await createTorrent({
+ sourcePath: path.join(dir, 'empty.bin'),
+ pieceLength: 16 * 1024,
+ })
+ // Zero pieces → 'pieces' must be a zero-length byte string, not
+ // sha1('') — the empty digest would be 20 bytes of bogus data.
+ const raw = Buffer.from(result.bytes).toString('latin1')
+ expect(raw).toContain('6:pieces0:')
+ expect(result.pieceCount).toBe(0)
+ })
+
+ it('hashes individual pieces across file boundaries including the final tail', async () => {
+ const src = path.join(dir, 'split')
+ await mkdir(src)
+ const chunk = 32768
+ const data = Buffer.concat([
+ Buffer.alloc(chunk, 1),
+ Buffer.alloc(chunk, 2),
+ Buffer.from('tail'),
+ ])
+ await writeFile(path.join(src, 'a'), data.subarray(0, 17001))
+ await writeFile(path.join(src, 'b'), data.subarray(17001))
+ const result = await createTorrent({ sourcePath: src, pieceLength: chunk })
+ const parsed = parseTorrent(result.bytes)
+ expect(parsed.v1?.pieces.length).toBe(3)
+ for (let i = 0; i < 3; i++)
+ expect(parsed.v1?.pieces.hex(i)).toBe(
+ sha1(data.subarray(i * chunk, (i + 1) * chunk))
+ )
+ })
+
+ it('preserves directory shape even with a single nested file and distinguishes private swarms', async () => {
+ const src = path.join(dir, 'one')
+ await mkdir(path.join(src, 'nested'), { recursive: true })
+ await writeFile(path.join(src, 'nested', 'x'), 'abc')
+ const opts = {
+ sourcePath: src,
+ trackers: ['https://tracker.example/announce'],
+ webSeeds: ['https://seed.example/'],
+ }
+ const publicResult = await createTorrent(opts)
+ const result = await createTorrent({ ...opts, private: true })
+ const parsed = parseTorrent(result.bytes)
+ expect(parsed.v1?.multiFile).toBe(true)
+ expect(
+ parsed.v1?.files[0].path.map((p) => new TextDecoder().decode(p))
+ ).toEqual(['nested', 'x'])
+ expect(parsed.webSeeds).toEqual(opts.webSeeds)
+ expect(parsed.private).toBe(true)
+ expect(publicResult.infoHash).not.toBe(result.infoHash)
+ })
+
+ it('rejects a source modified while being hashed', async () => {
+ const { truncateSync } = await import('node:fs')
+ const file = path.join(dir, 'changing')
+ await writeFile(file, Buffer.alloc(2 * 1024 ** 2))
+ await expect(
+ createTorrent(
+ { sourcePath: file },
+ {
+ onProgress(done, total) {
+ if (done < total) truncateSync(file, 0)
+ },
+ }
+ )
+ ).rejects.toThrow('changed')
+ })
+ it('rejects invalid piece lengths', async () => {
+ await expect(
+ createTorrent({
+ sourcePath: path.join(dir, 'payload.bin'),
+ pieceLength: 15000,
+ })
+ ).rejects.toThrow()
+ })
+})
+
+describe('piece length helpers', () => {
+ it('suggests larger pieces for larger inputs', () => {
+ expect(suggestPieceLength(1024)).toBe(32 * 1024)
+ expect(suggestPieceLength(4 * 1024 * 1024 * 1024)).toBe(2 * 1024 * 1024)
+ })
+
+ it('validates powers of two within bounds', () => {
+ expect(isValidPieceLength(16 * 1024)).toBe(true)
+ expect(isValidPieceLength(15 * 1024)).toBe(false)
+ expect(isValidPieceLength(32 * 1024 * 1024)).toBe(false)
+ })
+})
diff --git a/src/core/torrent/create-torrent.ts b/src/core/torrent/create-torrent.ts
new file mode 100644
index 00000000..e30b4810
--- /dev/null
+++ b/src/core/torrent/create-torrent.ts
@@ -0,0 +1,210 @@
+import { createHash } from 'node:crypto'
+import { constants, type Stats } from 'node:fs'
+import { lstat, open, opendir, realpath } from 'node:fs/promises'
+import path from 'node:path'
+import { type BInput, encode } from '@motrix/torrent'
+import { MAX_TORRENT_FILE_SIZE } from '@shared/lib/torrent-meta'
+import {
+ type CreateTorrentRequest,
+ createTorrentRequestSchema,
+} from '@shared/schemas/create-torrent'
+
+export { isValidPieceLength } from '@shared/schemas/create-torrent'
+export interface CreateTorrentOptions extends Partial<CreateTorrentRequest> {
+ sourcePath: string
+}
+export interface CreateTorrentHooks {
+ onProgress?: (processed: number, total: number) => void
+ signal?: AbortSignal
+ picked?: { path: string; dev: number; ino: number }
+ /** Hosts with per-user filesystem access must authorize descendants before listing or hashing. */
+ authorizeEntry?: (path: string, kind: 'file' | 'directory') => Promise<void>
+}
+// Bound the path/stat snapshot even when a directory contains mostly empty files.
+const MAX_SOURCE_ENTRIES = 100_000
+
+interface SourceFile {
+ absolute: string
+ segments: string[]
+ stat: Stats
+}
+export function suggestPieceLength(totalSize: number): number {
+ if (totalSize <= 64 * 1024 ** 2) return 32 * 1024
+ if (totalSize <= 512 * 1024 ** 2) return 128 * 1024
+ if (totalSize <= 2 * 1024 ** 3) return 512 * 1024
+ if (totalSize <= 8 * 1024 ** 3) return 2 * 1024 ** 2
+ return 8 * 1024 ** 2
+}
+function compareSegments(a: string[], b: string[]): number {
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
+ const diff = Buffer.compare(Buffer.from(a[i]), Buffer.from(b[i]))
+ if (diff !== 0) return diff
+ }
+ return a.length - b.length
+}
+export async function collectSourceFiles(
+ source: string,
+ hooks: CreateTorrentHooks = {}
+) {
+ const { signal, picked } = hooks
+ const sourcePath = await realpath(source)
+ const base = await lstat(sourcePath)
+ if (
+ picked &&
+ (sourcePath !== picked.path ||
+ base.dev !== picked.dev ||
+ base.ino !== picked.ino)
+ )
+ throw new Error('Selected source has been replaced')
+ const name = path.basename(sourcePath)
+ if (!name) throw new Error('A filesystem root cannot be a torrent source')
+ const files: SourceFile[] = []
+ const directories: SourceFile[] = []
+ let totalSize = 0
+ let visited = 0
+ const visit = async (absolute: string, segments: string[], stat: Stats) => {
+ signal?.throwIfAborted()
+ if (++visited > MAX_SOURCE_ENTRIES)
+ throw new Error('Too many source entries')
+ if (stat.isSymbolicLink()) return
+ if (path.basename(absolute).includes('\\'))
+ throw new Error('Unrepresentable torrent path')
+ if (stat.isDirectory()) {
+ await hooks.authorizeEntry?.(absolute, 'directory')
+ directories.push({ absolute, segments, stat })
+ for await (const entry of await opendir(absolute)) {
+ const child = path.join(absolute, entry.name)
+ await visit(child, [...segments, entry.name], await lstat(child))
+ }
+ } else if (stat.isFile()) {
+ await hooks.authorizeEntry?.(absolute, 'file')
+ totalSize += stat.size
+ if (!Number.isSafeInteger(totalSize))
+ throw new Error('Source exceeds torrent creation limits')
+ files.push({ absolute, segments, stat })
+ }
+ }
+ await visit(sourcePath, base.isDirectory() ? [] : [name], base)
+ files.sort((a, b) => compareSegments(a.segments, b.segments))
+ return { name, files, directories, totalSize, directory: base.isDirectory() }
+}
+function unchanged(expected: Stats, actual: Stats) {
+ return (
+ actual.isFile() === expected.isFile() &&
+ actual.isDirectory() === expected.isDirectory() &&
+ expected.dev === actual.dev &&
+ expected.ino === actual.ino &&
+ expected.size === actual.size &&
+ expected.mtimeMs === actual.mtimeMs &&
+ expected.ctimeMs === actual.ctimeMs
+ )
+}
+export async function createTorrent(
+ options: CreateTorrentOptions,
+ hooks: CreateTorrentHooks = {}
+) {
+ const { sourcePath, ...raw } = options
+ const settings = createTorrentRequestSchema.parse(raw)
+ const { name, files, directories, totalSize, directory } =
+ await collectSourceFiles(sourcePath, hooks)
+ if (!files.length) throw new Error('Source contains no regular files')
+ const pieceLength = settings.pieceLength ?? suggestPieceLength(totalSize)
+ const pieceCount = Math.ceil(totalSize / pieceLength)
+ if (pieceCount * 20 > MAX_TORRENT_FILE_SIZE)
+ throw new Error('Piece table exceeds the metainfo size limit')
+ const pieces = Buffer.alloc(pieceCount * 20)
+ let hash = createHash('sha1')
+ let filled = 0
+ let index = 0
+ let processed = 0
+ const finishPiece = () => {
+ pieces.set(hash.digest(), index++ * 20)
+ hash = createHash('sha1')
+ filled = 0
+ }
+ const scratch = Buffer.allocUnsafe(1024 ** 2)
+ const changed = () => new Error('Torrent source changed while hashing')
+ for (const file of files) {
+ hooks.signal?.throwIfAborted()
+ await hooks.authorizeEntry?.(file.absolute, 'file')
+ if ((await realpath(file.absolute)) !== file.absolute) throw changed()
+ const fd = await open(
+ file.absolute,
+ constants.O_RDONLY |
+ (constants.O_NOFOLLOW ?? 0) |
+ (constants.O_NONBLOCK ?? 0)
+ )
+ try {
+ if (!unchanged(file.stat, await fd.stat())) throw changed()
+ let remaining = file.stat.size
+ while (remaining > 0) {
+ hooks.signal?.throwIfAborted()
+ const { bytesRead } = await fd.read(
+ scratch,
+ 0,
+ Math.min(scratch.length, remaining),
+ null
+ )
+ if (!bytesRead) throw changed()
+ remaining -= bytesRead
+ for (let offset = 0; offset < bytesRead; ) {
+ const length = Math.min(pieceLength - filled, bytesRead - offset)
+ hash.update(scratch.subarray(offset, offset + length))
+ filled += length
+ offset += length
+ if (filled === pieceLength) finishPiece()
+ }
+ processed += bytesRead
+ hooks.onProgress?.(processed, totalSize)
+ }
+ if (!unchanged(file.stat, await fd.stat())) throw changed()
+ } finally {
+ await fd.close()
+ }
+ }
+ for (const file of [...files, ...directories]) {
+ hooks.signal?.throwIfAborted()
+ if (
+ !unchanged(file.stat, await lstat(file.absolute)) ||
+ (await realpath(file.absolute)) !== file.absolute
+ )
+ throw changed()
+ }
+ if (filled) finishPiece()
+ const info: Record<string, BInput> = {
+ name,
+ 'piece length': pieceLength,
+ pieces,
+ }
+ if (directory)
+ info.files = files.map((file) => ({
+ length: file.stat.size,
+ path: file.segments,
+ }))
+ else info.length = totalSize
+ if (settings.private) info.private = 1
+ const limits = { maxBytes: MAX_TORRENT_FILE_SIZE }
+ const infoHash = createHash('sha1').update(encode(info, limits)).digest('hex')
+ const meta: Record<string, BInput> = {
+ info,
+ 'creation date': Math.floor(Date.now() / 1000),
+ }
+ if (settings.trackers.length) {
+ meta.announce = settings.trackers[0]
+ meta['announce-list'] = settings.trackers.map((url) => [url])
+ }
+ if (settings.webSeeds.length) meta['url-list'] = settings.webSeeds
+ if (settings.comment) meta.comment = settings.comment
+ const bytes = encode(meta, limits)
+ hooks.onProgress?.(totalSize, totalSize)
+ return {
+ bytes,
+ infoHash,
+ name,
+ totalSize,
+ directory,
+ fileCount: files.length,
+ pieceCount,
+ pieceLength,
+ }
+}
diff --git a/src/main/commands/definitions/task.commands.ts b/src/main/commands/definitions/task.commands.ts
index c4200112..bbf2a108 100644
--- a/src/main/commands/definitions/task.commands.ts
+++ b/src/main/commands/definitions/task.commands.ts
@@ -9,6 +9,11 @@ export function registerTaskCommands(
registry: CommandRegistry,
_deps: CommandDeps
): void {
+ registry.register({
+ id: CommandIds.CreateTorrentFile,
+ title: 'createTorrent.menuLabel',
+ run: ({ deps }) => deps.windowManager.show('create-torrent'),
+ })
registry.register({
id: CommandIds.TaskNew,
title: 'menu.task.newTask',
diff --git a/src/main/index.ts b/src/main/index.ts
index 6fd96bf3..3404b349 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -752,9 +752,9 @@ function dispatchWhenReady(
payload: unknown,
resolvePayload?: () => unknown
) {
- const id = (['main', 'add-task', 'onboarding'] as const).find(
- (id) => windowManager?.get(id) === win
- )
+ const id = (
+ ['main', 'add-task', 'onboarding', 'create-torrent'] as const
+ ).find((id) => windowManager?.get(id) === win)
if (!id || win.isDestroyed()) return
if (rendererRecovery?.intents.deliver(id, channel, payload, resolvePayload))
return
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index b0e93b7c..3a891a06 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -178,6 +178,7 @@ import { installManagedFfmpeg } from '../plugin/verified-ffmpeg-electron'
import type { createMainProxyApplier } from '../proxy/wiring'
import type { createRendererRecoveryRuntime } from '../window/renderer-recovery-runtime'
import type { WindowManager } from '../window/window-manager'
+import { torrentCreatorHandlers } from './commands/create-torrent'
import { createOpenTaskFileHandler } from './commands/open-task-file'
import { createRevealInFolderHandler } from './commands/reveal-in-folder'
import { createSetSelectedFilesHandler } from './commands/set-selected-files'
@@ -953,6 +954,15 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
+ ...torrentCreatorHandlers(
+ (sender) =>
+ windowManager.getWindowIdBySender(sender) === 'create-torrent',
+ directoryHistory.wrap(async (request) => {
+ await activatePluginsForTask('bt', '')
+ return createAndPersist(request)
+ }),
+ () => ctx.rendererRecovery?.supervisor.enterModal()
+ ),
[Commands.CreateTask]: directoryHistory.wrap(async (request: unknown) => {
try {
request = admitTaskCreateRequest(request)
@@ -2076,6 +2086,9 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {
channel === Commands.MinimizeCurrentWindow ||
channel === Commands.ToggleMaximizeCurrentWindow ||
channel === Commands.PickSaveDir ||
+ channel === Commands.PickTorrentSource ||
+ channel === Commands.CreateTorrent ||
+ channel === Commands.SaveTorrentFile ||
OPERATION_CHANNELS.has(channel) ||
channel === Commands.PickFile ||
channel === Commands.ResizeWindow ||
diff --git a/src/main/ipc/commands/create-torrent.test.ts b/src/main/ipc/commands/create-torrent.test.ts
new file mode 100644
index 00000000..7faeb470
--- /dev/null
+++ b/src/main/ipc/commands/create-torrent.test.ts
@@ -0,0 +1,176 @@
+import { EventEmitter } from 'node:events'
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { parseTorrent } from '@motrix/torrent'
+import { Commands } from '@shared/protocol/commands'
+import type { WebContents } from 'electron'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { torrentCreatorHandlers } from './create-torrent'
+
+const staging = vi.hoisted(() => ({
+ afterCreate: undefined as undefined | (() => Promise<void>),
+ noHardLinks: false,
+}))
+vi.mock('node:fs/promises', async (load) => {
+ const fs = await load<typeof import('node:fs/promises')>()
+ return {
+ ...fs,
+ link: async (from: string, to: string) => {
+ if (staging.noHardLinks)
+ throw Object.assign(new Error('Unsupported'), { code: 'EOPNOTSUPP' })
+ await fs.link(from, to)
+ },
+ mkdtemp: async (prefix: string) => {
+ const created = await fs.mkdtemp(prefix)
+ if (path.basename(prefix) === '.motrix-torrent-')
+ await staging.afterCreate?.()
+ return created
+ },
+ }
+})
+const { pick, save } = vi.hoisted(() => ({ pick: vi.fn(), save: vi.fn() }))
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: () => ({}) },
+ dialog: { showOpenDialog: pick, showSaveDialog: save },
+}))
+let dir: string
+const owner = Object.assign(new EventEmitter(), {
+ isDestroyed: () => false,
+ send: vi.fn(),
+}) as unknown as WebContents
+const seed = vi.fn()
+let handlers: ReturnType<typeof torrentCreatorHandlers>
+beforeEach(async () => {
+ vi.resetAllMocks()
+ staging.afterCreate = undefined
+ staging.noHardLinks = false
+ dir = await realpath(await mkdtemp(path.join(tmpdir(), 'creator-ipc-')))
+ handlers = torrentCreatorHandlers((sender) => sender === owner, seed)
+})
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true })
+})
+async function source(kind: 'file' | 'directory' = 'file') {
+ const item = path.join(dir, 'data')
+ if (kind === 'directory') {
+ await mkdir(item)
+ await writeFile(path.join(item, 'item'), 'abc')
+ } else await writeFile(item, 'abc')
+ pick.mockResolvedValue({ canceled: false, filePaths: [item] })
+ await handlers[Commands.PickTorrentSource](owner, kind)
+ expect(pick).toHaveBeenCalledWith(
+ {},
+ { properties: [kind === 'file' ? 'openFile' : 'openDirectory'] }
+ )
+ return item
+}
+it('rejects concurrent hashes and never trusts a renderer-provided source or artifact', async () => {
+ await source()
+ await expect(
+ handlers[Commands.CreateTorrent](owner, { sourcePath: dir })
+ ).rejects.toThrow()
+ const [first, second] = await Promise.allSettled([
+ handlers[Commands.CreateTorrent](owner, {}),
+ handlers[Commands.CreateTorrent](owner, {}),
+ ])
+ expect(first.status).toBe('fulfilled')
+ expect(second.status).toBe('rejected')
+ const regenerated = await handlers[Commands.CreateTorrent](owner, {
+ comment: 'updated',
+ })
+ if (first.status !== 'fulfilled') throw Error('Missing first result')
+ await expect(
+ handlers[Commands.SaveTorrentFile](owner, {
+ id: first.value.id,
+ seed: false,
+ })
+ ).rejects.toThrow()
+ await expect(
+ handlers[Commands.SaveTorrentFile](owner, {
+ id: regenerated.id,
+ seed: false,
+ torrentBase64: 'fake',
+ })
+ ).rejects.toThrow()
+ expect(save).not.toHaveBeenCalled()
+})
+it('preserves the result on save cancellation, protects source members, and saves without seeding', async () => {
+ const folder = await source('directory')
+ const result = await handlers[Commands.CreateTorrent](owner, {})
+ const commit = () =>
+ handlers[Commands.SaveTorrentFile](owner, { id: result.id, seed: false })
+ save.mockResolvedValueOnce({ canceled: true })
+ expect(await commit()).toBeNull()
+ save.mockResolvedValueOnce({
+ canceled: false,
+ filePath: path.join(folder, 'item'),
+ })
+ await expect(commit()).rejects.toThrow()
+ expect(await readFile(path.join(folder, 'item'), 'utf8')).toBe('abc')
+ const target = path.join(dir, 'export.torrent')
+ save.mockResolvedValue({ canceled: false, filePath: target })
+ expect(await commit()).toEqual({ path: target, seeding: 'not-requested' })
+ expect(
+ parseTorrent(new Uint8Array(await readFile(target))).v1?.multiFile
+ ).toBe(true)
+ expect(seed).not.toHaveBeenCalled()
+ await expect(commit()).rejects.toThrow()
+})
+it('reports a successful save separately from a rejected adoption', async () => {
+ await source()
+ const result = await handlers[Commands.CreateTorrent](owner, {})
+ const target = path.join(dir, 'export.torrent')
+ save.mockResolvedValue({ canceled: false, filePath: target })
+ seed.mockResolvedValue({ outcome: 'conflict' })
+ expect(
+ await handlers[Commands.SaveTorrentFile](owner, {
+ id: result.id,
+ seed: true,
+ })
+ ).toEqual({ path: target, seeding: 'failed' })
+ expect(seed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ saveDir: dir,
+ duplicatePolicy: 'use-existing',
+ selectedFiles: [0],
+ })
+ )
+ expect((await readFile(target)).length).toBeGreaterThan(0)
+})
+
+it('rejects a replacement source picked under the original filename', async () => {
+ const file = await source()
+ await rename(file, `${file}.original`)
+ await writeFile(file, 'unselected replacement')
+ await expect(handlers[Commands.CreateTorrent](owner, {})).rejects.toThrow(
+ 'replaced'
+ )
+ expect(save).not.toHaveBeenCalled()
+})
+
+it.each([false, true])(
+ 'preserves a competing file (volume without hard links: %s)',
+ async (noHardLinks) => {
+ staging.noHardLinks = noHardLinks
+ const folder = await source('directory')
+ const result = await handlers[Commands.CreateTorrent](owner, {})
+ const target = path.join(folder, 'new.torrent')
+ save.mockResolvedValue({ canceled: false, filePath: target })
+ staging.afterCreate = () =>
+ writeFile(target, 'other writer', { flag: 'wx' })
+ await expect(
+ handlers[Commands.SaveTorrentFile](owner, { id: result.id, seed: false })
+ ).rejects.toThrow()
+ expect(await readFile(target, 'utf8')).toBe('other writer')
+ expect(seed).not.toHaveBeenCalled()
+ }
+)
diff --git a/src/main/ipc/commands/create-torrent.ts b/src/main/ipc/commands/create-torrent.ts
new file mode 100644
index 00000000..cce6e85b
--- /dev/null
+++ b/src/main/ipc/commands/create-torrent.ts
@@ -0,0 +1,245 @@
+import { randomUUID } from 'node:crypto'
+import { constants } from 'node:fs'
+import {
+ copyFile,
+ link,
+ lstat,
+ mkdtemp,
+ realpath,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import path from 'node:path'
+import { createTorrent } from '@core/torrent/create-torrent'
+import { AppError, ErrorCode } from '@shared/errors'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import type {
+ TaskCreateCommandResult,
+ TaskCreateRequest,
+} from '@shared/schemas/add-task'
+import {
+ createTorrentRequestSchema,
+ pickTorrentSourceSchema,
+ saveTorrentFileRequestSchema,
+} from '@shared/schemas/create-torrent'
+import { BrowserWindow, dialog, type WebContents } from 'electron'
+
+type Created = Awaited<ReturnType<typeof createTorrent>>
+interface Selection {
+ path: string
+ dev: number
+ ino: number
+ result?: { id: string; torrent: Created }
+}
+const fail = () =>
+ new AppError(
+ ErrorCode.TorrentCreateFailed,
+ 'Torrent creator request is no longer available'
+ )
+
+// Claim an initially absent filename without replacing a competing writer.
+// FAT/exFAT and some network volumes do not support hard links.
+async function publishNewTorrent(file: string, target: string) {
+ try {
+ await link(file, target)
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code
+ if (
+ !['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV'].includes(
+ code ?? ''
+ )
+ )
+ throw error
+ await copyFile(file, target, constants.COPYFILE_EXCL)
+ }
+}
+
+export function torrentCreatorHandlers(
+ isCreator: (sender: WebContents) => boolean,
+ seed: (request: TaskCreateRequest) => Promise<TaskCreateCommandResult>,
+ enterModal?: () => (() => void) | undefined
+) {
+ async function nativeDialog<T>(show: () => Promise<T>): Promise<T> {
+ const leave = enterModal?.()
+ try {
+ return await show()
+ } finally {
+ leave?.()
+ }
+ }
+ const sessions = new WeakMap<WebContents, Selection>()
+ let busy = false
+ const exclusive = async <T>(
+ sender: WebContents,
+ action: () => Promise<T>
+ ): Promise<T> => {
+ if (busy || sender.isDestroyed() || !isCreator(sender)) throw fail()
+ busy = true
+ try {
+ return await action()
+ } finally {
+ busy = false
+ }
+ }
+ return {
+ [Commands.PickTorrentSource]: (sender: WebContents, raw: unknown) =>
+ exclusive(sender, async () => {
+ const kind = pickTorrentSourceSchema.parse(raw)
+ const win = BrowserWindow.fromWebContents(sender)
+ if (!win) throw fail()
+ const picked = await nativeDialog(() =>
+ dialog.showOpenDialog(win, {
+ properties: [kind === 'file' ? 'openFile' : 'openDirectory'],
+ })
+ )
+ if (picked.canceled || !picked.filePaths[0] || sender.isDestroyed())
+ return null
+ const source = await realpath(picked.filePaths[0])
+ const stat = await lstat(source)
+ if (kind === 'file' ? !stat.isFile() : !stat.isDirectory()) throw fail()
+ sessions.set(sender, { path: source, dev: stat.dev, ino: stat.ino })
+ return { path: source }
+ }),
+ [Commands.CreateTorrent]: (sender: WebContents, raw: unknown) =>
+ exclusive(sender, async () => {
+ const options = createTorrentRequestSchema.parse(raw)
+ const selection = sessions.get(sender)
+ if (!selection) throw fail()
+ delete selection.result
+ const abort = new AbortController()
+ const cancel = () => abort.abort()
+ sender.once('destroyed', cancel)
+ let last = 0
+ try {
+ const torrent = await createTorrent(
+ { ...options, sourcePath: selection.path },
+ {
+ signal: abort.signal,
+ picked: selection,
+ onProgress(processed, total) {
+ if (
+ sender.isDestroyed() ||
+ (processed !== total && Date.now() - last < 250)
+ )
+ return
+ last = Date.now()
+ sender.send(
+ Events.CreateTorrentProgress,
+ total ? Math.min(1, processed / total) : 1
+ )
+ },
+ }
+ )
+ abort.signal.throwIfAborted()
+ const id = randomUUID()
+ selection.result = { id, torrent }
+ const { bytes: _bytes, directory: _directory, ...summary } = torrent
+ return { ...summary, id }
+ } finally {
+ sender.removeListener('destroyed', cancel)
+ }
+ }),
+ [Commands.SaveTorrentFile]: (sender: WebContents, raw: unknown) =>
+ exclusive(sender, async () => {
+ const request = saveTorrentFileRequestSchema.parse(raw)
+ const selection = sessions.get(sender)
+ if (!selection?.result || selection.result.id !== request.id)
+ throw fail()
+ const { torrent } = selection.result
+ const win = BrowserWindow.fromWebContents(sender)
+ if (!win) throw fail()
+ const save = await nativeDialog(() =>
+ dialog.showSaveDialog(win, {
+ defaultPath: path.join(
+ path.dirname(selection.path),
+ `${torrent.name}.torrent`
+ ),
+ filters: [{ name: 'BitTorrent', extensions: ['torrent'] }],
+ })
+ )
+ if (save.canceled || !save.filePath || sender.isDestroyed()) return null
+ // Resolve the parent even for a new destination. Never follow an output
+ // symlink or replace an existing member of the selected directory.
+ const target = path.join(
+ await realpath(path.dirname(save.filePath)),
+ path.basename(save.filePath)
+ )
+ const stat = await lstat(target).catch((e: NodeJS.ErrnoException) => {
+ if (e.code !== 'ENOENT') throw e
+ return null
+ })
+ const relative = path.relative(selection.path, target)
+ if (stat) {
+ const sourceStat = await lstat(selection.path)
+ if (stat.dev === sourceStat.dev && stat.ino === sourceStat.ino)
+ throw fail()
+ if (torrent.directory) {
+ // Case-insensitive aliases and bind mounts need an identity check;
+ // a lexical containment check alone can miss the same directory.
+ for (let parent = path.dirname(target); ; ) {
+ const parentStat = await lstat(parent)
+ if (
+ parentStat.dev === sourceStat.dev &&
+ parentStat.ino === sourceStat.ino
+ )
+ throw fail()
+ const next = path.dirname(parent)
+ if (next === parent) break
+ parent = next
+ }
+ }
+ }
+ if (
+ !relative ||
+ stat?.isSymbolicLink() ||
+ (stat &&
+ torrent.directory &&
+ !relative.startsWith(`..${path.sep}`) &&
+ relative !== '..' &&
+ !path.isAbsolute(relative))
+ )
+ throw fail()
+ // Rename the directory entry itself; following a destination symlink
+ // between the check above and the write could overwrite source data.
+ const staging = await mkdtemp(
+ path.join(path.dirname(target), '.motrix-torrent-')
+ )
+ try {
+ const file = path.join(staging, 'metainfo')
+ await writeFile(file, torrent.bytes, { flag: 'wx', mode: 0o600 })
+ if (stat) await rename(file, target)
+ else await publishNewTorrent(file, target)
+ } finally {
+ await rm(staging, { recursive: true, force: true }).catch(
+ () => undefined
+ )
+ }
+ delete selection.result
+ if (!request.seed) return { path: target, seeding: 'not-requested' }
+ try {
+ const task = await seed({
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64: '' },
+ torrentBytes: Uint8Array.from(torrent.bytes),
+ selectedFiles: Array.from(
+ { length: torrent.fileCount },
+ (_, index) => index
+ ),
+ saveDir: path.dirname(selection.path),
+ duplicatePolicy: 'use-existing',
+ })
+ if (
+ task.outcome !== 'created' &&
+ task.outcome !== 'reused' &&
+ task.outcome !== 'rechecked'
+ )
+ throw fail()
+ return { path: target, seeding: 'submitted' }
+ } catch {
+ return { path: target, seeding: 'failed' }
+ }
+ }),
+ }
+}
diff --git a/src/main/menu/application-menu-snapshot.test.ts b/src/main/menu/application-menu-snapshot.test.ts
index b0c060f3..4610a520 100644
--- a/src/main/menu/application-menu-snapshot.test.ts
+++ b/src/main/menu/application-menu-snapshot.test.ts
@@ -171,13 +171,13 @@ function createManager(
type: 'submenu',
menuId: MenuIds.MenubarTask,
group: '2_hidden',
- submenu: MenuIds.MenubarFile,
+ submenu: MenuIds.Tray,
when: () => false,
})
menuRegistry.appendItem({
id: 'menubar.file.nested',
type: 'normal',
- menuId: MenuIds.MenubarFile,
+ menuId: MenuIds.Tray,
group: '1_nested',
commandId: 'test.nested',
})
@@ -315,6 +315,7 @@ describe('MenuManager application-menu snapshot', () => {
expect(snapshot.items.map((item) => item.id)).toEqual([
MenuItemIds.AppAbout,
MenuItemIds.ApplicationSubmenusSeparator,
+ MenuIds.MenubarFile,
MenuIds.MenubarTask,
MenuIds.MenubarEdit,
MenuIds.MenubarWindow,
@@ -322,15 +323,18 @@ describe('MenuManager application-menu snapshot', () => {
MenuItemIds.ApplicationQuitSeparator,
MenuItemIds.AppQuit,
])
- expect(snapshot.items[2]?.children?.[0]).toMatchObject({
+ expect(
+ snapshot.items.find((item) => item.id === MenuIds.MenubarTask)
+ ?.children?.[0]
+ ).toMatchObject({
id: MenuItemIds.TaskPause,
enabled: false,
visible: true,
})
expect(
- snapshot.items[5]?.children?.find(
- (item) => item.id === MenuItemIds.HelpWebsite
- )
+ snapshot.items
+ .find((item) => item.id === MenuIds.MenubarHelp)
+ ?.children?.find((item) => item.id === MenuItemIds.HelpWebsite)
).toMatchObject({ visible: false })
expect(changed).toHaveBeenCalledOnce()
@@ -354,7 +358,10 @@ describe('MenuManager application-menu snapshot', () => {
expect(manager.getApplicationMenuSnapshot().revision).toBe(2)
expect(changed).toHaveBeenCalledOnce()
expect(
- manager.getApplicationMenuSnapshot().items[2]?.children?.[0]?.enabled
+ manager
+ .getApplicationMenuSnapshot()
+ .items.find((item) => item.id === MenuIds.MenubarTask)?.children?.[0]
+ ?.enabled
).toBe(true)
contextStore.merge({ selectedTaskId: 'task-1' })
@@ -376,7 +383,9 @@ describe('MenuManager application-menu snapshot', () => {
expect(onApplicationMenuSet).toHaveBeenCalledTimes(2)
expect(
- manager.getApplicationMenuSnapshot().items[2]?.children?.[0]
+ manager
+ .getApplicationMenuSnapshot()
+ .items.find((item) => item.id === MenuIds.MenubarTask)?.children?.[0]
).toMatchObject({ enabled: true, visible: true })
manager.dispose()
diff --git a/src/main/menu/contributions/index.test.ts b/src/main/menu/contributions/index.test.ts
index 24b2ca24..d6fc2e17 100644
--- a/src/main/menu/contributions/index.test.ts
+++ b/src/main/menu/contributions/index.test.ts
@@ -9,7 +9,7 @@ describe('installAllMenubarContributions', () => {
installAllMenubarContributions(reg)
const ids = new Set(reg.listMenuIds())
expect(ids.has(MenuIds.MenubarApp)).toBe(true)
- expect(ids.has(MenuIds.MenubarFile)).toBe(false)
+ expect(ids.has(MenuIds.MenubarFile)).toBe(true)
expect(
reg
.getItems(MenuIds.MenubarWindow, 'darwin')
@@ -43,12 +43,13 @@ describe('installAllMenubarContributions', () => {
}
})
- it('task menu starts with New/NewBt/OpenFile', () => {
+ it('file menu separates downloading, opening and creating torrents', () => {
const reg = new MenuRegistry()
installAllMenubarContributions(reg)
- const items = reg.getItems(MenuIds.MenubarTask)
+ const items = reg.getItems(MenuIds.MenubarFile)
expect(items[0].commandId).toBe('motrix.task.new')
expect(items[1].commandId).toBe('motrix.task.newBt')
expect(items[2].commandId).toBe('motrix.task.openFile')
+ expect(items[3].commandId).toBe('motrix.torrent.create')
})
})
diff --git a/src/main/menu/contributions/shared.ts b/src/main/menu/contributions/shared.ts
index 42c55c16..33e2bdb9 100644
--- a/src/main/menu/contributions/shared.ts
+++ b/src/main/menu/contributions/shared.ts
@@ -9,7 +9,11 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
id: item.id,
type: 'normal',
menuId:
- item.section === 'task' ? MenuIds.MenubarTask : MenuIds.MenubarHelp,
+ item.section === 'file'
+ ? MenuIds.MenubarFile
+ : item.section === 'task'
+ ? MenuIds.MenubarTask
+ : MenuIds.MenubarHelp,
group: item.group,
order: item.order,
commandId: item.commandId,
diff --git a/src/main/menu/menu-manager.ts b/src/main/menu/menu-manager.ts
index 4329c7c8..1bccd0f9 100644
--- a/src/main/menu/menu-manager.ts
+++ b/src/main/menu/menu-manager.ts
@@ -33,6 +33,7 @@ export interface MenuManagerDeps {
const ROOT_MENUBAR_IDS: readonly MenuId[] = [
MenuIds.MenubarApp,
+ MenuIds.MenubarFile,
MenuIds.MenubarTask,
MenuIds.MenubarEdit,
MenuIds.MenubarWindow,
@@ -40,6 +41,7 @@ const ROOT_MENUBAR_IDS: readonly MenuId[] = [
]
const DROPDOWN_SUBMENU_IDS: readonly MenuId[] = [
+ MenuIds.MenubarFile,
MenuIds.MenubarTask,
MenuIds.MenubarEdit,
MenuIds.MenubarWindow,
diff --git a/src/main/window/renderer-recovery-runtime.ts b/src/main/window/renderer-recovery-runtime.ts
index 085ddaa1..c67981ca 100644
--- a/src/main/window/renderer-recovery-runtime.ts
+++ b/src/main/window/renderer-recovery-runtime.ts
@@ -178,8 +178,8 @@ export function createRendererRecoveryRuntime(deps: {
submissions,
recoverFocused: () => {
const id =
- (['onboarding', 'add-task', 'main'] as const).find((id) =>
- deps.windows().get(id)?.isFocused()
+ (['onboarding', 'create-torrent', 'add-task', 'main'] as const).find(
+ (id) => deps.windows().get(id)?.isFocused()
) ?? 'main'
if (!deps.windows().get(id)) {
deps.windows().show(id)
diff --git a/src/main/window/renderer-supervisor.ts b/src/main/window/renderer-supervisor.ts
index 08c8898c..7b230cd7 100644
--- a/src/main/window/renderer-supervisor.ts
+++ b/src/main/window/renderer-supervisor.ts
@@ -303,6 +303,7 @@ export class RendererSupervisor implements WindowLifecycle {
report.surface === 'route-error' ||
(report.surface === 'app' &&
(id === 'onboarding' ||
+ id === 'create-torrent' ||
slot.capabilities.has(
id === 'main' ? 'navigation' : 'add-task-hydration'
)))
diff --git a/src/main/window/window-configs.ts b/src/main/window/window-configs.ts
index 3818724e..f741aef3 100644
--- a/src/main/window/window-configs.ts
+++ b/src/main/window/window-configs.ts
@@ -1,4 +1,7 @@
-import { ADD_TASK_COLLAPSED_HEIGHT } from '@shared/constants/add-task'
+import {
+ ADD_TASK_COLLAPSED_HEIGHT,
+ TASK_FORM_WIDTH,
+} from '@shared/constants/add-task'
import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
import type { WindowId } from '@shared/types/window'
import { WindowRoutes } from '@shared/types/window'
@@ -42,7 +45,7 @@ export const WINDOW_CONFIGS: Record<WindowId, WindowConfig> = {
'add-task': {
id: 'add-task',
title: 'New Task',
- width: 640,
+ width: TASK_FORM_WIDTH,
height: ADD_TASK_COLLAPSED_HEIGHT,
resizable: false,
route: WindowRoutes['add-task'],
@@ -53,6 +56,21 @@ export const WINDOW_CONFIGS: Record<WindowId, WindowConfig> = {
liquidGlass: false,
transparent: false,
},
+ 'create-torrent': {
+ id: 'create-torrent',
+ title: 'Motrix',
+ width: TASK_FORM_WIDTH,
+ height: ADD_TASK_COLLAPSED_HEIGHT,
+ minWidth: 470,
+ minHeight: 290,
+ resizable: true,
+ route: WindowRoutes['create-torrent'],
+ closeBehavior: 'destroy',
+ persistBounds: false,
+ maximizable: false,
+ vibrancy: false,
+ liquidGlass: false,
+ },
onboarding: {
id: 'onboarding',
title: 'Motrix',
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index 38578fb5..e2ca03c3 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -117,6 +117,10 @@ export class WindowManager {
if (id !== requestedId) options = undefined
this.lastFocusRequested = id
let win = this.windows.get(id)
+ if (id === 'create-torrent' && win && !win.isDestroyed()) {
+ this.focusWindow(id, win)
+ return
+ }
if (!win || win.isDestroyed()) {
// Self-heal: a window with closeBehavior 'destroy' may have been
// destroyed by the user (e.g. clicking the traffic-light close
@@ -208,6 +212,7 @@ export class WindowManager {
if (
!this.willQuit &&
config.closeBehavior === 'destroy' &&
+ id !== 'create-torrent' &&
(id !== 'add-task' || this.shouldPrewarmAddTask())
) {
this.precreate(id)
diff --git a/src/renderer/app-root.tsx b/src/renderer/app-root.tsx
index b3c662df..b3584617 100644
--- a/src/renderer/app-root.tsx
+++ b/src/renderer/app-root.tsx
@@ -26,6 +26,15 @@ const AddTaskWindow = lazy(() =>
}))
)
+const CreateTorrentWindow =
+ __MOTRIX_TARGET__ === 'electron'
+ ? lazy(() =>
+ import('./components/create-torrent/create-torrent-window').then(
+ (m) => ({ default: m.CreateTorrentWindow })
+ )
+ )
+ : null
+
const OnboardingWindow = lazy(() =>
import('./windows/onboarding-window').then((module) => ({
default: module.OnboardingWindow,
@@ -42,9 +51,11 @@ const windowParam = params.get('w')
const windowId: RendererWindowId =
windowParam === 'add-task'
? 'add-task'
- : windowParam === 'onboarding'
- ? 'onboarding'
- : 'main'
+ : windowParam === 'create-torrent' && CreateTorrentWindow
+ ? 'create-torrent'
+ : windowParam === 'onboarding'
+ ? 'onboarding'
+ : 'main'
document.documentElement.classList.add(`platform-${transport.platform}`)
document.documentElement.classList.add(`window-${windowId}`)
@@ -95,6 +106,17 @@ export async function startRenderer(rootContainer: HTMLElement): Promise<void> {
</Root>
</RendererBoundary>
)
+ } else if (windowId === 'create-torrent' && CreateTorrentWindow) {
+ root.render(
+ <RendererBoundary>
+ <Root>
+ <Suspense fallback={<div aria-busy="true" />}>
+ <RendererReady />
+ <CreateTorrentWindow />
+ </Suspense>
+ </Root>
+ </RendererBoundary>
+ )
} else if (windowId === 'onboarding') {
root.render(
<RendererBoundary>
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
index 24e7dd41..1c6d34a0 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
@@ -207,16 +207,15 @@ describe('AddTaskDialogHost', () => {
renderWithRouter()
const dialog = screen.getByRole('dialog')
expect(dialog).toHaveClass(
- 'max-w-[640px]',
'gap-0',
'overflow-hidden',
'p-0',
'transition-[height]',
'duration-200',
'ease-out',
- 'motion-reduce:transition-none',
- 'sm:max-w-[640px]'
+ 'motion-reduce:transition-none'
)
+ expect(dialog.style.maxWidth).toBe('640px')
expect(dialog.style.height).toBe(`${ADD_TASK_COLLAPSED_HEIGHT}px`)
expect(dialog.style.maxHeight).toContain('760px')
expect(dialog.style.maxHeight).toContain('100vh')
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
index 06d6062c..713c4726 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
@@ -1,12 +1,6 @@
import { AddTaskForm } from '@renderer/components/add-task/add-task-form'
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from '@renderer/components/ui/dialog'
-import { WindowChromeCaptionIcon } from '@renderer/components/window-chrome/window-chrome'
+import { TaskFormDialog } from '@renderer/components/task-form-dialog'
+import { Dialog } from '@renderer/components/ui/dialog'
import { MenuConfirmation } from '@renderer/features/application-menu/menu-confirmation'
import { WebDirectoryPickerDialog } from '@renderer/features/web-directory-picker/web-directory-picker-dialog'
import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
@@ -165,21 +159,12 @@ export function AddTaskDialogHost() {
return (
<>
<Dialog open={open} onOpenChange={(v) => !v && requestClose()}>
- <DialogContent
- ref={dialogRef}
- showCloseButton={false}
- overlayClassName="transition-opacity duration-150 data-open:animate-none data-closed:animate-none data-starting-style:opacity-0 data-ending-style:opacity-0"
- className="flex w-[calc(100%-2rem)] max-w-[640px] flex-col gap-0 overflow-hidden p-0 transition-[height] duration-200 ease-out motion-reduce:transition-none sm:max-w-[640px]"
- style={{
- height: dialogHeight,
- maxHeight: `min(${ADD_TASK_MAX_HEIGHT}px, calc(100vh - 2rem))`,
- }}
+ <TaskFormDialog
+ contentRef={dialogRef}
+ title={t('task.add.title')}
+ busy={draft.busy}
+ height={dialogHeight}
>
- <DialogHeader className="h-10 shrink-0 justify-center px-4 pe-14">
- <DialogTitle className="pt-[14px] text-[13px] font-semibold">
- {t('task.add.title')}
- </DialogTitle>
- </DialogHeader>
<PlatformServicesProvider services={webServices}>
<AddTaskForm
active={open}
@@ -194,14 +179,7 @@ export function AddTaskDialogHost() {
subscribeEvents={false}
/>
</PlatformServicesProvider>
- <DialogClose
- disabled={draft.busy}
- aria-label={t('chrome.close')}
- className="app-no-drag absolute top-3.5 end-3.5 flex size-7 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-foreground outline-none transition-colors [&>svg]:opacity-65 hover:bg-accent hover:text-accent-foreground hover:[&>svg]:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:[&>svg]:opacity-90 dark:hover:bg-accent/50"
- >
- <WindowChromeCaptionIcon name="close" />
- </DialogClose>
- </DialogContent>
+ </TaskFormDialog>
</Dialog>
<MenuConfirmation
request={
diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsx
index fc9fbafc..bf0b4cb2 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -84,10 +84,10 @@ describe('AddTaskForm', () => {
await userEvent.type(screen.getByLabelText('Header value'), 'fresh-value')
await userEvent.click(screen.getByRole('button', { name: 'Download' }))
expect(
- await screen.findByText('Enter a header name or remove this header.')
+ await screen.findByText('Add a name for each header with a value.')
).toBeVisible()
expect(screen.getByLabelText('Header name')).toHaveAccessibleDescription(
- 'Enter a header name or remove this header.'
+ 'Add a name for each header with a value.'
)
expect(
invokeMock.mock.calls.filter(
@@ -104,6 +104,70 @@ describe('AddTaskForm', () => {
)
})
+ it('reuses the unfinished row and omits it from a download', async () => {
+ renderForm({
+ defaultValues: {
+ tab: 'links',
+ urls: 'https://example.com/a',
+ saveDir: '/d',
+ },
+ })
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Advanced' }))
+ const add = screen.getByRole('button', { name: 'Add header' })
+ await user.click(add)
+ await user.click(add)
+ const name = screen.getByLabelText('Header name')
+ expect(name).toHaveFocus()
+ await user.type(name, ' ')
+ await user.tab()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Download' }))
+ await waitFor(() =>
+ expect(invokeMock).toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.objectContaining({ headers: [] })
+ )
+ )
+ })
+
+ it('reveals incomplete headers on submit and shares one accessible hint until corrected', async () => {
+ const user = userEvent.setup()
+ renderForm({
+ defaultValues: {
+ tab: 'links',
+ urls: 'https://example.com/a',
+ saveDir: '/d',
+ extraHeaders: [
+ { name: '', value: 'one' },
+ { name: ' ', value: 'two' },
+ ],
+ },
+ })
+ await user.click(screen.getByRole('button', { name: 'Download' }))
+ const hint = await screen.findByRole('alert')
+ const [first, second] = screen.getAllByLabelText('Header name')
+ for (const name of [first, second]) {
+ expect(name).toHaveAttribute('aria-invalid', 'true')
+ expect(name).toHaveAccessibleDescription(hint.textContent ?? '')
+ }
+ await waitFor(() => expect(first).toHaveFocus())
+ await user.type(first, 'Accept')
+ expect(second).toHaveAttribute('aria-invalid', 'true')
+ await user.clear(screen.getAllByLabelText('Header value')[1])
+ await user.tab()
+ await waitFor(() =>
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ )
+ await user.click(screen.getByRole('button', { name: 'Download' }))
+ await waitFor(() =>
+ expect(invokeMock).toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.objectContaining({ headers: [{ name: 'Accept', value: 'one' }] })
+ )
+ )
+ })
+
it('keeps migration guidance visible while editing and submits only newly entered request settings', async () => {
renderForm({
defaultValues: {
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 4c9e2579..ce07f420 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -1,5 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { RendererSubmissionNotice } from '@renderer/components/renderer-recovery-notice'
+import { taskFormFooter } from '@renderer/components/task-form-layout'
import {
AlertDialog,
AlertDialogAction,
@@ -804,7 +805,7 @@ export function AddTaskForm({
ref={footerRef}
data-slot="add-task-form-footer"
className={cn(
- 'w-full shrink-0 border-t-[0.5px] border-border bg-background px-4 py-3',
+ taskFormFooter,
presentation === 'window' && 'fixed bottom-0 left-0'
)}
>
diff --git a/src/renderer/components/add-task/advanced-panel.tsx b/src/renderer/components/add-task/advanced-panel.tsx
index 0f5e0b85..dd1f6673 100644
--- a/src/renderer/components/add-task/advanced-panel.tsx
+++ b/src/renderer/components/add-task/advanced-panel.tsx
@@ -1,20 +1,11 @@
-import {
- ChevronRightIcon,
- HelpIcon,
- RemoveIcon,
-} from '@renderer/components/icons'
+import { AddIcon, HelpIcon, RemoveIcon } from '@renderer/components/icons'
+import { TaskFormAdvanced } from '@renderer/components/task-form-layout'
import { Button } from '@renderer/components/ui/button'
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from '@renderer/components/ui/collapsible'
import {
FormControl,
FormField,
FormItem,
FormLabel,
- useFormField,
} from '@renderer/components/ui/form'
import { Input } from '@renderer/components/ui/input'
import { Textarea } from '@renderer/components/ui/textarea'
@@ -22,8 +13,20 @@ import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { cn } from '@renderer/lib/utils'
import { EXTERNAL_URLS } from '@shared/external-urls'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
-import { type ReactNode, useLayoutEffect, useState } from 'react'
-import { useFieldArray, useFormContext, useWatch } from 'react-hook-form'
+import {
+ type ReactNode,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react'
+import {
+ useFieldArray,
+ useFormContext,
+ useFormState,
+ useWatch,
+} from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { useAddTaskLayoutChange } from './add-task-layout-context'
@@ -32,14 +35,36 @@ export function AdvancedPanel({
}: {
defaultOpen?: boolean
}) {
- const { t } = useTranslation()
const [open, setOpen] = useState(defaultOpen)
const onLayoutChange = useAddTaskLayoutChange()
+ const { control, getValues, getFieldState, setFocus } =
+ useFormContext<AddTaskFormValues>()
+ const { submitCount } = useFormState({ control })
+ const lastSubmit = useRef(submitCount)
+ const pendingFocus = useRef<number | null>(null)
const tab = useWatch<AddTaskFormValues, 'tab'>({ name: 'tab' })
const requestOptions = useWatch<AddTaskFormValues, 'legacyRequestOptions'>({
name: 'legacyRequestOptions',
})
+ useEffect(() => {
+ if (lastSubmit.current === submitCount) return
+ lastSubmit.current = submitCount
+ if (open || tab !== 'links') return
+ const index = (getValues('extraHeaders') ?? []).findIndex(
+ (_, i) => getFieldState(`extraHeaders.${i}.name`).invalid
+ )
+ if (index < 0) return
+ pendingFocus.current = index
+ setOpen(true)
+ }, [submitCount, open, tab, getValues, getFieldState])
+ useEffect(() => {
+ if (open && pendingFocus.current !== null) {
+ setFocus(`extraHeaders.${pendingFocus.current}.name`)
+ pendingFocus.current = null
+ }
+ }, [open, setFocus])
+
useLayoutEffect(() => {
if (tab === 'links' && requestOptions !== undefined) setOpen(true)
}, [requestOptions, tab])
@@ -49,30 +74,9 @@ export function AdvancedPanel({
}, [onLayoutChange, open])
return (
- <Collapsible open={open} onOpenChange={setOpen}>
- <CollapsibleTrigger
- render={
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="-ms-2 h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground hover:bg-transparent dark:hover:bg-transparent"
- />
- }
- >
- <ChevronRightIcon
- className={cn(
- 'h-3.5 w-3.5 transition-transform duration-150',
- open && 'rotate-90'
- )}
- aria-hidden="true"
- />
- {t('task.add.advanced')}
- </CollapsibleTrigger>
- <CollapsibleContent className="mt-2 ms-1.5 space-y-2 border-s-2 border-border ps-3">
- {tab === 'links' ? <LinksAdvancedFields /> : <TorrentAdvancedFields />}
- </CollapsibleContent>
- </Collapsible>
+ <TaskFormAdvanced open={open} onOpenChange={setOpen}>
+ {tab === 'links' ? <LinksAdvancedFields /> : <TorrentAdvancedFields />}
+ </TaskFormAdvanced>
)
}
@@ -141,88 +145,122 @@ function LinksAdvancedFields() {
function ExtraHeadersFields() {
const { t } = useTranslation()
- const { control } = useFormContext<AddTaskFormValues>()
+ const labelId = useId()
+ const errorId = useId()
+ const { control, getFieldState, getValues, setFocus } =
+ useFormContext<AddTaskFormValues>()
+ const state = useFormState({ control, name: 'extraHeaders' })
const { fields, append, remove } = useFieldArray({
control,
name: 'extraHeaders',
})
+ const hasNameError = fields.some(
+ (_, index) => getFieldState(`extraHeaders.${index}.name`, state).invalid
+ )
+ const addHeader = () => {
+ const rows = getValues('extraHeaders') ?? []
+ const unnamed = rows.findIndex((row) => !row.name.trim())
+ if (unnamed !== -1) {
+ setFocus(`extraHeaders.${unnamed}.name`)
+ return
+ }
+ append(
+ { name: '', value: '' },
+ { focusName: `extraHeaders.${rows.length}.name` }
+ )
+ }
return (
- <fieldset className="space-y-2">
- <legend className="text-xs text-muted-foreground">
+ <fieldset
+ aria-labelledby={labelId}
+ className="grid min-w-0 grid-cols-[5rem_minmax(0,1fr)] items-start gap-3"
+ >
+ <span
+ id={labelId}
+ className="pt-2 text-xs leading-4 text-muted-foreground"
+ >
{t('task.add.extraHeaders')}
- </legend>
- {fields.map((field, index) => (
- <div key={field.id} className="flex min-w-0 items-center gap-2">
- <FormField
- control={control}
- name={`extraHeaders.${index}.name`}
- render={({ field: nameField }) => (
- <FormItem className="min-w-0 flex-1">
- <FormLabel className="sr-only">
- {t('task.add.headerName')}
- </FormLabel>
- <FormControl>
- <Input
- {...nameField}
- placeholder={t('task.add.headerName')}
- className="h-8 text-xs"
- />
- </FormControl>
- <HeaderNameError />
- </FormItem>
- )}
- />
- <FormField
- control={control}
- name={`extraHeaders.${index}.value`}
- render={({ field: valueField }) => (
- <FormItem className="min-w-0 flex-[2]">
- <FormLabel className="sr-only">
- {t('task.add.headerValue')}
- </FormLabel>
- <FormControl>
- <Input
- {...valueField}
- placeholder={t('task.add.headerValue')}
- className="h-8 text-xs"
- />
- </FormControl>
- </FormItem>
- )}
- />
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- aria-label={t('task.add.removeHeader')}
- onClick={() => remove(index)}
+ </span>
+ <div className="@container/headers flex min-h-8 min-w-0 flex-col justify-center gap-1.5">
+ {fields.map((field, index) => (
+ <div
+ key={field.id}
+ className="grid min-w-0 grid-cols-[minmax(0,1fr)_1.5rem] items-start gap-x-2 gap-y-1 @min-[16rem]/headers:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_1.5rem]"
>
- <RemoveIcon aria-hidden="true" />
- </Button>
- </div>
- ))}
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={() => append({ name: '', value: '' })}
- >
- {t('task.add.addHeader')}
- </Button>
+ <FormField
+ control={control}
+ name={`extraHeaders.${index}.name`}
+ render={({ field: nameField, fieldState }) => (
+ <FormItem className="min-w-0">
+ <FormLabel className="sr-only">
+ {t('task.add.headerName')}
+ </FormLabel>
+ <FormControl
+ aria-describedby={fieldState.invalid ? errorId : undefined}
+ >
+ <Input
+ {...nameField}
+ placeholder={t('task.add.headerName')}
+ className="h-8 text-xs"
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={control}
+ name={`extraHeaders.${index}.value`}
+ rules={{ deps: `extraHeaders.${index}.name` }}
+ render={({ field: valueField }) => (
+ <FormItem className="col-start-1 row-start-2 min-w-0 @min-[16rem]/headers:col-start-2 @min-[16rem]/headers:row-start-1">
+ <FormLabel className="sr-only">
+ {t('task.add.headerValue')}
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...valueField}
+ placeholder={t('task.add.headerValue')}
+ className="h-8 text-xs"
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="col-start-2 row-start-1 mt-1 text-muted-foreground hover:text-foreground @min-[16rem]/headers:col-start-3"
+ aria-label={t('task.add.removeHeader')}
+ onClick={() => remove(index)}
+ >
+ <RemoveIcon aria-hidden="true" />
+ </Button>
+ </div>
+ ))}
+ {hasNameError && (
+ <p
+ id={errorId}
+ role="alert"
+ className="text-xs leading-4 text-destructive"
+ >
+ {t('task.add.errors.headerNameRequired')}
+ </p>
+ )}
+ <Button
+ type="button"
+ size="xs"
+ variant="ghost"
+ className="-ms-1.5 self-start font-normal text-muted-foreground hover:text-foreground"
+ onClick={addHeader}
+ >
+ <AddIcon aria-hidden="true" className="size-3.5" />
+ {t('task.add.addHeader')}
+ </Button>
+ </div>
</fieldset>
)
}
-function HeaderNameError() {
- const { t } = useTranslation()
- const { error, formMessageId } = useFormField()
- return error ? (
- <p id={formMessageId} role="alert" className="text-xs text-destructive">
- {t('task.add.errors.headerNameRequired')}
- </p>
- ) : null
-}
-
function TorrentAdvancedFields() {
const { unitSystem, formatByteUnit } = useByteFormat()
const scale = unitSystem === 'binary' ? 1024 : 1000
diff --git a/src/renderer/components/add-task/footer-actions.tsx b/src/renderer/components/add-task/footer-actions.tsx
index 92ac9a2d..f5949ec8 100644
--- a/src/renderer/components/add-task/footer-actions.tsx
+++ b/src/renderer/components/add-task/footer-actions.tsx
@@ -1,3 +1,4 @@
+import { taskFormActions } from '@renderer/components/task-form-layout'
import { Button } from '@renderer/components/ui/button'
import { useTranslation } from 'react-i18next'
@@ -31,7 +32,7 @@ export function FooterActions({
<span className="min-w-0 truncate text-xs text-muted-foreground">
{torrentQueue ? t('task.add.torrentQueueProgress', torrentQueue) : null}
</span>
- <div className="flex shrink-0 items-center gap-2">
+ <div className={taskFormActions}>
<Button
type="button"
variant="outline"
diff --git a/src/renderer/components/create-torrent/create-torrent-form.tsx b/src/renderer/components/create-torrent/create-torrent-form.tsx
new file mode 100644
index 00000000..dd4a41dd
--- /dev/null
+++ b/src/renderer/components/create-torrent/create-torrent-form.tsx
@@ -0,0 +1,496 @@
+import {
+ CheckIcon,
+ ChevronLeftIcon,
+ WarningIcon,
+} from '@renderer/components/icons'
+import { SettingsSelectTrigger } from '@renderer/components/settings-kit/settings-select-trigger'
+import {
+ TaskFormAdvanced,
+ taskFormActions,
+ taskFormFooter,
+} from '@renderer/components/task-form-layout'
+import { Alert, AlertDescription } from '@renderer/components/ui/alert'
+import { Button } from '@renderer/components/ui/button'
+import { Input } from '@renderer/components/ui/input'
+import { Progress } from '@renderer/components/ui/progress'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectValue,
+} from '@renderer/components/ui/select'
+import { Spinner } from '@renderer/components/ui/spinner'
+import { Textarea } from '@renderer/components/ui/textarea'
+import { useAdaptiveWindowHeight } from '@renderer/hooks/use-adaptive-window-height'
+import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { transport } from '@renderer/lib/transport'
+import { cn } from '@renderer/lib/utils'
+import {
+ ADD_TASK_COLLAPSED_HEIGHT,
+ ADD_TASK_MAX_HEIGHT,
+} from '@shared/constants/add-task'
+import { windowChromeHeight } from '@shared/constants/window-chrome'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import {
+ CREATE_TORRENT_COMMENT_MAX,
+ CREATE_TORRENT_URL_LIMIT,
+ type CreateTorrentResultPayload,
+ createTorrentProgressSchema,
+ createTorrentRequestSchema,
+ createTorrentResultSchema,
+ pickedTorrentSourceSchema,
+ saveTorrentFileResultSchema,
+} from '@shared/schemas/create-torrent'
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ ControlRow,
+ type PickedSource,
+ type SourceKind,
+ SourcePicker,
+ ToggleRow,
+ TorrentSummary,
+} from './creator-sections'
+import type { ServerTorrentClient } from './server-torrent-client'
+
+const textField =
+ 'bg-background text-[13px] leading-5 placeholder:text-xs md:text-[13px]'
+const listField = cn(
+ textField,
+ 'field-sizing-fixed h-[3.25rem] min-h-0 resize-y py-1.5'
+)
+const pieceSizes = [32, 128, 512, 1024, 2048, 4096, 8192, 16384]
+const lines = (text: string) =>
+ text
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+type Status = 'draft' | 'picking' | 'hashing' | 'ready' | 'saving' | 'done'
+export function CreateTorrentForm({
+ server,
+ onClose,
+ onBusyChange,
+}: {
+ server?: ServerTorrentClient
+ onClose: () => void
+ onBusyChange?: (busy: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { formatBytes } = useByteFormat()
+ const [advanced, setAdvanced] = useState(false)
+ const [source, setSource] = useState<PickedSource | null>(null)
+ const [trackers, setTrackers] = useState('')
+ const [webSeeds, setWebSeeds] = useState('')
+ const [comment, setComment] = useState('')
+ const [isPrivate, setPrivate] = useState(false)
+ const [piece, setPiece] = useState('auto')
+ const [seed, setSeed] = useState(false)
+ const [progress, setProgress] = useState(0)
+ const [error, setError] = useState('')
+ const [invalidField, setInvalidField] = useState<
+ 'trackers' | 'webSeeds' | null
+ >(null)
+ const [status, setStatus] = useState<Status>('draft')
+ const [result, setResult] = useState<CreateTorrentResultPayload | null>(null)
+ const [saved, setSaved] = useState<ReturnType<
+ typeof saveTorrentFileResultSchema.parse
+ > | null>(null)
+ const busy = useRef(false)
+ const headerHeight = server
+ ? 40
+ : windowChromeHeight(transport.platform, false)
+ // Footer: a 32px small button, 12px block padding on each side and a half-pixel rule.
+ const chromeHeight = headerHeight + 57
+ useEffect(() => {
+ onBusyChange?.(status === 'saving')
+ }, [onBusyChange, status])
+ useAdaptiveWindowHeight({
+ minHeight: result ? 292 : ADD_TASK_COLLAPSED_HEIGHT,
+ maxHeight: Math.min(
+ ADD_TASK_MAX_HEIGHT,
+ window.screen.availHeight || ADD_TASK_MAX_HEIGHT
+ ),
+ chromeHeight,
+ enabled: !server,
+ })
+ useEffect(() => {
+ if (server) return
+ const update = (value: unknown) => {
+ const p = createTorrentProgressSchema.safeParse(value)
+ if (p.success) setProgress(Math.round(p.data * 100))
+ }
+ transport.on(Events.CreateTorrentProgress, update)
+ return () => transport.off(Events.CreateTorrentProgress, update)
+ }, [server])
+ useEffect(() => {
+ if (invalidField)
+ document
+ .getElementById(
+ invalidField === 'webSeeds' ? 'creator-web-seeds' : 'creator-trackers'
+ )
+ ?.focus()
+ }, [invalidField])
+ const pick = async (kind: SourceKind) => {
+ if (busy.current || status !== 'draft') return
+ busy.current = true
+ setStatus('picking')
+ setError('')
+ try {
+ const selected = pickedTorrentSourceSchema
+ .nullable()
+ .parse(
+ server
+ ? await server.pick(kind)
+ : await transport.invoke(Commands.PickTorrentSource, kind)
+ )
+ if (selected) setSource({ path: selected.path, kind })
+ } catch {
+ setError(t('createTorrent.createFailed'))
+ } finally {
+ busy.current = false
+ setStatus('draft')
+ }
+ }
+ const create = async () => {
+ if (busy.current || status !== 'draft' || !source) return
+ const parsed = createTorrentRequestSchema.safeParse({
+ trackers: lines(trackers),
+ webSeeds: lines(webSeeds),
+ comment: comment.trim() || undefined,
+ private: isPrivate,
+ pieceLength: piece === 'auto' ? undefined : Number(piece),
+ })
+ if (!parsed.success) {
+ const field = parsed.error.issues[0]?.path[0]
+ if (field === 'webSeeds') setAdvanced(true)
+ setInvalidField(
+ field === 'webSeeds' || field === 'trackers' ? field : null
+ )
+ setError(
+ t('createTorrent.invalidOptions', { limit: CREATE_TORRENT_URL_LIMIT })
+ )
+ return
+ }
+ busy.current = true
+ setInvalidField(null)
+ setProgress(0)
+ setStatus('hashing')
+ setError('')
+ try {
+ setResult(
+ createTorrentResultSchema.parse(
+ server
+ ? await server.create(source, parsed.data, (fraction) =>
+ setProgress(Math.round(fraction * 100))
+ )
+ : await transport.invoke(Commands.CreateTorrent, parsed.data)
+ )
+ )
+ setStatus('ready')
+ } catch {
+ setError(t('createTorrent.createFailed'))
+ setStatus('draft')
+ } finally {
+ busy.current = false
+ }
+ }
+ const save = async () => {
+ if (busy.current || !result || status !== 'ready') return
+ busy.current = true
+ setStatus('saving')
+ setError('')
+ try {
+ const value = saveTorrentFileResultSchema.nullable().parse(
+ server
+ ? await server.save(result, seed)
+ : await transport.invoke(Commands.SaveTorrentFile, {
+ id: result.id,
+ seed,
+ })
+ )
+ if (!value) {
+ setStatus('ready')
+ return
+ }
+ setSaved(value)
+ setStatus('done')
+ } catch {
+ setError(t('createTorrent.saveFailed'))
+ setStatus('ready')
+ } finally {
+ busy.current = false
+ }
+ }
+ const locked = status !== 'draft'
+ const seedOption = (
+ <ToggleRow
+ id="seed"
+ label={t('createTorrent.seedAfter')}
+ checked={seed}
+ disabled={status === 'saving'}
+ onChange={setSeed}
+ />
+ )
+ const pieceOptions = [
+ { value: 'auto', label: t('createTorrent.pieceAuto') },
+ ...pieceSizes.map((kib) => ({
+ value: String(kib * 1024),
+ label: formatBytes(kib * 1024),
+ })),
+ ]
+ const clearValidation = () => {
+ if (invalidField) {
+ setInvalidField(null)
+ setError('')
+ }
+ }
+ const fieldError =
+ invalidField && error ? (
+ <p
+ id="creator-error"
+ role="alert"
+ className="mt-1.5 text-xs leading-4 text-destructive"
+ >
+ {error}
+ </p>
+ ) : null
+ return (
+ <>
+ <main className="min-h-0 flex-1 overflow-y-auto">
+ <div
+ data-adaptive-content
+ className="mx-auto flex w-full flex-col gap-3 px-4 pt-2 pb-3"
+ style={
+ !result
+ ? { minHeight: ADD_TASK_COLLAPSED_HEIGHT - chromeHeight }
+ : undefined
+ }
+ >
+ {!result ? (
+ <>
+ <SourcePicker
+ source={source}
+ disabled={locked}
+ onPick={(kind) => void pick(kind)}
+ />
+ <section
+ aria-label={t('createTorrent.options')}
+ className="flex min-w-0 flex-1 flex-col"
+ >
+ <ControlRow
+ stretch
+ id="creator-trackers"
+ label={t('createTorrent.trackers')}
+ top
+ >
+ <Textarea
+ id="creator-trackers"
+ spellCheck={false}
+ dir="ltr"
+ disabled={locked}
+ className={cn(
+ listField,
+ 'h-auto min-h-16 flex-1 resize-none'
+ )}
+ value={trackers}
+ aria-invalid={invalidField === 'trackers' || undefined}
+ aria-describedby={
+ invalidField === 'trackers' ? 'creator-error' : undefined
+ }
+ onChange={(e) => {
+ setTrackers(e.target.value)
+ clearValidation()
+ }}
+ placeholder={t('createTorrent.trackersPlaceholder')}
+ />
+ {invalidField === 'trackers' && fieldError}
+ </ControlRow>
+ <ToggleRow
+ id="private"
+ label={t('createTorrent.private')}
+ description={t('createTorrent.privateDesc')}
+ checked={isPrivate}
+ disabled={locked}
+ onChange={(value) => {
+ setPrivate(value)
+ clearValidation()
+ }}
+ />
+ {seedOption}
+ <TaskFormAdvanced
+ open={advanced}
+ onOpenChange={setAdvanced}
+ disabled={locked}
+ >
+ <ControlRow
+ id="creator-web-seeds"
+ label={t('createTorrent.webSeeds')}
+ top
+ >
+ <Textarea
+ id="creator-web-seeds"
+ dir="ltr"
+ spellCheck={false}
+ disabled={locked}
+ className={listField}
+ value={webSeeds}
+ aria-invalid={invalidField === 'webSeeds' || undefined}
+ aria-describedby={
+ invalidField === 'webSeeds'
+ ? 'creator-error'
+ : undefined
+ }
+ onChange={(e) => {
+ setWebSeeds(e.target.value)
+ clearValidation()
+ }}
+ placeholder={t('createTorrent.webSeedsPlaceholder')}
+ />
+ {invalidField === 'webSeeds' && fieldError}
+ </ControlRow>
+ <ControlRow
+ id="creator-comment"
+ label={t('createTorrent.comment')}
+ >
+ <Input
+ id="creator-comment"
+ className={cn(textField, 'h-8')}
+ value={comment}
+ disabled={locked}
+ maxLength={CREATE_TORRENT_COMMENT_MAX}
+ onChange={(e) => setComment(e.target.value)}
+ />
+ </ControlRow>
+ <ControlRow
+ id="creator-piece"
+ label={t('createTorrent.pieceLength')}
+ >
+ <Select
+ items={pieceOptions}
+ value={piece}
+ disabled={locked}
+ onValueChange={(value) => {
+ if (value !== null) setPiece(value)
+ }}
+ >
+ <SettingsSelectTrigger
+ id="creator-piece"
+ className="text-[13px]"
+ >
+ <SelectValue />
+ </SettingsSelectTrigger>
+ <SelectContent position="popper" align="start">
+ {pieceOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </ControlRow>
+ </TaskFormAdvanced>
+ </section>
+ </>
+ ) : (
+ <TorrentSummary result={result}>
+ {!saved && seedOption}
+ </TorrentSummary>
+ )}
+ {status === 'hashing' && (
+ <div className="space-y-1.5" role="status">
+ <p className="flex justify-between text-xs text-muted-foreground">
+ {t('createTorrent.hashing')}
+ <span className="tabular-nums">{progress}%</span>
+ </p>
+ <Progress
+ value={progress}
+ aria-label={t('createTorrent.hashing')}
+ />
+ </div>
+ )}
+ {saved && (
+ <Alert role="status" className="border-border/80">
+ {saved.seeding === 'failed' ? <WarningIcon /> : <CheckIcon />}
+ <AlertDescription className="min-w-0 select-text break-words text-xs leading-5 text-foreground">
+ <p>
+ {t(
+ server
+ ? 'createTorrent.downloadRequested'
+ : 'createTorrent.savedToast',
+ { path: saved.path }
+ )}
+ </p>
+ {saved.seeding !== 'not-requested' && (
+ <p
+ className={
+ saved.seeding === 'failed'
+ ? 'text-destructive'
+ : 'text-muted-foreground'
+ }
+ >
+ {t(
+ saved.seeding === 'failed'
+ ? 'createTorrent.seedFailed'
+ : 'createTorrent.seedSubmitted'
+ )}
+ </p>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+ {error && !invalidField && (
+ <Alert id="creator-error" variant="destructive">
+ <WarningIcon />
+ <AlertDescription className="text-xs">{error}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+ </main>
+ <footer data-slot="add-task-form-footer" className={taskFormFooter}>
+ <div className={cn(taskFormActions, 'justify-end')}>
+ {status === 'ready' && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="me-auto text-muted-foreground"
+ onClick={() => {
+ server?.release()
+ setResult(null)
+ setStatus('draft')
+ setError('')
+ }}
+ >
+ <ChevronLeftIcon className="size-3.5 rtl:rotate-180" />
+ {t('menu.edit.title')}
+ </Button>
+ )}
+ <Button
+ size="sm"
+ variant={saved ? 'default' : 'outline'}
+ disabled={status === 'saving'}
+ onClick={onClose}
+ >
+ {t('common.close')}
+ </Button>
+ {!saved && (
+ <Button
+ size="sm"
+ className="gap-2"
+ disabled={result ? status !== 'ready' : !source || locked}
+ onClick={() => void (result ? save() : create())}
+ >
+ {(status === 'saving' || status === 'hashing') && (
+ <Spinner
+ aria-hidden="true"
+ className="size-3.5 motion-reduce:animate-none"
+ />
+ )}
+ {t(result ? 'createTorrent.saveFile' : 'createTorrent.create')}
+ </Button>
+ )}
+ </div>
+ </footer>
+ </>
+ )
+}
diff --git a/src/renderer/components/create-torrent/create-torrent-window.tsx b/src/renderer/components/create-torrent/create-torrent-window.tsx
new file mode 100644
index 00000000..79a55e71
--- /dev/null
+++ b/src/renderer/components/create-torrent/create-torrent-window.tsx
@@ -0,0 +1,25 @@
+import { WindowChrome } from '@renderer/components/window-chrome/window-chrome'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { useTranslation } from 'react-i18next'
+import { CreateTorrentForm } from './create-torrent-form'
+
+export function CreateTorrentWindow() {
+ const { t } = useTranslation()
+ return (
+ <div className="flex h-screen flex-col bg-background text-foreground">
+ <WindowChrome
+ variant="titled"
+ maximizable={false}
+ title={t('createTorrent.title')}
+ />
+ <CreateTorrentForm
+ onClose={() =>
+ void transport.invoke(Commands.CloseCurrentWindow, {
+ showMain: 'if-visible',
+ })
+ }
+ />
+ </div>
+ )
+}
diff --git a/src/renderer/components/create-torrent/creator-sections.tsx b/src/renderer/components/create-torrent/creator-sections.tsx
new file mode 100644
index 00000000..b02ecb71
--- /dev/null
+++ b/src/renderer/components/create-torrent/creator-sections.tsx
@@ -0,0 +1,246 @@
+import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
+import {
+ DocumentIcon,
+ FolderIcon,
+ TorrentFileIcon,
+} from '@renderer/components/icons'
+import { Button } from '@renderer/components/ui/button'
+import { Label } from '@renderer/components/ui/label'
+import { Separator } from '@renderer/components/ui/separator'
+import { Switch } from '@renderer/components/ui/switch'
+import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { cn } from '@renderer/lib/utils'
+import type { CreateTorrentResultPayload } from '@shared/schemas/create-torrent'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export type SourceKind = 'file' | 'directory'
+export interface PickedSource {
+ path: string
+ kind: SourceKind
+}
+const controlLabel = 'text-[13px] font-medium leading-5'
+const fieldGrid = 'grid min-w-0 grid-cols-[7rem_minmax(0,1fr)] gap-x-4'
+
+export function SourcePicker({
+ source,
+ disabled,
+ onPick,
+}: {
+ source: PickedSource | null
+ disabled: boolean
+ onPick: (kind: SourceKind) => void
+}) {
+ const { t } = useTranslation()
+ const SourceIcon = source?.kind === 'directory' ? FolderIcon : DocumentIcon
+ return (
+ <section
+ aria-labelledby="creator-source-label"
+ className={cn(fieldGrid, 'items-start')}
+ >
+ <h2 id="creator-source-label" className={cn(controlLabel, 'pt-1.5')}>
+ {t('createTorrent.source')}
+ </h2>
+ <div className="min-w-0">
+ {source && (
+ <div className="mb-2 flex min-w-0 items-center gap-2.5">
+ <SourceIcon className="size-[18px] shrink-0 text-chart-2" />
+ <div className="min-w-0">
+ <p
+ dir="auto"
+ className="truncate text-[13px] font-medium leading-5"
+ title={source.path}
+ >
+ {source.path.split(/[/\\]/).at(-1)}
+ </p>
+ <p
+ dir="auto"
+ className="truncate text-xs leading-4 text-muted-foreground"
+ title={source.path}
+ >
+ {source.path}
+ </p>
+ </div>
+ </div>
+ )}
+ <fieldset
+ aria-labelledby="creator-source-label"
+ className="flex min-w-0 flex-wrap gap-2"
+ >
+ {(['file', 'directory'] as const).map((kind) => {
+ const Icon = kind === 'file' ? DocumentIcon : FolderIcon
+ return (
+ <Button
+ type="button"
+ key={kind}
+ size="sm"
+ variant="outline"
+ disabled={disabled}
+ className="h-auto min-h-8 max-w-full whitespace-normal py-1 text-start text-[13px] font-medium shadow-none"
+ onClick={() => onPick(kind)}
+ >
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
+ {t(
+ kind === 'file'
+ ? 'directoryPicker.selectFile'
+ : 'directoryPicker.selectFolder'
+ )}
+ </Button>
+ )
+ })}
+ </fieldset>
+ </div>
+ </section>
+ )
+}
+
+export function ControlRow({
+ id,
+ label,
+ children,
+ top = false,
+ stretch = false,
+}: {
+ id: string
+ label: string
+ children: ReactNode
+ top?: boolean
+ stretch?: boolean
+}) {
+ return (
+ <div
+ className={cn(
+ fieldGrid,
+ 'py-2',
+ stretch ? 'flex-1 items-stretch' : top ? 'items-start' : 'items-center'
+ )}
+ >
+ <Label
+ htmlFor={id}
+ className={cn(controlLabel, top && 'self-start pt-1.5')}
+ >
+ {label}
+ </Label>
+ <div className={cn('min-w-0', stretch && 'flex flex-col')}>
+ {children}
+ </div>
+ </div>
+ )
+}
+
+export function ToggleRow({
+ id,
+ label,
+ description,
+ checked,
+ disabled,
+ onChange,
+}: {
+ id: string
+ label: string
+ description?: string
+ checked: boolean
+ disabled: boolean
+ onChange: (checked: boolean) => void
+}) {
+ return (
+ <div className="flex items-center justify-between gap-3 py-2">
+ <div
+ className={cn(
+ 'min-w-0 flex-1',
+ description && fieldGrid,
+ 'items-baseline'
+ )}
+ >
+ <Label htmlFor={id} className={controlLabel}>
+ {label}
+ </Label>
+ {description && (
+ <p
+ id={`${id}-hint`}
+ className="text-xs leading-4 text-muted-foreground"
+ >
+ {description}
+ </p>
+ )}
+ </div>
+ <Switch
+ id={id}
+ aria-describedby={description ? `${id}-hint` : undefined}
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={onChange}
+ />
+ </div>
+ )
+}
+
+export function TorrentSummary({
+ result,
+ children,
+}: {
+ result: CreateTorrentResultPayload
+ children?: ReactNode
+}) {
+ const { t } = useTranslation()
+ const { formatBytes } = useByteFormat()
+ const filename = `${result.name}.torrent`
+ const copyLabel = `${t('menu.edit.copy')} · ${t('createTorrent.resultInfoHash')}`
+ return (
+ <section aria-label={filename} className="min-w-0">
+ <div className="flex min-w-0 items-center gap-3 pb-3">
+ <span className="grid size-8 shrink-0 place-items-center text-foreground">
+ <TorrentFileIcon className="size-5" />
+ </span>
+ <h2
+ className="min-w-0 truncate text-base font-semibold leading-5 tracking-tight"
+ title={filename}
+ >
+ {filename}
+ </h2>
+ </div>
+ <Separator />
+ <dl className="grid grid-cols-3 gap-4 py-3">
+ {[
+ [t('createTorrent.resultSize'), formatBytes(result.totalSize)],
+ [t('panel.downloads.inspector.tab.files'), result.fileCount],
+ [t('panel.downloads.inspector.tab.pieces'), result.pieceCount],
+ ].map(([name, value]) => (
+ <div key={name} className="min-w-0">
+ <dt className="text-xs text-muted-foreground">{name}</dt>
+ <dd className="mt-1 text-[13px] font-medium tabular-nums">
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <Separator />
+ <div className="flex min-w-0 items-center gap-3 py-2.5">
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-muted-foreground">
+ {t('createTorrent.resultInfoHash')}
+ </p>
+ <code
+ dir="ltr"
+ className="mt-1 block select-all break-all font-mono text-xs leading-4"
+ >
+ {result.infoHash}
+ </code>
+ </div>
+ <CopyButton
+ variant="ghost"
+ size="icon-sm"
+ content={result.infoHash}
+ aria-label={copyLabel}
+ title={copyLabel}
+ />
+ </div>
+ {children && (
+ <>
+ <Separator />
+ {children}
+ </>
+ )}
+ </section>
+ )
+}
diff --git a/src/renderer/components/create-torrent/server-torrent-client.ts b/src/renderer/components/create-torrent/server-torrent-client.ts
new file mode 100644
index 00000000..f0f2330f
--- /dev/null
+++ b/src/renderer/components/create-torrent/server-torrent-client.ts
@@ -0,0 +1,111 @@
+import { webBaseUrl, webOriginHeaders } from '@renderer/lib/web-base-url'
+import { __webPathPickerBus } from '@renderer/platform/web-services'
+import type {
+ CreateTorrentRequest,
+ CreateTorrentResultPayload,
+} from '@shared/schemas/create-torrent'
+import {
+ saveTorrentFileResultSchema,
+ TORRENT_CREATOR_API,
+ TORRENT_SEED_HEADER,
+ torrentJobSchema,
+ torrentJobStatusSchema,
+} from '@shared/schemas/create-torrent'
+import type { PickedSource, SourceKind } from './creator-sections'
+
+/** One dialog owns one job; closing it also cancels unfinished server work. */
+export class ServerTorrentClient {
+ private id?: string
+ private controller?: AbortController
+ private readonly url = webBaseUrl() + TORRENT_CREATOR_API
+ async pick(kind: SourceKind) {
+ const path = await __webPathPickerBus.request(
+ kind === 'file' ? { file: { kind: 'open' } } : { readDirectory: true }
+ )
+ return path ? { path } : null
+ }
+ release() {
+ this.controller?.abort()
+ this.controller = undefined
+ if (this.id) this.remove(this.id)
+ this.id = undefined
+ }
+ private remove(id: string) {
+ void fetch(`${this.url}/${id}`, {
+ method: 'DELETE',
+ credentials: 'same-origin',
+ headers: webOriginHeaders(),
+ }).catch(() => undefined)
+ }
+ async create(
+ source: PickedSource,
+ options: CreateTorrentRequest,
+ onProgress: (fraction: number) => void
+ ) {
+ this.release()
+ const controller = new AbortController()
+ this.controller = controller
+ // Receive the id even if the dialog closes during creation so the new job can be discarded.
+ const start = await fetch(this.url, {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { ...webOriginHeaders(), 'content-type': 'application/json' },
+ body: JSON.stringify({ source, options }),
+ })
+ if (!start.ok) throw new Error('Torrent creation unavailable')
+ const { id } = torrentJobSchema.parse(await start.json())
+ if (controller.signal.aborted) {
+ this.remove(id)
+ controller.signal.throwIfAborted()
+ }
+ this.id = id
+ try {
+ for (;;) {
+ const res = await fetch(`${this.url}/${id}`, {
+ signal: controller.signal,
+ credentials: 'same-origin',
+ headers: webOriginHeaders(),
+ cache: 'no-store',
+ })
+ if (!res.ok) throw new Error('Torrent job expired')
+ const state = torrentJobStatusSchema.parse(await res.json())
+ if (state.state === 'ready') return state.result
+ if (state.state === 'failed') throw new Error('Torrent creation failed')
+ onProgress(state.progress)
+ await new Promise<void>((resolve) => setTimeout(resolve, 350))
+ }
+ } catch (error) {
+ if (this.id === id) this.release()
+ throw error
+ }
+ }
+ async save(result: CreateTorrentResultPayload, seed: boolean) {
+ if (this.id !== result.id) throw new Error('Stale torrent')
+ const res = await fetch(`${this.url}/${result.id}/export`, {
+ method: 'POST',
+ signal: this.controller?.signal,
+ credentials: 'same-origin',
+ headers: { ...webOriginHeaders(), 'content-type': 'application/json' },
+ body: JSON.stringify({ seed }),
+ })
+ if (!res.ok) throw new Error('Torrent export failed')
+ const filename = `${result.name}.torrent`
+ const outcome = saveTorrentFileResultSchema.parse({
+ path: filename,
+ seeding: res.headers.get(TORRENT_SEED_HEADER),
+ })
+ const url = URL.createObjectURL(await res.blob())
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.append(a)
+ try {
+ a.click()
+ } finally {
+ a.remove()
+ setTimeout(() => URL.revokeObjectURL(url), 60_000)
+ }
+ this.release()
+ return outcome
+ }
+}
diff --git a/src/renderer/components/create-torrent/server-torrent-dialog.tsx b/src/renderer/components/create-torrent/server-torrent-dialog.tsx
new file mode 100644
index 00000000..c91d8ae0
--- /dev/null
+++ b/src/renderer/components/create-torrent/server-torrent-dialog.tsx
@@ -0,0 +1,45 @@
+import { useAdaptiveDialogHeight } from '@renderer/components/add-task-dialog/use-adaptive-dialog-height'
+import { TaskFormDialog } from '@renderer/components/task-form-dialog'
+import { Dialog } from '@renderer/components/ui/dialog'
+import {
+ ADD_TASK_COLLAPSED_HEIGHT,
+ ADD_TASK_MAX_HEIGHT,
+} from '@shared/constants/add-task'
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { CreateTorrentForm } from './create-torrent-form'
+import { ServerTorrentClient } from './server-torrent-client'
+
+export function ServerTorrentDialog({ onClose }: { onClose: () => void }) {
+ const { t } = useTranslation()
+ const [client] = useState(() => new ServerTorrentClient())
+ const [busy, setBusy] = useState(false)
+ const ref = useRef<HTMLDivElement>(null)
+ const { height } = useAdaptiveDialogHeight(ref, {
+ open: true,
+ collapsedHeight: ADD_TASK_COLLAPSED_HEIGHT,
+ maxHeight: ADD_TASK_MAX_HEIGHT,
+ })
+ useEffect(() => () => client.release(), [client])
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !busy) onClose()
+ }}
+ >
+ <TaskFormDialog
+ contentRef={ref}
+ title={t('createTorrent.title')}
+ busy={busy}
+ height={height}
+ >
+ <CreateTorrentForm
+ server={client}
+ onBusyChange={setBusy}
+ onClose={onClose}
+ />
+ </TaskFormDialog>
+ </Dialog>
+ )
+}
diff --git a/src/renderer/components/task-form-dialog.tsx b/src/renderer/components/task-form-dialog.tsx
new file mode 100644
index 00000000..62070dc5
--- /dev/null
+++ b/src/renderer/components/task-form-dialog.tsx
@@ -0,0 +1,56 @@
+import {
+ DialogClose,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { WindowChromeCaptionIcon } from '@renderer/components/window-chrome/window-chrome'
+import {
+ ADD_TASK_MAX_HEIGHT,
+ TASK_FORM_WIDTH,
+} from '@shared/constants/add-task'
+import type { ReactNode, Ref } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export function TaskFormDialog({
+ contentRef,
+ height,
+ title,
+ busy,
+ children,
+}: {
+ contentRef: Ref<HTMLDivElement>
+ height: number
+ title: string
+ busy: boolean
+ children: ReactNode
+}) {
+ const { t } = useTranslation()
+ return (
+ <DialogContent
+ ref={contentRef}
+ showCloseButton={false}
+ overlayClassName="transition-opacity duration-150 data-open:animate-none data-closed:animate-none data-starting-style:opacity-0 data-ending-style:opacity-0"
+ className="flex w-[calc(100%-2rem)] flex-col gap-0 overflow-hidden p-0 transition-[height] duration-200 ease-out motion-reduce:transition-none"
+ style={{
+ height,
+ maxWidth: TASK_FORM_WIDTH,
+ maxHeight: `min(${ADD_TASK_MAX_HEIGHT}px, calc(100vh - 2rem))`,
+ }}
+ >
+ <DialogHeader className="h-10 shrink-0 justify-center px-4 pe-14">
+ <DialogTitle className="pt-[14px] text-[13px] font-semibold">
+ {title}
+ </DialogTitle>
+ </DialogHeader>
+ {children}
+ <DialogClose
+ disabled={busy}
+ aria-label={t('chrome.close')}
+ className="app-no-drag absolute top-3.5 end-3.5 flex size-7 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-foreground outline-none transition-colors [&>svg]:opacity-65 hover:bg-accent hover:text-accent-foreground hover:[&>svg]:opacity-90 focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <WindowChromeCaptionIcon name="close" />
+ </DialogClose>
+ </DialogContent>
+ )
+}
diff --git a/src/renderer/components/task-form-layout.tsx b/src/renderer/components/task-form-layout.tsx
new file mode 100644
index 00000000..b15c70b5
--- /dev/null
+++ b/src/renderer/components/task-form-layout.tsx
@@ -0,0 +1,54 @@
+import { ChevronRightIcon } from '@renderer/components/icons'
+import { Button } from '@renderer/components/ui/button'
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@renderer/components/ui/collapsible'
+import { cn } from '@renderer/lib/utils'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export const taskFormFooter =
+ 'w-full shrink-0 border-t-[0.5px] border-border bg-background px-4 py-3'
+export const taskFormActions = 'flex shrink-0 items-center gap-2'
+export function TaskFormAdvanced({
+ open,
+ onOpenChange,
+ disabled,
+ children,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ disabled?: boolean
+ children: ReactNode
+}) {
+ const { t } = useTranslation()
+ return (
+ <Collapsible open={open} onOpenChange={onOpenChange}>
+ <CollapsibleTrigger
+ disabled={disabled}
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="-ms-2 h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground hover:bg-transparent dark:hover:bg-transparent"
+ />
+ }
+ >
+ <ChevronRightIcon
+ className={cn(
+ 'size-3.5 motion-safe:transition-transform motion-safe:duration-150',
+ open ? 'rotate-90' : 'rtl:rotate-180'
+ )}
+ aria-hidden="true"
+ />
+ {t('task.add.advanced')}
+ </CollapsibleTrigger>
+ <CollapsibleContent className="mt-2 ms-1.5 space-y-2 border-s-2 border-border ps-3">
+ {children}
+ </CollapsibleContent>
+ </Collapsible>
+ )
+}
diff --git a/src/renderer/components/window-chrome/window-chrome.tsx b/src/renderer/components/window-chrome/window-chrome.tsx
index ebb23e52..ee64d2f1 100644
--- a/src/renderer/components/window-chrome/window-chrome.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.tsx
@@ -3,7 +3,7 @@ import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import {
DESKTOP_WINDOW_CHROME_HEIGHT,
- WINDOW_CONTROLS_OVERLAY_HEIGHT,
+ windowChromeHeight,
} from '@shared/constants/window-chrome'
import { Commands } from '@shared/protocol/commands'
import {
@@ -156,7 +156,7 @@ export function shouldShowDesktopWindowControls(
export function WindowChrome({
actionsPosition = 'start',
- compact: _compact,
+ compact = false,
maximizable = true,
previewDesktopControls = false,
title,
@@ -196,10 +196,15 @@ export function WindowChrome({
const offsetStartActionsForDesktopMenu =
leading != null && actionsPosition === 'start'
+ const height = windowChromeHeight(
+ __MOTRIX_TARGET__ === 'electron' ? platform : 'web',
+ compact || isOverlay
+ )
+ // Compact surfaces align their controls to y=27 with an inset; full-height
+ // title bars center that same row without any additional padding.
+ const insetCaptionRow = height === DESKTOP_WINDOW_CHROME_HEIGHT
const containerStyle: React.CSSProperties = {
- height: usesWindowControlsOverlay
- ? WINDOW_CONTROLS_OVERLAY_HEIGHT
- : DESKTOP_WINDOW_CHROME_HEIGHT,
+ height,
display: 'flex',
alignItems: 'center',
paddingLeft: showTrafficLight ? 94 : undefined,
@@ -233,7 +238,7 @@ export function WindowChrome({
data-slot="window-chrome-actions"
className={cn(
'app-no-drag relative z-[60] flex shrink-0 items-center gap-2 empty:hidden',
- !usesWindowControlsOverlay && 'pt-3.5',
+ insetCaptionRow && 'pt-3.5',
offsetStartActionsForDesktopMenu && 'ms-1'
)}
>
@@ -252,7 +257,7 @@ export function WindowChrome({
<div
className={cn(
'text-[13px] font-[600]',
- !usesWindowControlsOverlay && 'pt-[14px]'
+ insetCaptionRow && 'pt-[14px]'
)}
>
{title}
@@ -263,7 +268,7 @@ export function WindowChrome({
data-slot="window-chrome-leading"
className={cn(
'app-no-drag relative z-[60] me-1.5 flex shrink-0 items-center empty:hidden',
- !usesWindowControlsOverlay && 'pt-3.5'
+ insetCaptionRow && 'pt-3.5'
)}
>
{leading}
diff --git a/src/renderer/features/application-menu/web-menu-button.test.tsx b/src/renderer/features/application-menu/web-menu-button.test.tsx
index ee8a374e..57deb85a 100644
--- a/src/renderer/features/application-menu/web-menu-button.test.tsx
+++ b/src/renderer/features/application-menu/web-menu-button.test.tsx
@@ -76,7 +76,7 @@ it('opens the links form once after the menu closes', async () => {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Motrix' }))
await screen.findByRole('menu')
- await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ await user.click(screen.getByRole('menuitem', { name: 'File' }))
await user.click(screen.getByRole('menuitem', { name: 'New Task…' }))
await waitFor(() =>
expect(openAddTaskDialog).toHaveBeenCalledExactlyOnceWith({ tab: 'links' })
@@ -88,7 +88,7 @@ it('uses a one-level stack below 640px and Escape returns before closing', async
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Motrix' }))
await screen.findByRole('menu')
- await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ await user.click(screen.getByRole('menuitem', { name: 'File' }))
expect(screen.getAllByRole('menu')).toHaveLength(1)
expect(screen.getByRole('menuitem', { name: 'Back' })).toBeVisible()
await user.keyboard('{Escape}')
@@ -121,7 +121,7 @@ it('activates the browser file input synchronously and passes all parsed files t
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Motrix' }))
await screen.findByRole('menu')
- await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ await user.click(screen.getByRole('menuitem', { name: 'File' }))
const input = screen.getByLabelText('Open Torrent File…') as HTMLInputElement
const click = vi.spyOn(input, 'click')
fireEvent.click(screen.getByRole('menuitem', { name: 'Open Torrent File…' }))
diff --git a/src/renderer/features/application-menu/web-menu-button.tsx b/src/renderer/features/application-menu/web-menu-button.tsx
index 2d26c9ce..2e322a35 100644
--- a/src/renderer/features/application-menu/web-menu-button.tsx
+++ b/src/renderer/features/application-menu/web-menu-button.tsx
@@ -2,6 +2,7 @@ import { torrentFileErrorKey } from '@shared/lib/engine-torrent'
import { isNasAuthMode } from '@shared/schemas/operator-auth'
import './application-menu.css'
import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { ServerTorrentDialog } from '@renderer/components/create-torrent/server-torrent-dialog'
import { ArrowLeftIcon, ChevronRightIcon } from '@renderer/components/icons'
import { Button } from '@renderer/components/ui/button'
import {
@@ -72,10 +73,14 @@ export function WebMenuButton() {
const { t } = useTranslation()
const location = useLocation()
const [open, setOpen] = useState(false)
+ const [creatorOpen, setCreatorOpen] = useState(false)
+ const creatorAvailable = useOperatorSession(
+ (s) => s.status?.nasCapabilities?.torrentPicker !== false
+ )
const [narrow, setNarrow] = useState(
() => window.matchMedia?.('(width < 640px)').matches ?? false
)
- const [level, setLevel] = useState<'task' | 'help' | null>(null)
+ const [level, setLevel] = useState<'file' | 'task' | 'help' | null>(null)
const [intent, setIntent] = useState<TaskMenuIntent>()
const [confirmation, setConfirmation] =
useState<MenuConfirmationRequest | null>(null)
@@ -226,6 +231,8 @@ export function WebMenuButton() {
for (const item of PRODUCT_MENU_ITEMS.filter(
(item) => item.section === section
)) {
+ if (item.commandId === CommandIds.CreateTorrentFile && !creatorAvailable)
+ continue
if (group && group !== item.group && section !== 'app')
result.push(<DropdownMenuSeparator key={`separator-${item.group}`} />)
group = item.group
@@ -257,7 +264,7 @@ export function WebMenuButton() {
}
return result
}
- const submenu = (section: 'task' | 'help') =>
+ const submenu = (section: 'file' | 'task' | 'help') =>
narrow ? (
<DropdownMenuItem
key={section}
@@ -318,6 +325,8 @@ export function WebMenuButton() {
restoreSource()
if (command === 'logout')
setConfirmation({ kind: 'logout', run: operatorLogout })
+ else if (command === CommandIds.CreateTorrentFile)
+ setCreatorOpen(true)
else void execute(command)
})
}
@@ -392,6 +401,7 @@ export function WebMenuButton() {
)}
{renderItems('app')}
<DropdownMenuSeparator />
+ {submenu('file')}
{submenu('task')}
{submenu('help')}
{canLogout && (
@@ -448,6 +458,9 @@ export function WebMenuButton() {
})()
}}
/>
+ {creatorOpen && (
+ <ServerTorrentDialog onClose={() => setCreatorOpen(false)} />
+ )}
<MenuConfirmation
request={confirmation}
close={() => setConfirmation(null)}
diff --git a/src/renderer/features/web-directory-picker/directory-picker-controller.ts b/src/renderer/features/web-directory-picker/directory-picker-controller.ts
index ad784d5d..05132afa 100644
--- a/src/renderer/features/web-directory-picker/directory-picker-controller.ts
+++ b/src/renderer/features/web-directory-picker/directory-picker-controller.ts
@@ -127,7 +127,8 @@ export class DirectoryPickerController {
'mutate' | 'getSnapshot'
> = directoryPreferences,
private readonly sortPreferences: DirectorySortPreferences = directorySortPreferences,
- readonly file?: FilePickerOptions
+ readonly file?: FilePickerOptions,
+ private readonly readDirectory = false
) {
this.state.sort = sortPreferences.get()
this.locationsStore = new ServerDirectoryLocationsStore(transport, {
@@ -697,7 +698,7 @@ export class DirectoryPickerController {
: await this.request(
Queries.ValidateServerDirectory,
ValidateServerDirectoryResultSchema,
- { path: target }
+ { path: target, ...(this.readDirectory ? { access: 'read' } : {}) }
)
if (!this.current(generation) || this.target !== target) return
if (!result.ok) throw new DirectoryRequestError(result.error.code)
diff --git a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
index e470c02a..483391f3 100644
--- a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
+++ b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
@@ -115,7 +115,8 @@ export function WebDirectoryPickerDialog() {
},
undefined,
undefined,
- request.file
+ request.file,
+ request.readDirectory
)
current.current = { request, controller }
setSession(current.current)
diff --git a/src/renderer/hooks/use-adaptive-window-height.ts b/src/renderer/hooks/use-adaptive-window-height.ts
index 775b650b..4a3c19fe 100644
--- a/src/renderer/hooks/use-adaptive-window-height.ts
+++ b/src/renderer/hooks/use-adaptive-window-height.ts
@@ -3,7 +3,8 @@ import { Commands } from '@shared/protocol/commands'
import { useEffect } from 'react'
interface Options {
- width: number
+ /** Omit for resizable windows to preserve the current user-selected width. */
+ width?: number
minHeight: number
maxHeight: number
/** Chrome height (non-content) to add on top of measured content. */
@@ -62,7 +63,7 @@ export function useAdaptiveWindowHeight({
if (Math.abs(clamped - last) < 2) return
last = clamped
void transport.invoke(Commands.ResizeWindow, {
- width,
+ width: width ?? window.outerWidth,
height: clamped,
})
}
diff --git a/src/renderer/lib/bootstrap-locale.ts b/src/renderer/lib/bootstrap-locale.ts
index 13485c46..52a18b70 100644
--- a/src/renderer/lib/bootstrap-locale.ts
+++ b/src/renderer/lib/bootstrap-locale.ts
@@ -8,7 +8,9 @@ import {
} from '@shared/constants/locales'
import { Queries } from '@shared/protocol/queries'
-export type RendererWindowId = 'main' | 'add-task' | 'onboarding'
+export type { WindowId as RendererWindowId } from '@shared/types/window'
+
+import type { WindowId as RendererWindowId } from '@shared/types/window'
interface LanguageState {
language?: unknown
diff --git a/src/renderer/platform/web-services.ts b/src/renderer/platform/web-services.ts
index ff42e28f..e5987ab2 100644
--- a/src/renderer/platform/web-services.ts
+++ b/src/renderer/platform/web-services.ts
@@ -14,6 +14,7 @@ export type PickRequest = {
defaultPath?: string
allowFavoriteEditing?: boolean
file?: FilePickerOptions
+ readDirectory?: boolean
opener: HTMLElement | null
}
type PickListener = (req: PickRequest) => void
@@ -37,6 +38,7 @@ export class PathPickerBus {
defaultPath?: string
allowFavoriteEditing?: boolean
file?: FilePickerOptions
+ readDirectory?: boolean
}): Promise<string | null> {
const id = ++this.latestId
const opener =
diff --git a/src/renderer/windows/add-task-window.tsx b/src/renderer/windows/add-task-window.tsx
index 74659bee..635ec3e6 100644
--- a/src/renderer/windows/add-task-window.tsx
+++ b/src/renderer/windows/add-task-window.tsx
@@ -6,6 +6,7 @@ import { PlatformServicesProvider } from '@renderer/platform/services'
import {
ADD_TASK_COLLAPSED_HEIGHT,
ADD_TASK_MAX_HEIGHT,
+ TASK_FORM_WIDTH,
} from '@shared/constants/add-task'
import {
addTaskUrlParamsSchema,
@@ -19,7 +20,7 @@ export function AddTaskWindow() {
const { t } = useTranslation()
useAdaptiveWindowHeight({
- width: 640,
+ width: TASK_FORM_WIDTH,
minHeight: ADD_TASK_COLLAPSED_HEIGHT,
maxHeight: ADD_TASK_MAX_HEIGHT,
enabled: __MOTRIX_TARGET__ === 'electron',
diff --git a/src/server/http/app.ts b/src/server/http/app.ts
index 1b993f22..407e737c 100644
--- a/src/server/http/app.ts
+++ b/src/server/http/app.ts
@@ -37,6 +37,10 @@ import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limit
import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify'
import type { RemoteExtensionConfig } from '../bridge/remote-extension-config'
import type { FnosGatewayOptions } from '../platform/fnos/identity'
+import {
+ registerTorrentCreator,
+ type TorrentCreatorDeps,
+} from '../routes/torrent-creator'
import { bindEventHeartbeat } from './event-heartbeat'
import { bindEventBroadcaster } from './events'
import {
@@ -113,6 +117,7 @@ async function directoryRpc(
}
export interface AppOptions {
+ torrentCreator?: TorrentCreatorDeps
/** Supported pairing surfaces, independent of the user's enable switch. */
clientPairing?: ClientPairingCapabilities
basePath?: string
@@ -186,6 +191,10 @@ export async function createApp(
...(clientPairing ? { clientPairing } : {}),
}))
}
+ if (opts.torrentCreator)
+ registerTorrentCreator(app, opts.torrentCreator, (req) =>
+ operatorSessions?.principal(req)
+ )
const commands = opts.commandHandlers ?? {}
const queries = opts.queryHandlers ?? {}
const bridgeCommands = opts.bridgeCommandHandlers ?? {}
diff --git a/src/server/index.ts b/src/server/index.ts
index 3f40d32d..444c69a8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -1525,6 +1525,14 @@ async function main() {
| Awaited<ReturnType<typeof listenNasClientGateway>>
| undefined
const app = await createApp({
+ torrentCreator: {
+ policy: downloadPathPolicy,
+ authorizeFile: nasFiles
+ ? (file) => nasFiles.authorizeFile(file, downloadPathPolicy)
+ : undefined,
+ createTask: async (request) =>
+ (await createTask(request)) as TaskCreateCommandResult,
+ },
getHiddenNotificationKinds: () =>
getHiddenNotificationKinds(settingsManager.getApp()),
clientPairing: {
diff --git a/src/server/routes/torrent-creator.test.ts b/src/server/routes/torrent-creator.test.ts
new file mode 100644
index 00000000..43601ef4
--- /dev/null
+++ b/src/server/routes/torrent-creator.test.ts
@@ -0,0 +1,255 @@
+// @vitest-environment node
+import {
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { parseTorrent } from '@motrix/torrent'
+import {
+ TORRENT_CREATOR_API,
+ TORRENT_SEED_HEADER,
+} from '@shared/schemas/create-torrent'
+import type { FastifyInstance } from 'fastify'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { createServerDownloadPathPolicy } from '../download-path-policy'
+import { createApp } from '../http/app'
+
+const token = 'torrent-creator-test-operator-token'
+let root: string, allowed: string, app: FastifyInstance
+let deny = false
+let hold: Promise<void> | undefined
+const seed = vi.fn()
+const headers = { authorization: `Bearer ${token}` }
+const start = (source: string, kind: 'file' | 'directory' = 'file') =>
+ app.inject({
+ method: 'POST',
+ url: TORRENT_CREATOR_API,
+ headers,
+ payload: { source: { path: source, kind }, options: {} },
+ })
+async function wait(id: string) {
+ const status = () =>
+ app
+ .inject({ url: `${TORRENT_CREATOR_API}/${id}`, headers })
+ .then((r) => r.json())
+ await expect.poll(async () => (await status()).state).not.toBe('hashing')
+ return status()
+}
+const exp = (id: string, doSeed: boolean) =>
+ app.inject({
+ method: 'POST',
+ url: `${TORRENT_CREATOR_API}/${id}/export`,
+ headers,
+ payload: { seed: doSeed },
+ })
+beforeEach(async () => {
+ deny = false
+ hold = undefined
+ seed.mockReset()
+ root = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'motrix-create-server-'))
+ )
+ allowed = path.join(root, 'downloads')
+ await mkdir(allowed)
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: allowed,
+ allowedSaveDirs: [allowed],
+ })
+ app = await createApp({
+ operatorAuth: { operatorToken: token },
+ torrentCreator: {
+ policy,
+ authorizeFile: async (p) => {
+ if (hold) await hold
+ if (deny && p.endsWith('asset.bin')) throw Error('Access revoked')
+ return p
+ },
+ createTask: seed,
+ },
+ })
+})
+afterEach(async () => {
+ await app.close()
+ await rm(root, { recursive: true, force: true })
+})
+it('exports valid multi-piece original data only to its owner; seeding is optional and idempotent', async () => {
+ const folder = path.join(allowed, 'folder')
+ await mkdir(folder)
+ await writeFile(path.join(folder, 'asset.bin'), Buffer.alloc(65540, 1))
+ expect(
+ (
+ await app.inject({
+ method: 'POST',
+ url: TORRENT_CREATOR_API,
+ payload: {},
+ })
+ ).statusCode
+ ).toBe(401)
+ const res = await start(folder, 'directory')
+ expect(res.statusCode).toBe(202)
+ const { id } = res.json()
+ const ready = await wait(id)
+ expect(ready.result).toMatchObject({
+ name: 'folder',
+ fileCount: 1,
+ pieceCount: 3,
+ })
+ const login = await app.inject({
+ method: 'POST',
+ url: '/rpc/auth/login',
+ payload: { token },
+ })
+ const cookie = String(login.headers['set-cookie']).split(';')[0]
+ expect(
+ (
+ await app.inject({
+ url: `${TORRENT_CREATOR_API}/${id}`,
+ headers: { cookie },
+ })
+ ).statusCode
+ ).toBe(404)
+ const result = await exp(id, false)
+ expect(result.statusCode).toBe(200)
+ expect(parseTorrent(new Uint8Array(result.rawPayload)).v1?.multiFile).toBe(
+ true
+ )
+ expect(seed).not.toHaveBeenCalled()
+ seed.mockResolvedValue({ outcome: 'created' })
+ for (const response of [await exp(id, true), await exp(id, true)])
+ expect(response.headers[TORRENT_SEED_HEADER]).toBe('submitted')
+ expect(seed).toHaveBeenCalledTimes(1)
+ expect(seed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ saveDir: allowed,
+ duplicatePolicy: 'use-existing',
+ selectedFiles: [0],
+ })
+ )
+ deny = true
+ const revoked = await app.inject({
+ url: `${TORRENT_CREATOR_API}/${id}`,
+ headers,
+ })
+ expect(revoked.statusCode).toBe(403)
+ expect(revoked.body).not.toContain(ready.result.infoHash)
+ expect((await exp(id, false)).statusCode).toBe(403)
+ await app.inject({
+ method: 'DELETE',
+ url: `${TORRENT_CREATOR_API}/${id}`,
+ headers,
+ })
+ expect((await exp(id, false)).statusCode).toBe(404)
+})
+it('still offers the downloadable torrent if original data cannot be admitted for seeding', async () => {
+ const file = path.join(allowed, 'asset.bin')
+ await writeFile(file, 'abc')
+ const { id } = (await start(file)).json()
+ expect((await wait(id)).state).toBe('ready')
+ seed.mockRejectedValue(new Error('Original data changed'))
+ const response = await exp(id, true)
+ expect(response.statusCode).toBe(200)
+ expect(response.headers[TORRENT_SEED_HEADER]).toBe('failed')
+ expect(parseTorrent(new Uint8Array(response.rawPayload)).name).toBe(
+ 'asset.bin'
+ )
+})
+
+it('denies an escaping symlink and refuses to hash a folder containing an unreadable NAS member', async () => {
+ const outside = path.join(root, 'private.bin')
+ await writeFile(outside, 'secret')
+ const alias = path.join(allowed, 'alias')
+ await symlink(outside, alias)
+ for (const source of [alias, outside]) {
+ const job = await start(source)
+ expect((await wait(job.json().id)).state).toBe('failed')
+ }
+ await writeFile(path.join(allowed, 'asset.bin'), 'protected')
+ deny = true
+ const job = await start(allowed, 'directory')
+ expect((await wait(job.json().id)).state).toBe('failed')
+ expect(seed).not.toHaveBeenCalled()
+})
+
+it('holds the single hash slot through cancellation and isolates export work', async () => {
+ const file = path.join(allowed, 'asset.bin')
+ await writeFile(file, 'valid data')
+ let resume!: () => void
+ hold = new Promise((resolve) => {
+ resume = resolve
+ })
+ const { id } = (await start(file)).json()
+ try {
+ expect((await start(file)).statusCode).toBe(429)
+ await app.inject({
+ method: 'DELETE',
+ url: `${TORRENT_CREATOR_API}/${id}`,
+ headers,
+ })
+ expect(
+ (await app.inject({ url: `${TORRENT_CREATOR_API}/${id}`, headers }))
+ .statusCode
+ ).toBe(404)
+ } finally {
+ hold = undefined
+ resume()
+ }
+ let next: string | undefined
+ await expect
+ .poll(async () => {
+ const r = await start(file)
+ if (r.statusCode === 202) next = r.json().id
+ return r.statusCode
+ })
+ .toBe(202)
+ if (!next) throw new Error('No replacement job')
+ expect((await wait(next)).state).toBe('ready')
+ let finish!: () => void
+ let entering!: () => void
+ const started = new Promise<void>((resolve) => {
+ entering = resolve
+ })
+ seed.mockImplementation(async () => {
+ entering()
+ await new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ return { outcome: 'created' }
+ })
+ const first = exp(next, true)
+ await started
+ try {
+ expect((await exp(next, true)).statusCode).toBe(429)
+ } finally {
+ finish()
+ }
+ expect((await first).headers[TORRENT_SEED_HEADER]).toBe('submitted')
+ expect(seed).toHaveBeenCalledTimes(1)
+})
+
+it('does not let abandoned, failed jobs deny a different operator a creation slot', async () => {
+ const file = path.join(allowed, 'asset.bin')
+ await writeFile(file, 'accessible')
+ for (let i = 0; i < 4; i++) {
+ const res = await start(path.join(root, 'missing'))
+ expect(res.statusCode).toBe(202)
+ expect((await wait(res.json().id)).state).toBe('failed')
+ }
+ const login = await app.inject({
+ method: 'POST',
+ url: '/rpc/auth/login',
+ payload: { token },
+ })
+ const cookie = String(login.headers['set-cookie']).split(';')[0]
+ const next = await app.inject({
+ method: 'POST',
+ url: TORRENT_CREATOR_API,
+ headers: { cookie },
+ payload: { source: { path: file, kind: 'file' }, options: {} },
+ })
+ expect(next.statusCode).toBe(202)
+})
diff --git a/src/server/routes/torrent-creator.ts b/src/server/routes/torrent-creator.ts
new file mode 100644
index 00000000..65bfd640
--- /dev/null
+++ b/src/server/routes/torrent-creator.ts
@@ -0,0 +1,283 @@
+import { randomUUID } from 'node:crypto'
+import { lstat, realpath } from 'node:fs/promises'
+import path from 'node:path'
+import {
+ type CreateTorrentHooks,
+ createTorrent,
+} from '@core/torrent/create-torrent'
+import type {
+ TaskCreateCommandResult,
+ TaskCreateRequest,
+} from '@shared/schemas/add-task'
+import {
+ serverCreateTorrentSchema,
+ TORRENT_CREATOR_API,
+ TORRENT_SEED_HEADER,
+ torrentExportSchema,
+} from '@shared/schemas/create-torrent'
+import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
+import type { ServerDownloadPathPolicy } from '../download-path-policy'
+
+export interface TorrentCreatorDeps {
+ policy: ServerDownloadPathPolicy
+ authorizeFile?: (canonical: string) => Promise<string>
+ createTask: (request: TaskCreateRequest) => Promise<TaskCreateCommandResult>
+}
+type Result = Awaited<ReturnType<typeof createTorrent>>
+type Principal = { id: string; eligible: () => boolean }
+interface Job {
+ id: string
+ owner: string
+ source: string
+ touched: number
+ abort: AbortController
+ progress: number
+ entries: Map<string, 'file' | 'directory'>
+ result?: Result
+ failed?: boolean
+ reading?: boolean
+ seed?: Promise<boolean>
+}
+const HASH_IDLE_LIMIT = 2 * 60_000
+const IDLE_LIMIT = 10 * 60_000
+const MAX_RESULTS = 4
+
+/** Only authenticated requests can retrieve their own results. No metainfo or
+ * source payload is persisted and creating/exporting alone never starts a task. */
+export function registerTorrentCreator(
+ app: FastifyInstance,
+ deps: TorrentCreatorDeps,
+ principal: (req: FastifyRequest) => Principal | undefined
+) {
+ const jobs = new Map<string, Job>()
+ let running: Promise<void> | undefined
+ let activeReads = 0
+ const discard = (job: Job) => {
+ job.abort.abort()
+ jobs.delete(job.id)
+ }
+ const reap = () => {
+ for (const job of jobs.values())
+ if (
+ Date.now() - job.touched >
+ (job.result || job.failed ? IDLE_LIMIT : HASH_IDLE_LIMIT)
+ )
+ discard(job)
+ }
+ const timer = setInterval(reap, 60_000)
+ timer.unref()
+ app.addHook('onClose', async () => {
+ clearInterval(timer)
+ for (const job of jobs.values()) discard(job)
+ await running
+ })
+ const authorize = async (candidate: string, kind: 'file' | 'directory') => {
+ if (!path.isAbsolute(candidate) || candidate.includes('\0'))
+ throw new Error('Invalid source')
+ if (kind === 'directory')
+ return (await deps.policy.authorizeDirectory(candidate)).canonicalPath
+ await deps.policy.authorizeDirectory(path.dirname(candidate))
+ const canonical = await realpath(candidate)
+ await deps.policy.authorizeDirectory(path.dirname(canonical))
+ if (
+ deps.authorizeFile &&
+ (await deps.authorizeFile(canonical)) !== canonical
+ )
+ throw new Error('Authorized file changed')
+ if (!(await lstat(canonical)).isFile())
+ throw new Error('Not a regular file')
+ return canonical
+ }
+ const get = (req: FastifyRequest, id: string) => {
+ reap()
+ const job = jobs.get(id)
+ const user = principal(req)
+ if (!job || !user?.eligible() || user.id !== job.owner) return
+ job.touched = Date.now()
+ return job
+ }
+ function reserveResultSlot(owner: string) {
+ if (jobs.size < MAX_RESULTS) return true
+ const retained = [...jobs.values()]
+ const idle = retained
+ .filter((job) => !job.reading)
+ .sort((a, b) => a.touched - b.touched)
+ // Keep one successful result per owner before retaining a second one.
+ // Failed jobs carry no useful result and can always be evicted.
+ const victim =
+ idle.find((job) => job.failed) ??
+ idle.find((job) => job.owner === owner) ??
+ idle.find((job) =>
+ retained.some((other) => other !== job && other.owner === job.owner)
+ )
+ if (!victim) return false
+ discard(victim)
+ return true
+ }
+
+ // An info hash is a swarm identifier. Apply the same current per-entry grants
+ // to revealing a ready summary as to exporting its bytes. Hold the slot
+ // until both the filesystem work and the HTTP response have finished.
+ async function readResult(
+ req: FastifyRequest,
+ reply: FastifyReply,
+ job: Job,
+ send: (t: Result, eligible: () => boolean) => Promise<void> | void
+ ) {
+ if (!job.result) return reply.code(404).send()
+ if (job.reading || activeReads >= MAX_RESULTS)
+ return reply.code(429).send({ error: 'Result busy' })
+ job.reading = true
+ activeReads++
+ let working = true
+ let finished = false
+ const release = () => {
+ if (working || !finished) return
+ reply.raw.off('finish', onFinish)
+ reply.raw.off('close', onFinish)
+ job.reading = false
+ activeReads--
+ }
+ const onFinish = () => {
+ finished = true
+ release()
+ }
+ reply.raw.once('finish', onFinish)
+ reply.raw.once('close', onFinish)
+ const user = principal(req)
+ const eligible = () =>
+ !job.abort.signal.aborted && !reply.raw.destroyed && !!user?.eligible()
+ try {
+ try {
+ for (const [entry, kind] of job.entries) {
+ if (!eligible() || (await authorize(entry, kind)) !== entry)
+ throw new Error('Source no longer authorized')
+ }
+ } catch {
+ return reply.code(403).send()
+ }
+ if (!eligible()) return reply.code(403).send()
+ await send(job.result, eligible)
+ return reply
+ } finally {
+ working = false
+ release()
+ }
+ }
+ app.post(TORRENT_CREATOR_API, async (req, reply) => {
+ reply.header('cache-control', 'no-store')
+ const user = principal(req)
+ if (!user?.eligible()) return reply.code(401).send()
+ const data = serverCreateTorrentSchema.safeParse(req.body)
+ if (!data.success)
+ return reply.code(400).send({ error: 'Invalid torrent options' })
+ reap()
+ if (running || !reserveResultSlot(user.id))
+ return reply.code(429).send({ error: 'Torrent creator busy' })
+ const { source, options } = data.data
+ const job: Job = {
+ id: randomUUID(),
+ owner: user.id,
+ source: source.path,
+ touched: Date.now(),
+ progress: 0,
+ abort: new AbortController(),
+ entries: new Map(),
+ }
+ jobs.set(job.id, job)
+ const run = async () => {
+ const canonical = await authorize(source.path, source.kind)
+ const stat = await lstat(canonical)
+ if (source.kind === 'file' ? !stat.isFile() : !stat.isDirectory())
+ throw new Error('Source kind changed')
+ const hooks: CreateTorrentHooks = {
+ signal: job.abort.signal,
+ picked: { path: canonical, dev: stat.dev, ino: stat.ino },
+ authorizeEntry: async (entry, kind) => {
+ if (!user.eligible() || (await authorize(entry, kind)) !== entry)
+ throw new Error('Source no longer authorized')
+ job.entries.set(entry, kind)
+ },
+ onProgress(done, total) {
+ if (!user.eligible()) throw new Error('Session expired')
+ job.progress = total ? done / total : 1
+ },
+ }
+ job.result = await createTorrent(
+ { ...options, sourcePath: canonical },
+ hooks
+ )
+ // The torrent root name is the canonical basename, including when picked through an alias.
+ job.source = canonical
+ }
+ running = run()
+ .catch(() => {
+ job.failed = true
+ job.entries.clear()
+ })
+ .finally(() => {
+ running = undefined
+ })
+ return reply.code(202).send({ id: job.id })
+ })
+ const endpoint = `${TORRENT_CREATOR_API}/:id`
+ app.get<{ Params: { id: string } }>(endpoint, async (req, reply) => {
+ reply.header('cache-control', 'no-store')
+ const job = get(req, req.params.id)
+ if (!job) return reply.code(404).send()
+ if (job.failed) return { state: 'failed' }
+ if (!job.result) return { state: 'hashing', progress: job.progress }
+ return readResult(
+ req,
+ reply,
+ job,
+ ({ bytes: _bytes, directory: _directory, ...summary }) => {
+ reply.send({ state: 'ready', result: { id: job.id, ...summary } })
+ }
+ )
+ })
+ app.delete<{ Params: { id: string } }>(endpoint, async (req, reply) => {
+ const job = get(req, req.params.id)
+ if (job) discard(job)
+ return reply.code(204).send()
+ })
+ app.post<{ Params: { id: string } }>(
+ `${endpoint}/export`,
+ async (req, reply) => {
+ const data = torrentExportSchema.safeParse(req.body)
+ if (!data.success) return reply.code(400).send()
+ const job = get(req, req.params.id)
+ if (!job) return reply.code(404).send()
+ return readResult(req, reply, job, async (t, eligible) => {
+ let seeding = 'not-requested'
+ if (data.data.seed) {
+ job.seed ??= deps
+ .createTask({
+ type: 'bt',
+ payload: {
+ kind: 'torrent-base64',
+ base64: Buffer.from(t.bytes).toString('base64'),
+ },
+ selectedFiles: Array.from({ length: t.fileCount }, (_, i) => i),
+ saveDir: path.dirname(job.source),
+ duplicatePolicy: 'use-existing',
+ })
+ .then((result) =>
+ ['created', 'reused', 'rechecked'].includes(result.outcome)
+ )
+ .catch(() => false)
+ seeding = (await job.seed) ? 'submitted' : 'failed'
+ }
+ if (!eligible()) {
+ reply.code(403).send()
+ return
+ }
+ reply
+ .header('cache-control', 'no-store')
+ .header(TORRENT_SEED_HEADER, seeding)
+ .type('application/x-bittorrent')
+ .send(Buffer.from(t.bytes))
+ })
+ }
+ )
+}
diff --git a/src/server/server-directory-service.test.ts b/src/server/server-directory-service.test.ts
index f9f3ad96..f800d2f6 100644
--- a/src/server/server-directory-service.test.ts
+++ b/src/server/server-directory-service.test.ts
@@ -45,6 +45,25 @@ afterEach(async () => {
})
describe('ServerDirectoryService', () => {
+ it('accepts readable sources without weakening save-directory checks', async () => {
+ const { downloads, policy } = await fixture()
+ const service = new ServerDirectoryService(policy, {
+ access: async (candidate, mode) => {
+ if (mode !== undefined && mode & constants.W_OK)
+ throw Object.assign(new Error('read only'), { code: 'EACCES' })
+ return access(candidate, mode)
+ },
+ opendir,
+ mkdir,
+ })
+ expect(
+ await service.validate({ path: downloads, access: 'read' })
+ ).toMatchObject({ ok: true })
+ expect(await service.validate({ path: downloads })).toMatchObject({
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ })
it('lists only immediate authorized directories with deterministic natural order and hidden filter', async () => {
const { root, downloads, service } = await fixture()
await Promise.all(
diff --git a/src/server/server-directory-service.ts b/src/server/server-directory-service.ts
index 9153c132..27c5ec84 100644
--- a/src/server/server-directory-service.ts
+++ b/src/server/server-directory-service.ts
@@ -374,7 +374,13 @@ export class ServerDirectoryService {
if (!request.success) return failure('invalidPath')
try {
const directory = await this.policy.authorizeDirectory(request.data.path)
- if (!(await this.writable(directory))) return failure('permissionDenied')
+ if (request.data.access === 'read')
+ await this.fs.access(
+ directory.canonicalPath,
+ constants.R_OK | constants.X_OK
+ )
+ else if (!(await this.writable(directory)))
+ return failure('permissionDenied')
return ValidateServerDirectoryResultSchema.parse({
ok: true,
value: { path: directory.path },
diff --git a/src/shared/application-menu-catalog.ts b/src/shared/application-menu-catalog.ts
index 5621446c..1e1e7053 100644
--- a/src/shared/application-menu-catalog.ts
+++ b/src/shared/application-menu-catalog.ts
@@ -5,7 +5,7 @@ export interface ProductMenuItem {
id: string
commandId: CommandId
title: string
- section: 'app' | 'task' | 'help'
+ section: 'app' | 'file' | 'task' | 'help'
group: string
order: number
scope: 'local' | 'selection' | 'list' | 'instance'
@@ -35,7 +35,7 @@ export const PRODUCT_MENU_ITEMS: readonly ProductMenuItem[] = [
id: 'menubar.task.new',
commandId: CommandIds.TaskNew,
title: 'menu.task.newTask',
- section: 'task',
+ section: 'file',
group: '1_new',
order: 10,
scope: 'local',
@@ -44,7 +44,7 @@ export const PRODUCT_MENU_ITEMS: readonly ProductMenuItem[] = [
id: 'menubar.task.newBt',
commandId: CommandIds.TaskNewBt,
title: 'menu.task.newBtTask',
- section: 'task',
+ section: 'file',
group: '1_new',
order: 20,
scope: 'local',
@@ -53,11 +53,20 @@ export const PRODUCT_MENU_ITEMS: readonly ProductMenuItem[] = [
id: 'menubar.task.openFile',
commandId: CommandIds.TaskOpenFile,
title: 'menu.task.openFile',
- section: 'task',
+ section: 'file',
group: '1_new',
order: 30,
scope: 'local',
},
+ {
+ id: 'menubar.file.createTorrent',
+ commandId: CommandIds.CreateTorrentFile,
+ title: 'createTorrent.menuLabel',
+ section: 'file',
+ group: '2_create',
+ order: 10,
+ scope: 'local',
+ },
{
id: 'menubar.task.list',
commandId: CommandIds.NavigateTaskList,
diff --git a/src/shared/commands-catalog.ts b/src/shared/commands-catalog.ts
index 57286e26..2865564d 100644
--- a/src/shared/commands-catalog.ts
+++ b/src/shared/commands-catalog.ts
@@ -15,6 +15,7 @@ export const CommandIds = {
AppQuit: 'motrix.app.quit',
// Task
+ CreateTorrentFile: 'motrix.torrent.create',
TaskNew: 'motrix.task.new',
TaskNewBt: 'motrix.task.newBt',
TaskOpenFile: 'motrix.task.openFile',
diff --git a/src/shared/constants/add-task.ts b/src/shared/constants/add-task.ts
index fcb562d5..c74dc715 100644
--- a/src/shared/constants/add-task.ts
+++ b/src/shared/constants/add-task.ts
@@ -1,2 +1,3 @@
+export const TASK_FORM_WIDTH = 640
export const ADD_TASK_COLLAPSED_HEIGHT = 386
export const ADD_TASK_MAX_HEIGHT = 760
diff --git a/src/shared/constants/window-chrome.ts b/src/shared/constants/window-chrome.ts
index d1bfdafc..57afc17b 100644
--- a/src/shared/constants/window-chrome.ts
+++ b/src/shared/constants/window-chrome.ts
@@ -1,5 +1,13 @@
/** Renderer-drawn title-bar geometry for surfaces without native WCO. */
export const DESKTOP_WINDOW_CHROME_HEIGHT = 40
-/** Centers native Linux controls on the app's existing y=27 action row. */
-export const WINDOW_CONTROLS_OVERLAY_HEIGHT = 54
+/** Full title bar centered on the native caption row (macOS lights: y=20, diameter=14). */
+export const NATIVE_TITLE_BAR_HEIGHT = 54
+/** Linux reserves the full title bar for its native controls overlay. */
+export const WINDOW_CONTROLS_OVERLAY_HEIGHT = NATIVE_TITLE_BAR_HEIGHT
export const WINDOW_CHROME_EDGE_GAP = 16
+
+export function windowChromeHeight(platform: string, compact: boolean): number {
+ return platform === 'linux' || (platform === 'darwin' && !compact)
+ ? NATIVE_TITLE_BAR_HEIGHT
+ : DESKTOP_WINDOW_CHROME_HEIGHT
+}
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 57f08043..429b8a6a 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -45,6 +45,7 @@ export enum ErrorCode {
StunDetectionFailed = 'STUN_DETECTION_FAILED',
// Torrent
TorrentParseFailed = 'TORRENT_PARSE_FAILED',
+ TorrentCreateFailed = 'TORRENT_CREATE_FAILED',
TorrentDuplicateConflict = 'TORRENT_DUPLICATE_CONFLICT',
MagnetResolveFailed = 'MAGNET_RESOLVE_FAILED',
MagnetResolveTimeout = 'MAGNET_RESOLVE_TIMEOUT',
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 6c2afa58..3bddba32 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -2930,7 +2930,7 @@
"title": "هذا التورنت موجود بالفعل"
},
"errors": {
- "headerNameRequired": "أدخل اسم الترويسة أو أزل هذه الترويسة.",
+ "headerNameRequired": "أدخل اسمًا لكل ترويسة لها قيمة.",
"missingSource": "يلزم ملف تورنت أو رابط magnet",
"noFilesSelected": "حدد ملفًا واحدًا على الأقل",
"saveDirRequired": "يلزم تحديد مجلد الحفظ",
@@ -3612,5 +3612,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "إنشاء تورنت",
+ "source": "المحتوى المراد مشاركته",
+ "options": "خيارات التورنت",
+ "trackers": "المتتبعات",
+ "trackersPlaceholder": "رابط announce واحد لكل سطر",
+ "webSeeds": "البذور الشبكية",
+ "webSeedsPlaceholder": "رابط HTTP(S) واحد لكل سطر (اختياري)",
+ "comment": "تعليق",
+ "private": "تورنت خاص",
+ "privateDesc": "يعطّل DHT وتبادل الأقران؛ التوزيع عبر المتتبعات فقط.",
+ "pieceLength": "حجم القطعة",
+ "pieceAuto": "تلقائي",
+ "hashing": "جارٍ حساب البصمات…",
+ "resultName": "الاسم",
+ "resultSize": "الحجم",
+ "resultInfoHash": "بصمة info",
+ "saveFile": "حفظ .torrent",
+ "create": "إنشاء",
+ "savedToast": "تم حفظ التورنت في {{path}}",
+ "createFailed": "تعذّر إنشاء التورنت",
+ "saveFailed": "تعذّر حفظ ملف التورنت",
+ "seedAfter": "بدء البذر بعد الحفظ",
+ "seedFailed": "تعذّر بدء البذر.",
+ "seedSubmitted": "أُرسلت مهمة البذر.",
+ "invalidOptions": "كل قائمة تقبل حتى {{limit}} عنوانًا صالحًا. يحتاج التورنت الخاص إلى متتبّع.",
+ "menuLabel": "إنشاء ملف تورنت…",
+ "downloadRequested": "طُلب تنزيل {{path}}"
}
}
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 5735425c..5d9e5608 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -2850,7 +2850,7 @@
"title": "Този торент вече съществува"
},
"errors": {
- "headerNameRequired": "Въведете име на заглавката или я премахнете.",
+ "headerNameRequired": "Въведете име за всеки хедър със стойност.",
"missingSource": "Необходим е торент файл или magnet връзка",
"noFilesSelected": "Изберете поне един файл",
"saveDirRequired": "Необходима е папка за запазване",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Създаване на торент",
+ "source": "Съдържание за споделяне",
+ "options": "Настройки на торента",
+ "trackers": "Тракери",
+ "trackersPlaceholder": "Един announce URL на ред",
+ "webSeeds": "Web сидове",
+ "webSeedsPlaceholder": "Един HTTP(S) URL на ред (по желание)",
+ "comment": "Коментар",
+ "private": "Частен торент",
+ "privateDesc": "Изключва DHT и обмена между пиъри; разпространение само през тракер.",
+ "pieceLength": "Размер на парчето",
+ "pieceAuto": "Автоматично",
+ "hashing": "Изчисляване на хешове…",
+ "resultName": "Име",
+ "resultSize": "Размер",
+ "resultInfoHash": "Info хеш",
+ "saveFile": "Запазете .torrent",
+ "create": "Създаване",
+ "savedToast": "Торентът е запазен в {{path}}",
+ "createFailed": "Торентът не можа да бъде създаден",
+ "saveFailed": "Торент файлът не можа да бъде запазен",
+ "seedAfter": "Започване на сийдване след запазване",
+ "seedFailed": "Сийдването не можа да започне.",
+ "seedSubmitted": "Задачата за сийдване е подадена.",
+ "invalidOptions": "До {{limit}} валидни URL адреса в списък. Частните торенти изискват тракер.",
+ "menuLabel": "Създаване на торент файл…",
+ "downloadRequested": "Заявено е изтегляне: {{path}}"
}
}
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index e4cc4005..fae06184 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -2870,7 +2870,7 @@
"title": "Aquest torrent ja existeix"
},
"errors": {
- "headerNameRequired": "Introduïu un nom per a la capçalera o elimineu-la.",
+ "headerNameRequired": "Introdueix un nom per a cada capçalera que tingui un valor.",
"missingSource": "Cal un fitxer torrent o un enllaç magnet",
"noFilesSelected": "Seleccioneu almenys un fitxer",
"saveDirRequired": "Cal una carpeta de destinació",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Crea un torrent",
+ "source": "Contingut per compartir",
+ "options": "Opcions del torrent",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Un URL announce per línia",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Un URL HTTP(S) per línia (opcional)",
+ "comment": "Comentari",
+ "private": "Torrent privat",
+ "privateDesc": "Desactiva DHT i l’intercanvi entre peers; distribució només per tracker.",
+ "pieceLength": "Mida de les peces",
+ "pieceAuto": "Automàtica",
+ "hashing": "Calculant els hash…",
+ "resultName": "Nom",
+ "resultSize": "Mida",
+ "resultInfoHash": "Hash info",
+ "saveFile": "Desa el .torrent",
+ "create": "Crea",
+ "savedToast": "Torrent desat a {{path}}",
+ "createFailed": "No s’ha pogut crear el torrent",
+ "saveFailed": "No s’ha pogut desar el fitxer torrent",
+ "seedAfter": "Comença a compartir després de desar",
+ "seedFailed": "No s’ha pogut començar a compartir.",
+ "seedSubmitted": "S’ha enviat la tasca de compartició.",
+ "invalidOptions": "Cada llista admet fins a {{limit}} URL vàlids. Els torrents privats necessiten un rastrejador.",
+ "menuLabel": "Crea un fitxer torrent…",
+ "downloadRequested": "S’ha sol·licitat la baixada de {{path}}"
}
}
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index f24f329f..ef7af237 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1129,7 +1129,7 @@
"doc": "Dokument"
},
"errors": {
- "headerNameRequired": "Geben Sie einen Headernamen ein oder entfernen Sie diesen Header.",
+ "headerNameRequired": "Für jeden Header mit einem Wert ist ein Name erforderlich.",
"urlsRequired": "Mindestens eine URL ist erforderlich",
"saveDirRequired": "Ein Speicherordner ist erforderlich",
"noFilesSelected": "Wählen Sie mindestens eine Datei aus",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Torrent erstellen",
+ "source": "Inhalt zum Teilen",
+ "options": "Torrent-Optionen",
+ "trackers": "Tracker",
+ "trackersPlaceholder": "Eine Announce-URL pro Zeile",
+ "webSeeds": "Web-Seeds",
+ "webSeedsPlaceholder": "Eine HTTP(S)-URL pro Zeile (optional)",
+ "comment": "Kommentar",
+ "private": "Privater Torrent",
+ "privateDesc": "DHT und Peeraustausch deaktivieren; Verteilung nur über Tracker.",
+ "pieceLength": "Piece-Größe",
+ "pieceAuto": "Automatisch",
+ "hashing": "Hashes werden berechnet…",
+ "resultName": "Name",
+ "resultSize": "Größe",
+ "resultInfoHash": "Info-Hash",
+ "saveFile": ".torrent speichern",
+ "create": "Erstellen",
+ "savedToast": "Torrent gespeichert unter {{path}}",
+ "createFailed": "Torrent konnte nicht erstellt werden",
+ "saveFailed": "Torrent-Datei konnte nicht gespeichert werden",
+ "seedAfter": "Nach dem Speichern seeden",
+ "seedFailed": "Das Seeden konnte nicht gestartet werden.",
+ "seedSubmitted": "Der Seeding-Auftrag wurde übermittelt.",
+ "invalidOptions": "Pro Liste sind bis zu {{limit}} gültige URLs zulässig. Private Torrents benötigen einen Tracker.",
+ "menuLabel": "Torrent-Datei erstellen…",
+ "downloadRequested": "Download angefordert: {{path}}"
}
}
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 2763b244..a336090b 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -2850,7 +2850,7 @@
"title": "Αυτό το torrent υπάρχει ήδη"
},
"errors": {
- "headerNameRequired": "Εισαγάγετε όνομα κεφαλίδας ή αφαιρέστε αυτήν την κεφαλίδα.",
+ "headerNameRequired": "Συμπληρώστε όνομα για κάθε κεφαλίδα που έχει τιμή.",
"missingSource": "Απαιτείται αρχείο torrent ή σύνδεσμος magnet",
"noFilesSelected": "Επιλέξτε τουλάχιστον ένα αρχείο",
"saveDirRequired": "Απαιτείται φάκελος αποθήκευσης",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Δημιουργία torrent",
+ "source": "Περιεχόμενο για διαμοιρασμό",
+ "options": "Επιλογές torrent",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Ένα URL announce ανά γραμμή",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Ένα URL HTTP(S) ανά γραμμή (προαιρετικό)",
+ "comment": "Σχόλιο",
+ "private": "Ιδιωτικό torrent",
+ "privateDesc": "Απενεργοποιεί DHT και ανταλλαγή peers· διανομή μόνο μέσω tracker.",
+ "pieceLength": "Μέγεθος piece",
+ "pieceAuto": "Αυτόματα",
+ "hashing": "Υπολογισμός hash…",
+ "resultName": "Όνομα",
+ "resultSize": "Μέγεθος",
+ "resultInfoHash": "Hash πληροφοριών",
+ "saveFile": "Αποθήκευση .torrent",
+ "create": "Δημιουργία",
+ "savedToast": "Το torrent αποθηκεύτηκε στο {{path}}",
+ "createFailed": "Δεν ήταν δυνατή η δημιουργία του torrent",
+ "saveFailed": "Δεν ήταν δυνατή η αποθήκευση του αρχείου torrent",
+ "seedAfter": "Έναρξη διαμοιρασμού μετά την αποθήκευση",
+ "seedFailed": "Ο διαμοιρασμός δεν ξεκίνησε.",
+ "seedSubmitted": "Η εργασία διαμοιρασμού υποβλήθηκε.",
+ "invalidOptions": "Έως {{limit}} έγκυρα URL ανά λίστα. Τα ιδιωτικά torrent απαιτούν tracker.",
+ "menuLabel": "Δημιουργία αρχείου torrent…",
+ "downloadRequested": "Ζητήθηκε λήψη: {{path}}"
}
}
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 48767f7d..b1f30048 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1129,7 +1129,7 @@
"doc": "Document"
},
"errors": {
- "headerNameRequired": "Enter a header name or remove this header.",
+ "headerNameRequired": "Add a name for each header with a value.",
"urlsRequired": "At least one URL is required",
"saveDirRequired": "Save directory is required",
"noFilesSelected": "Select at least one file",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Create torrent",
+ "source": "Content to share",
+ "options": "Torrent options",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "One announce URL per line",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "One HTTP(S) URL per line (optional)",
+ "comment": "Comment",
+ "private": "Private torrent",
+ "privateDesc": "Disable DHT and peer exchange; tracker-only distribution.",
+ "pieceLength": "Piece size",
+ "pieceAuto": "Automatic",
+ "hashing": "Hashing…",
+ "resultName": "Name",
+ "resultSize": "Size",
+ "resultInfoHash": "Info hash",
+ "saveFile": "Save .torrent",
+ "create": "Create",
+ "savedToast": "Torrent saved to {{path}}",
+ "createFailed": "Could not create the torrent",
+ "saveFailed": "Could not save the torrent file",
+ "seedAfter": "Start seeding after saving",
+ "seedFailed": "The seeding task could not be started.",
+ "seedSubmitted": "The seeding task was submitted.",
+ "invalidOptions": "Use up to {{limit}} valid URLs per list. Private torrents need a tracker.",
+ "menuLabel": "Create Torrent File…",
+ "downloadRequested": "Download requested: {{path}}"
}
}
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 5659c344..e7eb37a9 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1141,7 +1141,7 @@
"doc": "Documento"
},
"errors": {
- "headerNameRequired": "Introduce un nombre para la cabecera o elimínala.",
+ "headerNameRequired": "Añade un nombre a cada cabecera que tenga un valor.",
"urlsRequired": "Se requiere al menos una URL",
"saveDirRequired": "Se requiere una carpeta de destino",
"noFilesSelected": "Selecciona al menos un archivo",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Crear torrent",
+ "source": "Contenido para compartir",
+ "options": "Opciones del torrent",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Una URL announce por línea",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Una URL HTTP(S) por línea (opcional)",
+ "comment": "Comentario",
+ "private": "Torrent privado",
+ "privateDesc": "Desactiva DHT y el intercambio entre pares; distribución solo por tracker.",
+ "pieceLength": "Tamaño de pieza",
+ "pieceAuto": "Automático",
+ "hashing": "Calculando hashes…",
+ "resultName": "Nombre",
+ "resultSize": "Tamaño",
+ "resultInfoHash": "Hash de info",
+ "saveFile": "Guardar .torrent",
+ "create": "Crear",
+ "savedToast": "Torrent guardado en {{path}}",
+ "createFailed": "No se pudo crear el torrent",
+ "saveFailed": "No se pudo guardar el archivo torrent",
+ "seedAfter": "Compartir después de guardar",
+ "seedFailed": "No se pudo iniciar la tarea de siembra.",
+ "seedSubmitted": "Se envió la tarea de siembra.",
+ "invalidOptions": "Hasta {{limit}} URL válidas por lista. Los torrents privados requieren un rastreador.",
+ "menuLabel": "Crear archivo torrent…",
+ "downloadRequested": "Descarga solicitada: {{path}}"
}
}
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 45e1d248..168eb30c 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -2850,7 +2850,7 @@
"title": "این تورنت از قبل وجود دارد"
},
"errors": {
- "headerNameRequired": "نام سرآیند را وارد کنید یا این سرآیند را حذف کنید.",
+ "headerNameRequired": "برای هر سرآیند دارای مقدار، یک نام وارد کنید.",
"missingSource": "فایل تورنت یا پیوند magnet لازم است",
"noFilesSelected": "حداقل یک فایل انتخاب کنید",
"saveDirRequired": "پوشهٔ ذخیره لازم است",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "ساخت تورنت",
+ "source": "محتوای اشتراکی",
+ "options": "گزینه‌های تورنت",
+ "trackers": "ترکرها",
+ "trackersPlaceholder": "هر خط یک announce URL",
+ "webSeeds": "وب‌سیدها",
+ "webSeedsPlaceholder": "هر خط یک URL HTTP(S) (اختیاری)",
+ "comment": "یادداشت",
+ "private": "تورنت خصوصی",
+ "privateDesc": "DHT و تبادل همتا غیرفعال می‌شود؛ توزیع فقط از طریق ترکر.",
+ "pieceLength": "اندازه قطعه",
+ "pieceAuto": "خودکار",
+ "hashing": "در حال محاسبه هش…",
+ "resultName": "نام",
+ "resultSize": "حجم",
+ "resultInfoHash": "هش info",
+ "saveFile": "ذخیره .torrent",
+ "create": "ساخت",
+ "savedToast": "تورنت در {{path}} ذخیره شد",
+ "createFailed": "ساخت تورنت ممکن نشد",
+ "saveFailed": "ذخیره فایل تورنت ممکن نشد",
+ "seedAfter": "آغاز سید کردن پس از ذخیره",
+ "seedFailed": "سید کردن آغاز نشد.",
+ "seedSubmitted": "درخواست سید کردن ارسال شد.",
+ "invalidOptions": "هر فهرست حداکثر {{limit}} نشانی معتبر می‌پذیرد. تورنت خصوصی به ترکر نیاز دارد.",
+ "menuLabel": "ساخت فایل تورنت…",
+ "downloadRequested": "درخواست دانلود: {{path}}"
}
}
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index d1432d0e..b413d169 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -2870,7 +2870,7 @@
"title": "Ce torrent existe déjà"
},
"errors": {
- "headerNameRequired": "Saisissez un nom d’en-tête ou supprimez cet en-tête.",
+ "headerNameRequired": "Donnez un nom à chaque en-tête qui contient une valeur.",
"missingSource": "Un fichier torrent ou un lien magnet est requis",
"noFilesSelected": "Sélectionnez au moins un fichier",
"saveDirRequired": "Le dossier de destination est requis",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Créer un torrent",
+ "source": "Contenu à partager",
+ "options": "Options du torrent",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Une URL d’annonce par ligne",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Une URL HTTP(S) par ligne (facultatif)",
+ "comment": "Commentaire",
+ "private": "Torrent privé",
+ "privateDesc": "Désactive DHT et l’échange entre pairs ; distribution par trackers uniquement.",
+ "pieceLength": "Taille des pièces",
+ "pieceAuto": "Automatique",
+ "hashing": "Calcul des empreintes…",
+ "resultName": "Nom",
+ "resultSize": "Taille",
+ "resultInfoHash": "Empreinte info",
+ "saveFile": "Enregistrer le .torrent",
+ "create": "Créer",
+ "savedToast": "Torrent enregistré dans {{path}}",
+ "createFailed": "Impossible de créer le torrent",
+ "saveFailed": "Impossible d’enregistrer le fichier torrent",
+ "seedAfter": "Partager après l’enregistrement",
+ "seedFailed": "Le partage n’a pas pu démarrer.",
+ "seedSubmitted": "La tâche de partage a été envoyée.",
+ "invalidOptions": "Chaque liste accepte jusqu’à {{limit}} URL valides. Un torrent privé nécessite un tracker.",
+ "menuLabel": "Créer un fichier torrent…",
+ "downloadRequested": "Téléchargement demandé : {{path}}"
}
}
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 7879d0d1..3fb03dae 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1129,7 +1129,7 @@
"doc": "Dokumentum"
},
"errors": {
- "headerNameRequired": "Adja meg a fejléc nevét, vagy távolítsa el ezt a fejlécet.",
+ "headerNameRequired": "Minden értékkel rendelkező fejléchez adjon meg nevet.",
"urlsRequired": "Legalább egy URL megadása szükséges",
"saveDirRequired": "Mentési mappa megadása szükséges",
"noFilesSelected": "Válassz ki legalább egy fájlt",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Torrent létrehozása",
+ "source": "Megosztandó tartalom",
+ "options": "Torrentbeállítások",
+ "trackers": "Trackerek",
+ "trackersPlaceholder": "Soronként egy announce URL",
+ "webSeeds": "Web seedek",
+ "webSeedsPlaceholder": "Soronként egy HTTP(S) URL (opcionális)",
+ "comment": "Megjegyzés",
+ "private": "Privát torrent",
+ "privateDesc": "Kikapcsolja a DHT-t és a peer-cserét; csak trackeren keresztül oszt el.",
+ "pieceLength": "Darabméret",
+ "pieceAuto": "Automatikus",
+ "hashing": "Hashek számítása…",
+ "resultName": "Név",
+ "resultSize": "Méret",
+ "resultInfoHash": "Info hash",
+ "saveFile": ".torrent mentése",
+ "create": "Létrehozás",
+ "savedToast": "Torrent mentve ide: {{path}}",
+ "createFailed": "A torrentet nem sikerült létrehozni",
+ "saveFailed": "A torrentfájlt nem sikerült menteni",
+ "seedAfter": "Megosztás indítása mentés után",
+ "seedFailed": "A megosztás nem indult el.",
+ "seedSubmitted": "A megosztási feladat elküldve.",
+ "invalidOptions": "Listánként legfeljebb {{limit}} érvényes URL adható meg. A privát torrenthez tracker szükséges.",
+ "menuLabel": "Torrentfájl létrehozása…",
+ "downloadRequested": "Letöltés kérve: {{path}}"
}
}
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index a211bcee..70cb3f65 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1116,7 +1116,7 @@
"doc": "Dokumen"
},
"errors": {
- "headerNameRequired": "Masukkan nama header atau hapus header ini.",
+ "headerNameRequired": "Beri nama setiap header yang memiliki nilai.",
"urlsRequired": "Setidaknya satu URL diperlukan",
"saveDirRequired": "Folder penyimpanan diperlukan",
"noFilesSelected": "Pilih setidaknya satu berkas",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Buat torrent",
+ "source": "Konten untuk dibagikan",
+ "options": "Opsi torrent",
+ "trackers": "Tracker",
+ "trackersPlaceholder": "Satu URL announce per baris",
+ "webSeeds": "Web seed",
+ "webSeedsPlaceholder": "Satu URL HTTP(S) per baris (opsional)",
+ "comment": "Komentar",
+ "private": "Torrent privat",
+ "privateDesc": "Nonaktifkan DHT dan pertukaran peer; distribusi hanya via tracker.",
+ "pieceLength": "Ukuran potongan",
+ "pieceAuto": "Otomatis",
+ "hashing": "Menghitung hash…",
+ "resultName": "Nama",
+ "resultSize": "Ukuran",
+ "resultInfoHash": "Hash info",
+ "saveFile": "Simpan .torrent",
+ "create": "Buat",
+ "savedToast": "Torrent disimpan ke {{path}}",
+ "createFailed": "Tidak dapat membuat torrent",
+ "saveFailed": "Tidak dapat menyimpan file torrent",
+ "seedAfter": "Mulai menyemai setelah menyimpan",
+ "seedFailed": "Tugas penyemaian tidak dapat dimulai.",
+ "seedSubmitted": "Tugas penyemaian telah dikirim.",
+ "invalidOptions": "Maksimal {{limit}} URL valid per daftar. Torrent privat memerlukan pelacak.",
+ "menuLabel": "Buat berkas torrent…",
+ "downloadRequested": "Unduhan diminta: {{path}}"
}
}
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index 3243efd6..fa0f0d93 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1142,7 +1142,7 @@
"doc": "Documento"
},
"errors": {
- "headerNameRequired": "Inserisci un nome per l’intestazione o rimuovila.",
+ "headerNameRequired": "Assegna un nome a ogni intestazione con un valore.",
"urlsRequired": "È richiesto almeno un URL",
"saveDirRequired": "È richiesta una cartella di salvataggio",
"noFilesSelected": "Seleziona almeno un file",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Crea torrent",
+ "source": "Contenuto da condividere",
+ "options": "Opzioni torrent",
+ "trackers": "Tracker",
+ "trackersPlaceholder": "Un URL announce per riga",
+ "webSeeds": "Web seed",
+ "webSeedsPlaceholder": "Un URL HTTP(S) per riga (facoltativo)",
+ "comment": "Commento",
+ "private": "Torrent privato",
+ "privateDesc": "Disattiva DHT e scambio tra peer; distribuzione solo via tracker.",
+ "pieceLength": "Dimensione pezzi",
+ "pieceAuto": "Automatica",
+ "hashing": "Calcolo degli hash…",
+ "resultName": "Nome",
+ "resultSize": "Dimensione",
+ "resultInfoHash": "Hash info",
+ "saveFile": "Salva .torrent",
+ "create": "Crea",
+ "savedToast": "Torrent salvato in {{path}}",
+ "createFailed": "Impossibile creare il torrent",
+ "saveFailed": "Impossibile salvare il file torrent",
+ "seedAfter": "Avvia la condivisione dopo il salvataggio",
+ "seedFailed": "Impossibile avviare la condivisione.",
+ "seedSubmitted": "La richiesta di condivisione è stata inviata.",
+ "invalidOptions": "Ogni elenco accetta fino a {{limit}} URL validi. I torrent privati richiedono un tracker.",
+ "menuLabel": "Crea file torrent…",
+ "downloadRequested": "Download richiesto: {{path}}"
}
}
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index dfae6506..67567476 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1116,7 +1116,7 @@
"doc": "文書"
},
"errors": {
- "headerNameRequired": "ヘッダー名を入力するか、このヘッダーを削除してください。",
+ "headerNameRequired": "値を入力したヘッダーには名前が必要です。",
"urlsRequired": "URL を 1 件以上入力してください",
"saveDirRequired": "保存先フォルダーを指定してください",
"noFilesSelected": "ファイルを 1 個以上選択してください",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "トレントを作成",
+ "source": "共有する内容",
+ "options": "トレントの設定",
+ "trackers": "トラッカー",
+ "trackersPlaceholder": "1 行に 1 つの announce URL",
+ "webSeeds": "Web シード",
+ "webSeedsPlaceholder": "1 行に 1 つの HTTP(S) URL(任意)",
+ "comment": "コメント",
+ "private": "プライベートトレント",
+ "privateDesc": "DHT と PEX を無効化し、トラッカー限定で配信します。",
+ "pieceLength": "ピースサイズ",
+ "pieceAuto": "自動",
+ "hashing": "ハッシュ計算中…",
+ "resultName": "名前",
+ "resultSize": "サイズ",
+ "resultInfoHash": "Info ハッシュ",
+ "saveFile": ".torrent を保存",
+ "create": "作成",
+ "savedToast": "トレントを {{path}} に保存しました",
+ "createFailed": "トレントを作成できませんでした",
+ "saveFailed": "トレントファイルを保存できませんでした",
+ "seedAfter": "保存後にシードを開始",
+ "seedFailed": "シードを開始できませんでした。",
+ "seedSubmitted": "シードタスクを送信しました。",
+ "invalidOptions": "各リストには有効な URL を {{limit}} 件まで入力できます。プライベートトレントにはトラッカーが必要です。",
+ "menuLabel": "トレントファイルを作成…",
+ "downloadRequested": "ダウンロードをリクエストしました:{{path}}"
}
}
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index ec43ca16..db82400a 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1116,7 +1116,7 @@
"doc": "문서"
},
"errors": {
- "headerNameRequired": "헤더 이름을 입력하거나 이 헤더를 제거하세요.",
+ "headerNameRequired": "값을 입력한 헤더에는 이름이 필요합니다.",
"urlsRequired": "URL을 하나 이상 입력하세요",
"saveDirRequired": "저장 폴더를 지정하세요",
"noFilesSelected": "파일을 하나 이상 선택하세요",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "토렌트 만들기",
+ "source": "공유할 콘텐츠",
+ "options": "토렌트 옵션",
+ "trackers": "트래커",
+ "trackersPlaceholder": "줄마다 announce URL 하나씩",
+ "webSeeds": "웹 시드",
+ "webSeedsPlaceholder": "줄마다 HTTP(S) URL 하나씩 (선택)",
+ "comment": "메모",
+ "private": "비공개 토렌트",
+ "privateDesc": "DHT와 PEX를 비활성화하고 트래커로만 배포합니다.",
+ "pieceLength": "조각 크기",
+ "pieceAuto": "자동",
+ "hashing": "해시 계산 중…",
+ "resultName": "이름",
+ "resultSize": "크기",
+ "resultInfoHash": "Info 해시",
+ "saveFile": ".torrent 저장",
+ "create": "만들기",
+ "savedToast": "토렌트를 {{path}} 에 저장했습니다",
+ "createFailed": "토렌트를 만들 수 없습니다",
+ "saveFailed": "토렌트 파일을 저장할 수 없습니다",
+ "seedAfter": "저장 후 시딩 시작",
+ "seedFailed": "시딩 작업을 시작할 수 없습니다.",
+ "seedSubmitted": "시딩 작업을 요청했습니다.",
+ "invalidOptions": "목록마다 유효한 URL을 최대 {{limit}}개 입력할 수 있습니다. 비공개 토렌트에는 트래커가 필요합니다.",
+ "menuLabel": "토렌트 파일 만들기…",
+ "downloadRequested": "다운로드 요청됨: {{path}}"
}
}
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index e642ffaf..79ac81e4 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -2850,7 +2850,7 @@
"title": "Denne torrenten finnes allerede"
},
"errors": {
- "headerNameRequired": "Angi et headernavn eller fjern denne headeren.",
+ "headerNameRequired": "Gi hvert hodefelt med en verdi et navn.",
"missingSource": "En torrentfil eller magnetlenke kreves",
"noFilesSelected": "Velg minst én fil",
"saveDirRequired": "Lagringsmappe kreves",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Opprett torrent",
+ "source": "Innhold som skal deles",
+ "options": "Torrentvalg",
+ "trackers": "Trackere",
+ "trackersPlaceholder": "Én announce-URL per linje",
+ "webSeeds": "Web-frø",
+ "webSeedsPlaceholder": "Én HTTP(S)-URL per linje (valgfritt)",
+ "comment": "Kommentar",
+ "private": "Privat torrent",
+ "privateDesc": "Slår av DHT og peer-utveksling; distribusjon kun via tracker.",
+ "pieceLength": "Stykkestørrelse",
+ "pieceAuto": "Automatisk",
+ "hashing": "Beregner sjekksummer…",
+ "resultName": "Navn",
+ "resultSize": "Størrelse",
+ "resultInfoHash": "Info-sjekksum",
+ "saveFile": "Lagre .torrent",
+ "create": "Opprett",
+ "savedToast": "Torrent lagret til {{path}}",
+ "createFailed": "Kunne ikke opprette torrenten",
+ "saveFailed": "Kunne ikke lagre torrentfilen",
+ "seedAfter": "Start seeding etter lagring",
+ "seedFailed": "Seedingen kunne ikke startes.",
+ "seedSubmitted": "Seedingoppgaven er sendt inn.",
+ "invalidOptions": "Hver liste kan ha opptil {{limit}} gyldige URL-er. Private torrenter trenger en tracker.",
+ "menuLabel": "Opprett torrentfil…",
+ "downloadRequested": "Nedlasting forespurt: {{path}}"
}
}
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index da60b5e5..cf592b06 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -2850,7 +2850,7 @@
"title": "Deze torrent bestaat al"
},
"errors": {
- "headerNameRequired": "Voer een headernaam in of verwijder deze header.",
+ "headerNameRequired": "Geef elke header met een waarde een naam.",
"missingSource": "Er is een torrentbestand of magnetlink nodig",
"noFilesSelected": "Selecteer minstens één bestand",
"saveDirRequired": "Er is een opslagmap nodig",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Torrent aanmaken",
+ "source": "Te delen inhoud",
+ "options": "Torrentopties",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Eén announce-URL per regel",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Eén HTTP(S)-URL per regel (optioneel)",
+ "comment": "Opmerking",
+ "private": "Privé-torrent",
+ "privateDesc": "Schakelt DHT en peer-uitwisseling uit; alleen via trackers.",
+ "pieceLength": "Piece-grootte",
+ "pieceAuto": "Automatisch",
+ "hashing": "Hashes worden berekend…",
+ "resultName": "Naam",
+ "resultSize": "Grootte",
+ "resultInfoHash": "Info-hash",
+ "saveFile": ".torrent opslaan",
+ "create": "Aanmaken",
+ "savedToast": "Torrent opgeslagen in {{path}}",
+ "createFailed": "Kan de torrent niet aanmaken",
+ "saveFailed": "Kan het torrent-bestand niet opslaan",
+ "seedAfter": "Begin met seeden na het opslaan",
+ "seedFailed": "Het seeden kon niet worden gestart.",
+ "seedSubmitted": "De seedtaak is ingediend.",
+ "invalidOptions": "Elke lijst kan maximaal {{limit}} geldige URL’s bevatten. Privétorrents hebben een tracker nodig.",
+ "menuLabel": "Torrentbestand maken…",
+ "downloadRequested": "Download aangevraagd: {{path}}"
}
}
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 50df33d9..ffd534ad 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1155,7 +1155,7 @@
"doc": "Dokument"
},
"errors": {
- "headerNameRequired": "Wprowadź nazwę nagłówka lub usuń ten nagłówek.",
+ "headerNameRequired": "Podaj nazwę każdego nagłówka z wartością.",
"urlsRequired": "Wymagany jest co najmniej jeden adres URL",
"saveDirRequired": "Wymagany jest folder zapisu",
"noFilesSelected": "Wybierz co najmniej jeden plik",
@@ -3564,5 +3564,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Utwórz torrent",
+ "source": "Zawartość do udostępnienia",
+ "options": "Opcje torrenta",
+ "trackers": "Trackery",
+ "trackersPlaceholder": "Jeden URL announce na wiersz",
+ "webSeeds": "Web seedy",
+ "webSeedsPlaceholder": "Jeden URL HTTP(S) na wiersz (opcjonalnie)",
+ "comment": "Komentarz",
+ "private": "Torrent prywatny",
+ "privateDesc": "Wyłącza DHT i wymianę peerów; dystrybucja tylko przez trackery.",
+ "pieceLength": "Rozmiar kawałka",
+ "pieceAuto": "Automatycznie",
+ "hashing": "Obliczanie skrótów…",
+ "resultName": "Nazwa",
+ "resultSize": "Rozmiar",
+ "resultInfoHash": "Skrót info",
+ "saveFile": "Zapisz .torrent",
+ "create": "Utwórz",
+ "savedToast": "Torrent zapisano w {{path}}",
+ "createFailed": "Nie udało się utworzyć torrenta",
+ "saveFailed": "Nie udało się zapisać pliku torrent",
+ "seedAfter": "Rozpocznij udostępnianie po zapisaniu",
+ "seedFailed": "Nie udało się rozpocząć udostępniania.",
+ "seedSubmitted": "Zlecono udostępnianie.",
+ "invalidOptions": "Każda lista może zawierać do {{limit}} poprawnych adresów URL. Prywatny torrent wymaga trackera.",
+ "menuLabel": "Utwórz plik torrent…",
+ "downloadRequested": "Zlecono pobranie: {{path}}"
}
}
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index cee47bb3..da43781a 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1142,7 +1142,7 @@
"doc": "Documento"
},
"errors": {
- "headerNameRequired": "Insira um nome para o cabeçalho ou remova-o.",
+ "headerNameRequired": "Dê um nome a cada cabeçalho que tenha um valor.",
"urlsRequired": "É necessário pelo menos um URL",
"saveDirRequired": "A pasta de destino é obrigatória",
"noFilesSelected": "Selecione pelo menos um arquivo",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Criar torrent",
+ "source": "Conteúdo para compartilhar",
+ "options": "Opções do torrent",
+ "trackers": "Trackers",
+ "trackersPlaceholder": "Uma URL announce por linha",
+ "webSeeds": "Web seeds",
+ "webSeedsPlaceholder": "Uma URL HTTP(S) por linha (opcional)",
+ "comment": "Comentário",
+ "private": "Torrent privado",
+ "privateDesc": "Desativa DHT e troca entre peers; distribuição só por tracker.",
+ "pieceLength": "Tamanho do pedaço",
+ "pieceAuto": "Automático",
+ "hashing": "Calculando hashes…",
+ "resultName": "Nome",
+ "resultSize": "Tamanho",
+ "resultInfoHash": "Hash de info",
+ "saveFile": "Salvar .torrent",
+ "create": "Criar",
+ "savedToast": "Torrent salvo em {{path}}",
+ "createFailed": "Não foi possível criar o torrent",
+ "saveFailed": "Não foi possível salvar o arquivo torrent",
+ "seedAfter": "Começar a semear após salvar",
+ "seedFailed": "Não foi possível iniciar a semeadura.",
+ "seedSubmitted": "A tarefa de semeadura foi enviada.",
+ "invalidOptions": "Cada lista aceita até {{limit}} URLs válidas. Torrents privados precisam de um rastreador.",
+ "menuLabel": "Criar arquivo torrent…",
+ "downloadRequested": "Download solicitado: {{path}}"
}
}
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 2c246159..62b12005 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -2870,7 +2870,7 @@
"title": "Acest torrent există deja"
},
"errors": {
- "headerNameRequired": "Introduceți un nume pentru antet sau eliminați acest antet.",
+ "headerNameRequired": "Introduceți un nume pentru fiecare antet care are o valoare.",
"missingSource": "Este necesar un fișier torrent sau un link magnet",
"noFilesSelected": "Selectează cel puțin un fișier",
"saveDirRequired": "Este necesar un dosar de salvare",
@@ -3540,5 +3540,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Creează torrent",
+ "source": "Conținut de partajat",
+ "options": "Opțiuni torrent",
+ "trackers": "Trackere",
+ "trackersPlaceholder": "Câte un URL announce pe linie",
+ "webSeeds": "Web seed-uri",
+ "webSeedsPlaceholder": "Câte un URL HTTP(S) pe linie (opțional)",
+ "comment": "Comentariu",
+ "private": "Torrent privat",
+ "privateDesc": "Dezactivează DHT și schimbul între peers; distribuire doar prin trackere.",
+ "pieceLength": "Mărimea piesei",
+ "pieceAuto": "Automat",
+ "hashing": "Se calculează amprentele…",
+ "resultName": "Nume",
+ "resultSize": "Dimensiune",
+ "resultInfoHash": "Hash info",
+ "saveFile": "Salvează .torrent",
+ "create": "Creează",
+ "savedToast": "Torrentul a fost salvat în {{path}}",
+ "createFailed": "Torrentul nu a putut fi creat",
+ "saveFailed": "Fișierul torrent nu a putut fi salvat",
+ "seedAfter": "Începe distribuirea după salvare",
+ "seedFailed": "Distribuirea nu a putut porni.",
+ "seedSubmitted": "Sarcina de distribuire a fost trimisă.",
+ "invalidOptions": "Fiecare listă acceptă până la {{limit}} URL-uri valide. Torrentele private necesită un tracker.",
+ "menuLabel": "Creează un fișier torrent…",
+ "downloadRequested": "Descărcare solicitată: {{path}}"
}
}
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 3350b6ed..68eb2ebd 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1155,7 +1155,7 @@
"doc": "Документ"
},
"errors": {
- "headerNameRequired": "Введите имя заголовка или удалите этот заголовок.",
+ "headerNameRequired": "Укажите имя каждого заголовка со значением.",
"urlsRequired": "Требуется хотя бы один URL",
"saveDirRequired": "Укажите папку сохранения",
"noFilesSelected": "Выберите хотя бы один файл",
@@ -3564,5 +3564,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Создать торрент",
+ "source": "Содержимое для раздачи",
+ "options": "Параметры торрента",
+ "trackers": "Трекеры",
+ "trackersPlaceholder": "По одному announce-URL в строке",
+ "webSeeds": "Web-сиды",
+ "webSeedsPlaceholder": "По одному HTTP(S)-URL в строке (необязательно)",
+ "comment": "Комментарий",
+ "private": "Приватный торрент",
+ "privateDesc": "Отключает DHT и обмен пирами; раздача только через трекер.",
+ "pieceLength": "Размер куска",
+ "pieceAuto": "Автоматически",
+ "hashing": "Вычисление хешей…",
+ "resultName": "Имя",
+ "resultSize": "Размер",
+ "resultInfoHash": "Info-хеш",
+ "saveFile": "Сохранить .torrent",
+ "create": "Создать",
+ "savedToast": "Торрент сохранён в {{path}}",
+ "createFailed": "Не удалось создать торрент",
+ "saveFailed": "Не удалось сохранить торрент-файл",
+ "seedAfter": "Начать раздачу после сохранения",
+ "seedFailed": "Не удалось начать раздачу.",
+ "seedSubmitted": "Задача раздачи отправлена.",
+ "invalidOptions": "В каждом списке допускается до {{limit}} корректных URL. Для приватного торрента нужен трекер.",
+ "menuLabel": "Создать торрент-файл…",
+ "downloadRequested": "Запрошено скачивание: {{path}}"
}
}
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 1d298c9e..8108a296 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -2830,7 +2830,7 @@
"title": "มีทอร์เรนต์นี้อยู่แล้ว"
},
"errors": {
- "headerNameRequired": "ป้อนชื่อส่วนหัวหรือลบส่วนหัวนี้",
+ "headerNameRequired": "ระบุชื่อให้ทุกส่วนหัวที่กรอกค่าไว้",
"missingSource": "ต้องมีไฟล์ทอร์เรนต์หรือลิงก์แมกเน็ต",
"noFilesSelected": "เลือกอย่างน้อยหนึ่งไฟล์",
"saveDirRequired": "ต้องระบุโฟลเดอร์บันทึก",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "สร้างไฟล์ทอร์เรนต์",
+ "source": "เนื้อหาที่จะแชร์",
+ "options": "ตัวเลือกทอร์เรนต์",
+ "trackers": "แทรกเกอร์",
+ "trackersPlaceholder": "หนึ่ง announce URL ต่อบรรทัด",
+ "webSeeds": "Web seed",
+ "webSeedsPlaceholder": "หนึ่ง URL HTTP(S) ต่อบรรทัด (ไม่บังคับ)",
+ "comment": "หมายเหตุ",
+ "private": "ทอร์เรนต์ส่วนตัว",
+ "privateDesc": "ปิด DHT และการแลกเปลี่ยน peer; แจกจ่ายผ่านแทรกเกอร์เท่านั้น",
+ "pieceLength": "ขนาดชิ้นข้อมูล",
+ "pieceAuto": "อัตโนมัติ",
+ "hashing": "กำลังคำนวณแฮช…",
+ "resultName": "ชื่อ",
+ "resultSize": "ขนาด",
+ "resultInfoHash": "แฮช info",
+ "saveFile": "บันทึก .torrent",
+ "create": "สร้าง",
+ "savedToast": "บันทึกทอร์เรนต์ไปที่ {{path}} แล้ว",
+ "createFailed": "สร้างทอร์เรนต์ไม่สำเร็จ",
+ "saveFailed": "บันทึกไฟล์ทอร์เรนต์ไม่สำเร็จ",
+ "seedAfter": "เริ่มซีดหลังจากบันทึก",
+ "seedFailed": "เริ่มซีดไม่ได้",
+ "seedSubmitted": "ส่งงานซีดแล้ว",
+ "invalidOptions": "แต่ละรายการมี URL ที่ถูกต้องได้สูงสุด {{limit}} รายการ ทอร์เรนต์ส่วนตัวต้องมีแทร็กเกอร์",
+ "menuLabel": "สร้างไฟล์ทอร์เรนต์…",
+ "downloadRequested": "ขอดาวน์โหลดแล้ว: {{path}}"
}
}
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index bca0e45b..10b56e26 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1129,7 +1129,7 @@
"doc": "Belge"
},
"errors": {
- "headerNameRequired": "Bir üstbilgi adı girin veya bu üstbilgiyi kaldırın.",
+ "headerNameRequired": "Değeri olan her üst bilgi için bir ad girin.",
"urlsRequired": "En az bir URL gerekli",
"saveDirRequired": "Kayıt klasörü gerekli",
"noFilesSelected": "En az bir dosya seçin",
@@ -3516,5 +3516,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Torrent oluştur",
+ "source": "Paylaşılacak içerik",
+ "options": "Torrent seçenekleri",
+ "trackers": "İzleyiciler",
+ "trackersPlaceholder": "Her satıra bir announce URL’si",
+ "webSeeds": "Web tohumları",
+ "webSeedsPlaceholder": "Her satıra bir HTTP(S) URL (isteğe bağlı)",
+ "comment": "Yorum",
+ "private": "Özel torrent",
+ "privateDesc": "DHT ve eş değişimi devre dışı; dağıtım yalnızca izleyiciyle.",
+ "pieceLength": "Parça boyutu",
+ "pieceAuto": "Otomatik",
+ "hashing": "Hash hesaplanıyor…",
+ "resultName": "Ad",
+ "resultSize": "Boyut",
+ "resultInfoHash": "Info hash",
+ "saveFile": ".torrent kaydet",
+ "create": "Oluştur",
+ "savedToast": "Torrent {{path}} konumuna kaydedildi",
+ "createFailed": "Torrent oluşturulamadı",
+ "saveFailed": "Torrent dosyası kaydedilemedi",
+ "seedAfter": "Kaydettikten sonra paylaşmaya başla",
+ "seedFailed": "Paylaşım başlatılamadı.",
+ "seedSubmitted": "Paylaşım görevi gönderildi.",
+ "invalidOptions": "Her liste en fazla {{limit}} geçerli URL içerebilir. Özel torrentler izleyici gerektirir.",
+ "menuLabel": "Torrent dosyası oluştur…",
+ "downloadRequested": "İndirme istendi: {{path}}"
}
}
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 973bdbb6..96522f71 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -2890,7 +2890,7 @@
"title": "Цей торрент уже існує"
},
"errors": {
- "headerNameRequired": "Введіть назву заголовка або видаліть цей заголовок.",
+ "headerNameRequired": "Укажіть назву кожного заголовка зі значенням.",
"missingSource": "Потрібен торрент-файл або magnet-посилання",
"noFilesSelected": "Виберіть принаймні один файл",
"saveDirRequired": "Потрібно вказати теку збереження",
@@ -3564,5 +3564,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Створити торрент",
+ "source": "Вміст для роздачі",
+ "options": "Параметри торента",
+ "trackers": "Трекери",
+ "trackersPlaceholder": "По одному announce-URL на рядок",
+ "webSeeds": "Web-сіди",
+ "webSeedsPlaceholder": "По одному HTTP(S)-URL на рядок (необов’язково)",
+ "comment": "Коментар",
+ "private": "Приватний торрент",
+ "privateDesc": "Вимикає DHT та обмін пирами; роздача лише через трекер.",
+ "pieceLength": "Розмір шматка",
+ "pieceAuto": "Автоматично",
+ "hashing": "Обчислення хешів…",
+ "resultName": "Назва",
+ "resultSize": "Розмір",
+ "resultInfoHash": "Info-хеш",
+ "saveFile": "Зберегти .torrent",
+ "create": "Створити",
+ "savedToast": "Торрент збережено у {{path}}",
+ "createFailed": "Не вдалося створити торрент",
+ "saveFailed": "Не вдалося зберегти торрент-файл",
+ "seedAfter": "Почати роздачу після збереження",
+ "seedFailed": "Не вдалося розпочати роздачу.",
+ "seedSubmitted": "Завдання роздачі надіслано.",
+ "invalidOptions": "У кожному списку дозволено до {{limit}} дійсних URL. Приватному торенту потрібен трекер.",
+ "menuLabel": "Створити торрент-файл…",
+ "downloadRequested": "Запит на завантаження: {{path}}"
}
}
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 56dd2aff..d0caac69 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1116,7 +1116,7 @@
"doc": "Tài liệu"
},
"errors": {
- "headerNameRequired": "Nhập tên tiêu đề hoặc xóa tiêu đề này.",
+ "headerNameRequired": "Nhập tên cho mỗi tiêu đề có giá trị.",
"urlsRequired": "Cần ít nhất một URL",
"saveDirRequired": "Cần chọn thư mục lưu",
"noFilesSelected": "Chọn ít nhất một tệp",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "Tạo torrent",
+ "source": "Nội dung chia sẻ",
+ "options": "Tùy chọn torrent",
+ "trackers": "Tracker",
+ "trackersPlaceholder": "Mỗi dòng một URL announce",
+ "webSeeds": "Web seed",
+ "webSeedsPlaceholder": "Mỗi dòng một URL HTTP(S) (tùy chọn)",
+ "comment": "Ghi chú",
+ "private": "Torrent riêng tư",
+ "privateDesc": "Tắt DHT và trao đổi peer; chỉ phát hành qua tracker.",
+ "pieceLength": "Kích thước mảnh",
+ "pieceAuto": "Tự động",
+ "hashing": "Đang tính hash…",
+ "resultName": "Tên",
+ "resultSize": "Kích thước",
+ "resultInfoHash": "Hash info",
+ "saveFile": "Lưu .torrent",
+ "create": "Tạo",
+ "savedToast": "Đã lưu torrent vào {{path}}",
+ "createFailed": "Không thể tạo torrent",
+ "saveFailed": "Không thể lưu tệp torrent",
+ "seedAfter": "Bắt đầu chia sẻ sau khi lưu",
+ "seedFailed": "Không thể bắt đầu chia sẻ.",
+ "seedSubmitted": "Đã gửi tác vụ chia sẻ.",
+ "invalidOptions": "Mỗi danh sách nhận tối đa {{limit}} URL hợp lệ. Torrent riêng tư cần có tracker.",
+ "menuLabel": "Tạo tệp torrent…",
+ "downloadRequested": "Đã yêu cầu tải xuống: {{path}}"
}
}
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 6dcccbdd..80305b95 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1116,7 +1116,7 @@
"doc": "文档"
},
"errors": {
- "headerNameRequired": "请输入请求头名称,或移除此请求头。",
+ "headerNameRequired": "请为已填写值的请求头补全名称。",
"urlsRequired": "至少需要一个 URL",
"saveDirRequired": "必须指定保存目录",
"noFilesSelected": "请至少选择一个文件",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "授权文件访问",
"confirmFile": "允许此操作读取以下文件?"
+ },
+ "createTorrent": {
+ "title": "创建种子",
+ "source": "共享内容",
+ "options": "种子选项",
+ "trackers": "Tracker 服务器",
+ "trackersPlaceholder": "每行一个 announce URL",
+ "webSeeds": "Web 种子",
+ "webSeedsPlaceholder": "每行一个 HTTP(S) URL(可选)",
+ "comment": "备注",
+ "private": "私有种子",
+ "privateDesc": "禁用 DHT 与节点交换,仅通过 Tracker 分发。",
+ "pieceLength": "分块大小",
+ "pieceAuto": "自动",
+ "hashing": "正在计算哈希…",
+ "resultName": "名称",
+ "resultSize": "大小",
+ "resultInfoHash": "Info 哈希",
+ "saveFile": "保存 .torrent",
+ "create": "创建",
+ "savedToast": "种子已保存到 {{path}}",
+ "createFailed": "创建种子失败",
+ "saveFailed": "保存种子文件失败",
+ "seedAfter": "保存后使用原文件做种",
+ "seedFailed": "无法启动做种任务。",
+ "seedSubmitted": "已提交做种任务。",
+ "invalidOptions": "每个列表最多 {{limit}} 个有效 URL。私有种子至少需要一个 Tracker。",
+ "menuLabel": "创建种子文件…",
+ "downloadRequested": "已请求下载 {{path}}"
}
}
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 0c5b8823..f3a16850 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1116,7 +1116,7 @@
"doc": "文件"
},
"errors": {
- "headerNameRequired": "請輸入標頭名稱,或移除此標頭。",
+ "headerNameRequired": "請為已填寫值的標頭補上名稱。",
"urlsRequired": "至少需要一個 URL",
"saveDirRequired": "必須指定儲存目錄",
"noFilesSelected": "至少選擇一個檔案",
@@ -3492,5 +3492,34 @@
},
"confirmFileTitle": "Authorize file access",
"confirmFile": "Allow this operation to read the following file?"
+ },
+ "createTorrent": {
+ "title": "建立種子",
+ "source": "分享內容",
+ "options": "種子選項",
+ "trackers": "Tracker 伺服器",
+ "trackersPlaceholder": "每行一個 announce URL",
+ "webSeeds": "Web 種子",
+ "webSeedsPlaceholder": "每行一個 HTTP(S) URL(可選)",
+ "comment": "備註",
+ "private": "私人種子",
+ "privateDesc": "停用 DHT 與節點交換,僅透過 Tracker 發布。",
+ "pieceLength": "分塊大小",
+ "pieceAuto": "自動",
+ "hashing": "正在計算雜湊…",
+ "resultName": "名稱",
+ "resultSize": "大小",
+ "resultInfoHash": "Info 雜湊",
+ "saveFile": "儲存 .torrent",
+ "create": "建立",
+ "savedToast": "種子已儲存到 {{path}}",
+ "createFailed": "建立種子失敗",
+ "saveFailed": "儲存種子檔案失敗",
+ "seedAfter": "儲存後使用原始檔案做種",
+ "seedFailed": "無法啟動做種任務。",
+ "seedSubmitted": "已提交做種任務。",
+ "invalidOptions": "每個清單最多 {{limit}} 個有效網址。私人種子至少需要一個 Tracker。",
+ "menuLabel": "建立種子檔案…",
+ "downloadRequested": "已要求下載 {{path}}"
}
}
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 5b0a9f7d..e1b7bace 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -115,6 +115,10 @@ export const Commands = {
RunNatDiagnostic: 'command:runNatDiagnostic',
ForceRemapNat: 'command:forceRemapNat',
ExportNatBundle: 'command:exportNatBundle',
+ // Desktop torrent creator
+ CreateTorrent: 'command:createTorrent',
+ PickTorrentSource: 'command:pickTorrentSource',
+ SaveTorrentFile: 'command:saveTorrentFile',
// App auto-update
CheckForUpdates: 'command:checkForUpdates',
DownloadUpdate: 'command:downloadUpdate',
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index 9aae437c..30245a1d 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -125,6 +125,8 @@ export const Events = {
// Payload: EngineCompatibilityWarningPayload. Internal shell signal; the
// resulting durable NotificationAdded event is what reaches renderers.
EngineCompatibilityWarning: 'event:engineCompatibilityWarning',
+ // A 0..1 fraction delivered only to the creator window that owns the operation.
+ CreateTorrentProgress: 'event:createTorrentProgress',
RendererTaskMenuRequested: 'event:rendererTaskMenuRequested',
ApplicationMenuChanged: 'event:applicationMenuChanged',
// No payload; only the main window's current Downloads list handles this.
diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.ts
index 2f48dec8..c744a26a 100644
--- a/src/shared/schemas/add-task.test.ts
+++ b/src/shared/schemas/add-task.test.ts
@@ -331,6 +331,39 @@ describe('formValuesToTaskCreateRequest', () => {
expect(req.uris).toEqual(['https://a/b', 'https://c/d'])
})
+ it('drops blank draft headers, preserves explicitly empty values and rejects value-only rows', () => {
+ const input = {
+ tab: 'links' as const,
+ urls: 'https://example.com/a',
+ saveDir: '/d',
+ extraHeaders: [
+ { name: ' ', value: ' ' },
+ { name: ' X-Empty ', value: '' },
+ { name: 'Accept', value: ' application/json ' },
+ ],
+ }
+ const req = formValuesToTaskCreateRequest(addTaskFormSchema.parse(input))
+ expect(req).toMatchObject({
+ headers: [
+ { name: 'X-Empty', value: '' },
+ { name: 'Accept', value: ' application/json ' },
+ ],
+ })
+ const invalid = addTaskFormSchema.safeParse({
+ ...input,
+ extraHeaders: [...input.extraHeaders, { name: ' ', value: 'present' }],
+ })
+ expect(invalid.success).toBe(false)
+ if (!invalid.success)
+ expect(invalid.error.issues[0].path).toEqual(['extraHeaders', 3, 'name'])
+ expect(
+ taskCreateRequestSchema.safeParse({
+ ...req,
+ headers: [{ name: '', value: '' }],
+ }).success
+ ).toBe(false)
+ })
+
it('builds headers from userAgent/referer/cookie/authorization', () => {
const req = formValuesToTaskCreateRequest({
tab: 'links',
diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.ts
index 4f75f72d..7908fb99 100644
--- a/src/shared/schemas/add-task.ts
+++ b/src/shared/schemas/add-task.ts
@@ -26,12 +26,20 @@ const httpHeaderSchema = z.object({
value: z.string(),
})
+// A blank optional form row is a draft, not an HTTP header.
+const extraHeaderDraftSchema = httpHeaderSchema
+ .extend({ name: z.string() })
+ .refine(({ name, value }) => !!name.trim() || !value.trim(), {
+ path: ['name'],
+ message: 'task.add.errors.headerNameRequired',
+ })
+
const linksTabSchema = z.object({
tab: z.literal('links'),
urls: z.string().min(1, { message: 'task.add.errors.urlsRequired' }),
saveDir: z.string().min(1, { message: 'task.add.errors.saveDirRequired' }),
filename: z.string().optional(),
- extraHeaders: z.array(httpHeaderSchema).optional(),
+ extraHeaders: z.array(extraHeaderDraftSchema).optional(),
split: z.number().int().min(1).max(128).optional(),
userAgent: z.string().optional(),
referer: z.string().optional(),
@@ -343,7 +351,10 @@ export function formValuesToTaskCreateRequest(
}
}
const headers = [
- ...(v.extraHeaders ?? []),
+ ...(v.extraHeaders ?? []).flatMap(({ name, value }) => {
+ const key = name.trim()
+ return key || value.trim() ? [{ name: key, value }] : []
+ }),
...compactHeader('User-Agent', v.userAgent),
...compactHeader('Referer', v.referer),
...compactHeader('Cookie', v.cookie),
diff --git a/src/shared/schemas/create-torrent.test.ts b/src/shared/schemas/create-torrent.test.ts
new file mode 100644
index 00000000..207df279
--- /dev/null
+++ b/src/shared/schemas/create-torrent.test.ts
@@ -0,0 +1,32 @@
+import { expect, it } from 'vitest'
+import { createTorrentRequestSchema } from './create-torrent'
+
+it.each(['trackers', 'webSeeds'] as const)(
+ 'preserves 64 URLs and rejects 65 instead of discarding %s',
+ (key) => {
+ const urls = Array.from(
+ { length: 64 },
+ (_, i) => `https://example.org/${i}`
+ )
+ expect(createTorrentRequestSchema.parse({ [key]: urls })[key]).toEqual(urls)
+ expect(
+ createTorrentRequestSchema.safeParse({ [key]: [...urls, urls[0]] })
+ .success
+ ).toBe(false)
+ }
+)
+it('requires a tracker for private torrents and HTTP(S) web seeds', () => {
+ expect(createTorrentRequestSchema.safeParse({ private: true }).success).toBe(
+ false
+ )
+ expect(
+ createTorrentRequestSchema.safeParse({
+ private: true,
+ trackers: ['udp://tracker.example:1337'],
+ }).success
+ ).toBe(true)
+ expect(
+ createTorrentRequestSchema.safeParse({ webSeeds: ['file:///etc/passwd'] })
+ .success
+ ).toBe(false)
+})
diff --git a/src/shared/schemas/create-torrent.ts b/src/shared/schemas/create-torrent.ts
new file mode 100644
index 00000000..27b30875
--- /dev/null
+++ b/src/shared/schemas/create-torrent.ts
@@ -0,0 +1,102 @@
+import { z } from 'zod'
+
+export const CREATE_TORRENT_URL_LIMIT = 64
+export const CREATE_TORRENT_COMMENT_MAX = 2048
+export const PIECE_LENGTH_MIN = 16 * 1024
+export const PIECE_LENGTH_MAX = 16 * 1024 * 1024
+export function isValidPieceLength(value: number): boolean {
+ return (
+ Number.isInteger(value) &&
+ value >= PIECE_LENGTH_MIN &&
+ value <= PIECE_LENGTH_MAX &&
+ (value & (value - 1)) === 0
+ )
+}
+
+const url = (protocols: string[]) =>
+ z
+ .string()
+ .max(2048)
+ .refine((value) => {
+ try {
+ const parsed = new URL(value)
+ return !!parsed.hostname && protocols.includes(parsed.protocol)
+ } catch {
+ return false
+ }
+ })
+export const trackerUrlSchema = url(['http:', 'https:', 'udp:'])
+export const webSeedUrlSchema = url(['http:', 'https:'])
+export const pickTorrentSourceSchema = z.enum(['file', 'directory'])
+export const createTorrentRequestSchema = z
+ .object({
+ trackers: z
+ .array(trackerUrlSchema)
+ .max(CREATE_TORRENT_URL_LIMIT)
+ .default([]),
+ webSeeds: z
+ .array(webSeedUrlSchema)
+ .max(CREATE_TORRENT_URL_LIMIT)
+ .default([]),
+ comment: z.string().max(CREATE_TORRENT_COMMENT_MAX).optional(),
+ private: z.boolean().default(false),
+ pieceLength: z.number().refine(isValidPieceLength).optional(),
+ })
+ .strict()
+ .refine((value) => !value.private || value.trackers.length > 0, {
+ path: ['trackers'],
+ })
+export const createTorrentResultSchema = z
+ .object({
+ id: z.string().uuid(),
+ infoHash: z.string().regex(/^[a-f0-9]{40}$/),
+ name: z.string().min(1),
+ totalSize: z.number().int().nonnegative(),
+ fileCount: z.number().int().positive(),
+ pieceCount: z.number().int().nonnegative(),
+ pieceLength: z.number().refine(isValidPieceLength),
+ })
+ .strict()
+export const saveTorrentFileRequestSchema = z
+ .object({
+ id: z.string().uuid(),
+ seed: z.boolean(),
+ })
+ .strict()
+export const saveTorrentFileResultSchema = z
+ .object({
+ path: z.string().min(1),
+ seeding: z.enum(['not-requested', 'submitted', 'failed']),
+ })
+ .strict()
+export const pickedTorrentSourceSchema = z.object({ path: z.string().min(1) })
+export const createTorrentProgressSchema = z.number().min(0).max(1)
+export type CreateTorrentRequest = z.infer<typeof createTorrentRequestSchema>
+export type CreateTorrentResultPayload = z.infer<
+ typeof createTorrentResultSchema
+>
+
+export const serverTorrentSourceSchema = z
+ .object({
+ path: z.string().min(1).max(4096),
+ kind: pickTorrentSourceSchema,
+ })
+ .strict()
+export const serverCreateTorrentSchema = z
+ .object({
+ source: serverTorrentSourceSchema,
+ options: createTorrentRequestSchema,
+ })
+ .strict()
+export const torrentJobSchema = z.object({ id: z.uuid() }).strict()
+export const torrentJobStatusSchema = z.discriminatedUnion('state', [
+ z.object({
+ state: z.literal('hashing'),
+ progress: createTorrentProgressSchema,
+ }),
+ z.object({ state: z.literal('ready'), result: createTorrentResultSchema }),
+ z.object({ state: z.literal('failed') }),
+])
+export const torrentExportSchema = z.object({ seed: z.boolean() }).strict()
+export const TORRENT_CREATOR_API = '/api/torrent-creator'
+export const TORRENT_SEED_HEADER = 'x-motrix-seeding'
diff --git a/src/shared/schemas/renderer-health.ts b/src/shared/schemas/renderer-health.ts
index ce2e987e..57d907d5 100644
--- a/src/shared/schemas/renderer-health.ts
+++ b/src/shared/schemas/renderer-health.ts
@@ -26,7 +26,7 @@ export const rendererRecoveryStringsSchema = z.object({
export const rendererSessionSchema = z.object({
generation: rendererGenerationSchema,
- windowId: z.enum(['main', 'add-task', 'onboarding']),
+ windowId: z.enum(['main', 'add-task', 'onboarding', 'create-torrent']),
route: z.string().max(2048).optional(),
recovered: z.boolean(),
submissionNeedsReview: z.boolean(),
diff --git a/src/shared/schemas/server-directory.ts b/src/shared/schemas/server-directory.ts
index 8a75789b..c972b9d3 100644
--- a/src/shared/schemas/server-directory.ts
+++ b/src/shared/schemas/server-directory.ts
@@ -78,7 +78,7 @@ export const ListServerDirectoriesResultSchema = z.discriminatedUnion('ok', [
DirectoryFailureSchema,
])
export const ValidateServerDirectoryRequestSchema = z
- .object({ path: DirectoryPathSchema })
+ .object({ path: DirectoryPathSchema, access: z.literal('read').optional() })
.strict()
export const ValidateServerDirectoryResultSchema = z.discriminatedUnion('ok', [
z
diff --git a/src/shared/types/window.ts b/src/shared/types/window.ts
index 0699ef27..6adb5e64 100644
--- a/src/shared/types/window.ts
+++ b/src/shared/types/window.ts
@@ -1,7 +1,8 @@
-export type WindowId = 'main' | 'add-task' | 'onboarding'
+export type WindowId = 'main' | 'add-task' | 'onboarding' | 'create-torrent'
export const WindowRoutes: Record<WindowId, string> = {
main: '?w=main',
'add-task': '?w=add-task',
+ 'create-torrent': '?w=create-torrent',
onboarding: '?w=onboarding',
} as const
diff --git a/tests/scripts/ensure-electron-runtime.test.ts b/tests/scripts/ensure-electron-runtime.test.ts
index 8fb58ef8..13191aea 100644
--- a/tests/scripts/ensure-electron-runtime.test.ts
+++ b/tests/scripts/ensure-electron-runtime.test.ts
@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// @ts-expect-error — .mjs without types
import {
ensureElectronRuntime,
+ ensureElectronRuntimeForCi,
inspectElectronRuntime,
} from '../../scripts/ensure-electron-runtime.mjs'
@@ -281,3 +282,78 @@ describe('ensureElectronRuntime', () => {
expect(inspectElectronRuntime(packageDir).complete).toBe(false)
})
})
+
+describe('CI runtime download recovery', () => {
+ const gateway =
+ 'HTTPError: Response code 504 (Gateway Timeout) for https://github.com/electron/electron/releases/download/test'
+ it('restores a partial install before retrying and validates the recovered runtime', async () => {
+ await mkdir(path.join(packageDir, 'dist'))
+ await writeFile(path.join(packageDir, 'dist', 'original'), 'keep')
+ const sleep = vi.fn(async () => {
+ expect(
+ await readFile(path.join(packageDir, 'dist', 'original'), 'utf8')
+ ).toBe('keep')
+ })
+ const spawn = vi
+ .fn()
+ .mockImplementationOnce(() => {
+ mkdirSync(path.join(packageDir, 'dist'))
+ writeFileSync(
+ path.join(packageDir, 'dist', 'partial'),
+ 'incomplete download'
+ )
+ return { status: 1, stderr: gateway }
+ })
+ .mockImplementationOnce(() => {
+ expect(existsSync(path.join(packageDir, 'dist', 'partial'))).toBe(false)
+ writeRuntimeSync()
+ return { status: 0 }
+ })
+ expect(
+ await ensureElectronRuntimeForCi({
+ electronPackageDir: packageDir,
+ spawn,
+ sleep,
+ log: vi.fn(),
+ logError: vi.fn(),
+ })
+ ).toBe(0)
+ expect(spawn).toHaveBeenCalledTimes(2)
+ expect(sleep).toHaveBeenCalledOnce()
+ expect(inspectElectronRuntime(packageDir).complete).toBe(true)
+ })
+ it.each([
+ 'HTTPError: Response code 404 (Not Found)',
+ 'Checksum mismatch',
+ 'ENOSPC: no space left on device',
+ ])('fails immediately on %s', async (stderr) => {
+ const spawn = vi.fn(() => ({ status: 7, stderr }))
+ const sleep = vi.fn()
+ expect(
+ await ensureElectronRuntimeForCi({
+ electronPackageDir: packageDir,
+ spawn,
+ sleep,
+ log: vi.fn(),
+ logError: vi.fn(),
+ })
+ ).toBe(7)
+ expect(spawn).toHaveBeenCalledOnce()
+ expect(sleep).not.toHaveBeenCalled()
+ })
+ it('returns the installer failure after bounded backoff', async () => {
+ const spawn = vi.fn(() => ({ status: 1, stderr: gateway }))
+ const sleep = vi.fn()
+ expect(
+ await ensureElectronRuntimeForCi({
+ electronPackageDir: packageDir,
+ spawn,
+ sleep,
+ log: vi.fn(),
+ logError: vi.fn(),
+ })
+ ).toBe(1)
+ expect(spawn).toHaveBeenCalledTimes(4)
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([5000, 15000, 30000])
+ })
+})
diff --git a/tests/scripts/vite-desktop-locales.test.ts b/tests/scripts/vite-app-locales.test.ts
similarity index 76%
rename from tests/scripts/vite-desktop-locales.test.ts
rename to tests/scripts/vite-app-locales.test.ts
index 82916b89..8c012e1e 100644
--- a/tests/scripts/vite-desktop-locales.test.ts
+++ b/tests/scripts/vite-app-locales.test.ts
@@ -1,11 +1,11 @@
import { readdirSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
-import { desktopLocaleProjection } from '../../scripts/vite-desktop-locales'
+import { appLocaleProjection } from '../../scripts/vite-app-locales'
describe('desktop main locale projection', () => {
const root = path.resolve(import.meta.dirname, '../../src/shared/locales')
- const plugin = desktopLocaleProjection(root)
+ const plugin = appLocaleProjection(root, 'main')
const transform = plugin.transform as (
source: string,
id: string
@@ -28,6 +28,7 @@ describe('desktop main locale projection', () => {
errors: original.task.storage.errors,
})
delete original.operatorAdmin
+ original.createTorrent = { menuLabel: original.createTorrent.menuLabel }
delete original.settings.integration.browser
delete original.task.add.duplicate
original.task.storage = {
@@ -48,6 +49,18 @@ describe('desktop main locale projection', () => {
}
})
+ it('keeps the full creator UI in both renderers without shipping CLI messages', () => {
+ const renderer = appLocaleProjection(root, 'renderer')
+ .transform as typeof transform
+ const file = path.join(root, 'en-US.json')
+ const source = readFileSync(file, 'utf8')
+ const projected = JSON.parse(renderer(source, file)!.code)
+ const original = JSON.parse(source)
+ delete original.operatorAdmin
+ expect(projected).toEqual(original)
+ expect(projected.createTorrent.seedAfter).toBeTruthy()
+ })
+
it('leaves unrelated JSON and scripts unchanged', () => {
expect(transform('{}', path.join(root, '../schemas/test.json'))).toBeNull()
expect(
@@ -56,8 +69,9 @@ describe('desktop main locale projection', () => {
})
it('recognizes Windows module paths with Vite query suffixes', () => {
- const windowsPlugin = desktopLocaleProjection(
- 'C:\\app\\src\\shared\\locales'
+ const windowsPlugin = appLocaleProjection(
+ 'C:\\app\\src\\shared\\locales',
+ 'main'
)
const windowsTransform = windowsPlugin.transform as typeof transform
expect(
diff --git a/vite.main.config.ts b/vite.main.config.ts
index c2d8fff8..a44c6af5 100644
--- a/vite.main.config.ts
+++ b/vite.main.config.ts
@@ -1,7 +1,7 @@
import { builtinModules, createRequire } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
-import { desktopLocaleProjection } from './scripts/vite-desktop-locales'
+import { appLocaleProjection } from './scripts/vite-app-locales'
import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const require = createRequire(import.meta.url)
@@ -55,8 +55,9 @@ function isExternal(id: string): boolean {
export default defineConfig({
publicDir: false,
plugins: [
- desktopLocaleProjection(
- path.resolve(import.meta.dirname, 'src/shared/locales')
+ appLocaleProjection(
+ path.resolve(import.meta.dirname, 'src/shared/locales'),
+ 'main'
),
],
build: {
diff --git a/vite.renderer.config.ts b/vite.renderer.config.ts
index 12bb640b..64b5134a 100644
--- a/vite.renderer.config.ts
+++ b/vite.renderer.config.ts
@@ -2,13 +2,20 @@ import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import packageJson from './package.json' with { type: 'json' }
+import { appLocaleProjection } from './scripts/vite-app-locales'
import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
export default defineConfig(({ command }) => ({
// Electron file:// + asar needs relative asset paths; the default
// '/' resolves to the filesystem root, not inside the asar.
base: './',
- plugins: [tailwindcss()],
+ plugins: [
+ tailwindcss(),
+ appLocaleProjection(
+ path.resolve(import.meta.dirname, 'src/shared/locales'),
+ 'renderer'
+ ),
+ ],
worker: { rollupOptions: { output: PRODUCTION_OUTPUT } },
define: {
__MOTRIX_TARGET__: JSON.stringify('electron'),
diff --git a/vite.renderer.web.config.ts b/vite.renderer.web.config.ts
index 3f9dec61..57d89b86 100644
--- a/vite.renderer.web.config.ts
+++ b/vite.renderer.web.config.ts
@@ -2,6 +2,7 @@ import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import packageJson from './package.json' with { type: 'json' }
+import { appLocaleProjection } from './scripts/vite-app-locales'
import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const fnos = process.env.MOTRIX_FNOS_BUILD === '1'
@@ -10,6 +11,10 @@ export default defineConfig({
base: './',
plugins: [
tailwindcss(),
+ appLocaleProjection(
+ path.resolve(import.meta.dirname, 'src/shared/locales'),
+ 'renderer'
+ ),
{
name: 'motrix-integration-marker',
transformIndexHtml: () => [