Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

feat: Telegram Saved Messages downloads (#127)

Shovith Debnathad83e8aa3e37
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index fbea467..f8fae4f 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -313,6 +313,7 @@ export class PlexoApp {
if (last?.status === 'completed') return last
if (entry.kind === 'http') return { ...entry, blocks: [], streams: [] }
if (entry.kind === 'nzb') return { ...entry, blocks: [], streams: [] }
+ if (entry.kind === 'telegram') return { ...entry, blocks: [], readers: [] }
return { ...entry, pieces: [], peers: [] }
})
// One that finished between the two calls is in both: history has its final state.
@@ -388,9 +389,12 @@ export class PlexoApp {
(network) => `${network.id}:${network.status}${network.error ? ` (${network.error})` : ''}`
)
const connections = state
- ? (state.kind === 'torrent' ? state.peers : state.streams).map(
- (connection) => `${connection.interfaceId}:${connection.status}`
- )
+ ? (state.kind === 'http' || state.kind === 'nzb'
+ ? state.streams
+ : state.kind === 'telegram'
+ ? state.readers
+ : state.peers
+ ).map((connection) => `${connection.interfaceId}:${connection.status}`)
: undefined
throw new Error(
`Timed out after ${timeout} ms waiting on the download. Last seen: ${
@@ -441,7 +445,10 @@ export function checkEvents(sessions: DownloadState[][]): void {
`${label}: as many work units as planned`
)
for (const unit of units) {
- const attributed = Object.values(unit.bytesByInterface).reduce((a, b) => a + b, 0)
+ const attributed = Object.values(unit.bytesByInterface).reduce(
+ (a: number, b: number) => a + b,
+ 0
+ )
assert.equal(
attributed,
unit.bytesDownloaded,
@@ -487,7 +494,7 @@ export function checkEvents(sessions: DownloadState[][]): void {
state.bytesUploaded,
`${label}: the networks' uploads add up to the download's`
)
- } else if (state.status === 'downloading') {
+ } else if (state.kind === 'http' && state.status === 'downloading') {
// A stream holds a block exactly while it is fetching it. A block has at most one stream
// fetching it for real from where it has got to, two racing that one as hedges, and any
// number fetching parts split off further on; it is in flight whenever the first is
diff --git a/e2e/telegram.spec.ts b/e2e/telegram.spec.ts
new file mode 100644
index 0000000..2a0b3b5
--- /dev/null
+++ b/e2e/telegram.spec.ts
@@ -0,0 +1,135 @@
+import { readdir, readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import type { TelegramMediaType } from '../src/shared/types'
+import { expect, test, type PlexoApp } from './fixtures'
+import { seededBytes } from './origin'
+
+// Downloading from Telegram: the service is the e2e double (PLEXO_E2E_TELEGRAM_FAKE=1), so
+// the real transfer, manager, queue and persistence run against a source that serves seeded
+// bytes and inflicts the DC's faults — a flood-wait, a stale file reference, per-region caps
+// on the request size, and a photo whose size only the download itself learns.
+
+const KB = 1024
+
+/** Reads the finished download from the destination and compares it byte for byte with the
+ * fake's seeded output — a halving or retry bug that wrote the right size in wrong places
+ * would fail here. The bytes match because the double's generator and `seededBytes` are the
+ * same xorshift from the same seed. */
+async function expectDownloadedBytes(
+ plexo: PlexoApp,
+ namePrefix: string,
+ size: number,
+ seed: number
+): Promise<void> {
+ const names = await readdir(plexo.dirs.dest)
+ const name = names.find((entry) => entry.startsWith(namePrefix))
+ expect(name, `${namePrefix} should be in the destination`).toBeDefined()
+ const actual = await readFile(join(plexo.dirs.dest, name!))
+ expect(
+ actual.equals(seededBytes(size, seed)),
+ `${namePrefix}'s bytes should match the fake's seeded output`
+ ).toBe(true)
+}
+
+test.use({
+ appEnv: {
+ PLEXO_E2E_TELEGRAM_FAKE: '1',
+ // 500ms a chunk: a 3 MiB file takes ~3s, leaving a solid window to pause it mid-flight.
+ PLEXO_E2E_TELEGRAM_DELAY_MS: '500'
+ }
+})
+
+async function startItem(
+ plexo: PlexoApp,
+ messageId: number,
+ mediaType: TelegramMediaType,
+ fileName: string,
+ totalBytes: number
+): Promise<string> {
+ return plexo.api.startDownload({
+ kind: 'telegram',
+ messageId,
+ mediaType,
+ url: `telegram://saved-messages/${messageId}`,
+ destinationDir: plexo.dirs.dest,
+ suggestedFileName: fileName,
+ totalBytes,
+ supportsRanges: true,
+ interfaceIds: (await plexo.api.listInterfaces()).map((iface) => iface.id),
+ etag: null,
+ lastModified: null
+ })
+}
+
+test.describe('Telegram Saved Messages downloads', () => {
+ test('signs in through the dialog, lists media, and downloads a video and a photo @smoke', async ({
+ plexo
+ }) => {
+ // The dialog saves where the app's destination setting says: point it at the test's folder
+ // and relaunch, so the files land where the byte check reads them.
+ await plexo.api.updateSettings({ destinationDir: plexo.dirs.dest })
+ await plexo.relaunch()
+
+ await plexo.page.getByRole('button', { name: 'Telegram' }).first().click()
+ await plexo.page.locator('#tg-api-id').fill('12345')
+ await plexo.page.locator('#tg-api-hash').fill('fake-hash')
+ await plexo.page.locator('#tg-phone').fill('+1 555 010 1234')
+ await plexo.page.getByRole('button', { name: 'Send code' }).click()
+
+ // Signed in: the media browser is there, the login form isn't.
+ const list = plexo.page.getByRole('group', { name: 'Saved Messages media' })
+ await list.waitFor()
+ await expect(plexo.page.locator('#tg-api-id')).toHaveCount(0)
+ await expect(list).toContainText('clip.mp4')
+ await expect(list).toContainText('shot.jpg')
+
+ await plexo.page.getByText('clip.mp4').click()
+ await plexo.page.getByText('shot.jpg').click()
+ await plexo.page.getByRole('button', { name: /Download 2/ }).click()
+
+ await expect
+ .poll(
+ async () => (await plexo.all()).filter((state) => state.status === 'completed').length,
+ {
+ timeout: 30_000
+ }
+ )
+ .toBe(2)
+ const finished = (await plexo.all()).filter((state) => state.status === 'completed')
+ // The video's size was known ahead; the photo's size only the download itself learned.
+ // (Completion order and name suffixes aren't: whichever finished first sorts first.)
+ const video = finished.find((state) => state.fileName.startsWith('clip'))
+ const photo = finished.find((state) => state.fileName.startsWith('shot'))
+ expect(video?.totalBytes).toBe(3 * KB * KB)
+ expect(photo?.totalBytes).toBe(2 * KB * KB)
+ // And the bytes are the fake's, in the right places.
+ await expectDownloadedBytes(plexo, 'clip', 3 * KB * KB, 11)
+ await expectDownloadedBytes(plexo, 'shot', 2 * KB * KB, 22)
+ })
+
+ test('a flaky file survives a flood-wait, a stale file reference and region caps', async ({
+ plexo
+ }) => {
+ const id = await startItem(plexo, 3, 'document', 'flaky.zip', 3 * KB * KB)
+ const done = await plexo.waitForStatus('completed', 30_000)
+ expect(done.id).toBe(id)
+ expect(done.totalBytes).toBe(3 * KB * KB)
+ await expectDownloadedBytes(plexo, 'flaky', 3 * KB * KB, 33)
+ })
+
+ test('a paused download resumes after a relaunch', async ({ plexo }) => {
+ const id = await startItem(plexo, 1, 'video', 'clip.mp4', 3 * KB * KB)
+ // Pause straight away: the chunks take 500ms each, so this lands mid-download.
+ await plexo.api.pauseDownload(id)
+ const paused = await plexo.waitForStatus('paused', 15_000)
+ expect(paused.id).toBe(id)
+
+ await plexo.relaunch()
+ const restored = (await plexo.all()).find((state) => state.id === id)
+ expect(restored?.status).toBe('paused')
+
+ await plexo.api.resumeDownload(id)
+ const done = await plexo.waitForStatus('completed', 30_000)
+ expect(done.id).toBe(id)
+ })
+})
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index 94aecdf..9115dd1 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -3,13 +3,24 @@ import { defineConfig } from 'electron-vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
+// Telegram API credentials bundled into release builds (see src/main/telegram/service.ts):
+// whoever cuts a release sets TELEGRAM_API_ID/HASH (CI secrets), so users sign in with just
+// their phone. Unset in dev builds — the app then asks for the user's own credentials.
+const telegramDefine = {
+ __PLEXO_TG_API_ID__: JSON.stringify(
+ process.env.TELEGRAM_API_ID ? Number(process.env.TELEGRAM_API_ID) : undefined
+ ),
+ __PLEXO_TG_API_HASH__: JSON.stringify(process.env.TELEGRAM_API_HASH || undefined)
+}
+
export default defineConfig({
main: {
resolve: {
alias: {
'@shared': resolve('src/shared')
}
- }
+ },
+ define: telegramDefine
},
preload: {
resolve: {
diff --git a/package-lock.json b/package-lock.json
index 84ee20f..2573bc6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,6 +12,7 @@
"@base-ui/react": "^1.8.0",
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
+ "big-integer": "1.6.52",
"bittorrent-peerid": "2.0.2",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
@@ -21,7 +22,9 @@
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
"parse-torrent": "11.0.24",
+ "qrcode": "^1.5.4",
"react-day-picker": "^10.0.2",
+ "telegram": "^2.26.22",
"webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
@@ -33,6 +36,7 @@
"@tailwindcss/vite": "^4.3.3",
"@types/chrome": "^0.3.4",
"@types/node": "^22.19.1",
+ "@types/qrcode": "^1.5.6",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
@@ -420,6 +424,12 @@
}
}
},
+ "node_modules/@cryptography/aes": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/@cryptography/aes/-/aes-0.1.1.tgz",
+ "integrity": "sha512-PcYz4FDGblO6tM2kSC+VzhhK62vml6k6/YAkiWtyPvrgJVfnDRoHGDtKn5UiaRRUrvUTTocBpvc2rRgTCqxjsg==",
+ "license": "GPL-3.0-or-later"
+ },
"node_modules/@date-fns/tz": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
@@ -2790,6 +2800,16 @@
"undici-types": "~6.21.0"
}
},
+ "node_modules/@types/qrcode": {
+ "version": "1.5.6",
+ "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
+ "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
@@ -3209,7 +3229,6 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3219,7 +3238,6 @@
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -3570,6 +3588,15 @@
"node": ">= 0.4"
}
},
+ "node_modules/async-mutex": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz",
+ "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.3.1"
+ }
+ },
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -3812,6 +3839,15 @@
"node": ">=12.20.0"
}
},
+ "node_modules/big-integer": {
+ "version": "1.6.52",
+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
+ "license": "Unlicense",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
"node_modules/bitfield": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/bitfield/-/bitfield-5.0.1.tgz",
@@ -4137,7 +4173,6 @@
"integrity": "sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==",
"hasInstallScript": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"node-gyp-build": "^4.3.0"
},
@@ -4317,6 +4352,15 @@
"node": ">=6"
}
},
+ "node_modules/camelcase": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
+ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/caniuse-lite": {
"version": "1.0.30001810",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz",
@@ -4518,7 +4562,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -4531,7 +4574,6 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
- "dev": true,
"license": "MIT"
},
"node_modules/combined-stream": {
@@ -4718,6 +4760,19 @@
"devOptional": true,
"license": "MIT"
},
+ "node_modules/d": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz",
+ "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==",
+ "license": "ISC",
+ "dependencies": {
+ "es5-ext": "^0.10.64",
+ "type": "^2.7.2"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
@@ -4808,6 +4863,15 @@
}
}
},
+ "node_modules/decamelize": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
+ "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
@@ -4936,6 +5000,12 @@
"license": "MIT",
"optional": true
},
+ "node_modules/dijkstrajs": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
+ "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
+ "license": "MIT"
+ },
"node_modules/dir-compare": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
@@ -5004,6 +5074,61 @@
"node": ">=0.10.0"
}
},
+ "node_modules/dom-serializer": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz",
+ "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==",
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.0.1",
+ "domhandler": "^4.2.0",
+ "entities": "^2.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/domhandler": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz",
+ "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.2.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "2.8.0",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",
+ "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^1.0.1",
+ "domelementtype": "^2.2.0",
+ "domhandler": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
@@ -5293,7 +5418,6 @@
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
- "dev": true,
"license": "MIT"
},
"node_modules/end-of-stream": {
@@ -5319,6 +5443,15 @@
"node": ">=10.13.0"
}
},
+ "node_modules/entities": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",
+ "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==",
+ "license": "BSD-2-Clause",
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/env-paths": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
@@ -5535,6 +5668,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/es5-ext": {
+ "version": "0.10.64",
+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz",
+ "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==",
+ "hasInstallScript": true,
+ "license": "ISC",
+ "dependencies": {
+ "es6-iterator": "^2.0.3",
+ "es6-symbol": "^3.1.3",
+ "esniff": "^2.0.1",
+ "next-tick": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
"node_modules/es6-error": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
@@ -5543,6 +5692,30 @@
"license": "MIT",
"optional": true
},
+ "node_modules/es6-iterator": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",
+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",
+ "license": "MIT",
+ "dependencies": {
+ "d": "1",
+ "es5-ext": "^0.10.35",
+ "es6-symbol": "^3.1.1"
+ }
+ },
+ "node_modules/es6-symbol": {
+ "version": "3.1.4",
+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz",
+ "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==",
+ "license": "ISC",
+ "dependencies": {
+ "d": "^1.0.2",
+ "ext": "^1.7.0"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@@ -5901,6 +6074,21 @@
"node": "*"
}
},
+ "node_modules/esniff": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz",
+ "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==",
+ "license": "ISC",
+ "dependencies": {
+ "d": "^1.0.1",
+ "es5-ext": "^0.10.62",
+ "event-emitter": "^0.3.5",
+ "type": "^2.7.2"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
"node_modules/espree": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
@@ -5965,6 +6153,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/event-emitter": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",
+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",
+ "license": "MIT",
+ "dependencies": {
+ "d": "1",
+ "es5-ext": "~0.10.14"
+ }
+ },
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
@@ -6034,6 +6232,15 @@
"dev": true,
"license": "Apache-2.0"
},
+ "node_modules/ext": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz",
+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",
+ "license": "ISC",
+ "dependencies": {
+ "type": "^2.7.2"
+ }
+ },
"node_modules/fast-check": {
"version": "4.10.1",
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.1.tgz",
@@ -6493,7 +6700,6 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
- "dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
@@ -6908,6 +7114,25 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/htmlparser2": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",
+ "integrity": "sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A==",
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.0.1",
+ "domhandler": "^4.0.0",
+ "domutils": "^2.5.2",
+ "entities": "^2.0.0"
+ }
+ },
"node_modules/http-cache-semantics": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",
@@ -7046,7 +7271,6 @@
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
"integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.8.19"
@@ -7331,7 +7555,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -7534,6 +7757,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-typedarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
+ "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",
+ "license": "MIT"
+ },
"node_modules/is-weakmap": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz",
@@ -8628,6 +8857,12 @@
"node": ">= 0.4.0"
}
},
+ "node_modules/next-tick": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz",
+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==",
+ "license": "ISC"
+ },
"node_modules/node-abi": {
"version": "4.37.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.37.0.tgz",
@@ -8777,7 +9012,6 @@
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
"integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
"license": "MIT",
- "optional": true,
"bin": {
"node-gyp-build": "bin.js",
"node-gyp-build-optional": "optional.js",
@@ -8830,6 +9064,18 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/node-localstorage": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-2.2.1.tgz",
+ "integrity": "sha512-vv8fJuOUCCvSPjDjBLlMqYMHob4aGjkmrkaE42/mZr0VT+ZAU10jRF8oTnX9+pgU9/vYJ8P7YT3Vd6ajkmzSCw==",
+ "license": "MIT",
+ "dependencies": {
+ "write-file-atomic": "^1.1.4"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/node-releases": {
"version": "2.0.55",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.55.tgz",
@@ -9124,6 +9370,31 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/p-try": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/pako": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
+ "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -9230,11 +9501,16 @@
"node": ">=10"
}
},
+ "node_modules/path-browserify": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
+ "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",
+ "license": "MIT"
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -9372,6 +9648,15 @@
"node": ">=10.4.0"
}
},
+ "node_modules/pngjs": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
+ "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@@ -9652,6 +9937,141 @@
"node": ">=16.0.0"
}
},
+ "node_modules/qrcode": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
+ "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
+ "license": "MIT",
+ "dependencies": {
+ "dijkstrajs": "^1.0.1",
+ "pngjs": "^5.0.0",
+ "yargs": "^15.3.1"
+ },
+ "bin": {
+ "qrcode": "bin/qrcode"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/qrcode/node_modules/cliui": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
+ "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^6.2.0"
+ }
+ },
+ "node_modules/qrcode/node_modules/find-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "license": "MIT",
+ "dependencies": {
+ "p-try": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/qrcode/node_modules/p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/wrap-ansi": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
+ "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/y18n": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
+ "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
+ "license": "ISC"
+ },
+ "node_modules/qrcode/node_modules/yargs": {
+ "version": "15.4.1",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
+ "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
+ "license": "MIT",
+ "dependencies": {
+ "cliui": "^6.0.0",
+ "decamelize": "^1.2.0",
+ "find-up": "^4.1.0",
+ "get-caller-file": "^2.0.1",
+ "require-directory": "^2.1.1",
+ "require-main-filename": "^2.0.0",
+ "set-blocking": "^2.0.0",
+ "string-width": "^4.2.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^18.1.2"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/yargs-parser": {
+ "version": "18.1.3",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
+ "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
+ "license": "ISC",
+ "dependencies": {
+ "camelcase": "^5.0.0",
+ "decamelize": "^1.2.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -9867,6 +10287,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/real-cancellable-promise": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/real-cancellable-promise/-/real-cancellable-promise-1.2.3.tgz",
+ "integrity": "sha512-hBI5Gy/55VEeeMtImMgEirD7eq5UmqJf1J8dFZtbJZA/3rB0pYFZ7PayMGueb6v4UtUtpKpP+05L0VwyE1hI9Q==",
+ "license": "MIT"
+ },
"node_modules/record-cache": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/record-cache/-/record-cache-1.2.0.tgz",
@@ -9937,7 +10363,6 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -9953,6 +10378,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/require-main-filename": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
+ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
+ "license": "ISC"
+ },
"node_modules/resedit": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",
@@ -10308,6 +10739,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/set-blocking": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
+ "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
+ "license": "ISC"
+ },
"node_modules/set-function-length": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
@@ -10541,6 +10978,15 @@
"node": ">=6"
}
},
+ "node_modules/slide": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz",
+ "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==",
+ "license": "ISC",
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/smart-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
@@ -10650,6 +11096,12 @@
"node": ">= 0.4"
}
},
+ "node_modules/store2": {
+ "version": "2.14.4",
+ "resolved": "https://registry.npmjs.org/store2/-/store2-2.14.4.tgz",
+ "integrity": "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw==",
+ "license": "MIT"
+ },
"node_modules/streamx": {
"version": "2.28.0",
"resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz",
@@ -10674,7 +11126,6 @@
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -10810,7 +11261,6 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -11003,6 +11453,83 @@
"streamx": "^2.12.5"
}
},
+ "node_modules/telegram": {
+ "version": "2.26.22",
+ "resolved": "https://registry.npmjs.org/telegram/-/telegram-2.26.22.tgz",
+ "integrity": "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg==",
+ "deprecated": "This package is archived and no longer maintained. Development continues in teleproto (https://npmjs.com/package/teleproto), a largely compatible, actively maintained fork. See the migration guide at https://docs.teleproto.dev/migrating-from-gramjs",
+ "license": "MIT",
+ "dependencies": {
+ "@cryptography/aes": "^0.1.1",
+ "async-mutex": "^0.3.0",
+ "big-integer": "^1.6.48",
+ "buffer": "^6.0.3",
+ "htmlparser2": "^6.1.0",
+ "mime": "^3.0.0",
+ "node-localstorage": "^2.2.1",
+ "pako": "^2.0.3",
+ "path-browserify": "^1.0.1",
+ "real-cancellable-promise": "^1.1.1",
+ "socks": "^2.6.2",
+ "store2": "^2.13.0",
+ "ts-custom-error": "^3.2.0",
+ "websocket": "^1.0.34"
+ },
+ "optionalDependencies": {
+ "bufferutil": "^4.0.3",
+ "utf-8-validate": "^5.0.5"
+ }
+ },
+ "node_modules/telegram/node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/telegram/node_modules/mime": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",
+ "license": "MIT",
+ "bin": {
+ "mime": "cli.js"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/telegram/node_modules/utf-8-validate": {
+ "version": "5.0.10",
+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",
+ "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=6.14.2"
+ }
+ },
"node_modules/temp": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",
@@ -11218,11 +11745,19 @@
"typescript": ">=4.8.4"
}
},
+ "node_modules/ts-custom-error": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",
+ "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
- "dev": true,
"license": "0BSD"
},
"node_modules/tunnel-agent": {
@@ -11237,6 +11772,12 @@
"node": "*"
}
},
+ "node_modules/type": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz",
+ "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==",
+ "license": "ISC"
+ },
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -11342,6 +11883,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/typedarray-to-buffer": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz",
+ "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==",
+ "license": "MIT",
+ "dependencies": {
+ "is-typedarray": "^1.0.0"
+ }
+ },
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -12237,6 +12787,51 @@
"node": ">=16.0.0"
}
},
+ "node_modules/websocket": {
+ "version": "1.0.35",
+ "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz",
+ "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bufferutil": "^4.0.1",
+ "debug": "^2.2.0",
+ "es5-ext": "^0.10.63",
+ "typedarray-to-buffer": "^3.1.5",
+ "utf-8-validate": "^5.0.2",
+ "yaeti": "^0.0.6"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/websocket/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/websocket/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "license": "MIT"
+ },
+ "node_modules/websocket/node_modules/utf-8-validate": {
+ "version": "5.0.10",
+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",
+ "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=6.14.2"
+ }
+ },
"node_modules/webtorrent": {
"version": "3.0.21",
"resolved": "https://registry.npmjs.org/webtorrent/-/webtorrent-3.0.21.tgz",
@@ -12399,6 +12994,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/which-module": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
+ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
+ "license": "ISC"
+ },
"node_modules/which-runtime": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/which-runtime/-/which-runtime-1.4.0.tgz",
@@ -12462,6 +13063,17 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
+ "node_modules/write-file-atomic": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz",
+ "integrity": "sha512-SdrHoC/yVBPpV0Xq/mUZQIpW2sWXAShb/V4pomcJXh92RuaO+f3UTWItiR3Px+pLnV2PvC2/bfn5cwr5X6Vfxw==",
+ "license": "ISC",
+ "dependencies": {
+ "graceful-fs": "^4.1.11",
+ "imurmurhash": "^0.1.4",
+ "slide": "^1.1.5"
+ }
+ },
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
@@ -12525,6 +13137,16 @@
"node": ">=10"
}
},
+ "node_modules/yaeti": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz",
+ "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==",
+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.32"
+ }
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
diff --git a/package.json b/package.json
index 071d63b..b545efa 100644
--- a/package.json
+++ b/package.json
@@ -32,6 +32,7 @@
"@base-ui/react": "^1.8.0",
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
+ "big-integer": "1.6.52",
"bittorrent-peerid": "2.0.2",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
@@ -41,7 +42,9 @@
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
"parse-torrent": "11.0.24",
+ "qrcode": "^1.5.4",
"react-day-picker": "^10.0.2",
+ "telegram": "^2.26.22",
"webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
@@ -53,6 +56,7 @@
"@tailwindcss/vite": "^4.3.3",
"@types/chrome": "^0.3.4",
"@types/node": "^22.19.1",
+ "@types/qrcode": "^1.5.6",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 3a90672..0f4eebd 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -32,7 +32,10 @@ import {
type StartDownloadRequest,
type StartHttpDownloadRequest,
type StartNzbDownloadRequest,
+ type StartTelegramDownloadRequest,
type StartTorrentDownloadRequest,
+ type TelegramDownloadNetwork,
+ type TelegramDownloadState,
type TorrentDownloadNetwork,
type TorrentDownloadState,
type TorrentFileEntry,
@@ -41,6 +44,7 @@ import {
} from '../../shared/types'
import { Limits } from '../network/limits'
import { loadSettings } from '../settings'
+import type { TelegramServiceApi } from '../telegram/service'
import { addToHistory, findInHistory, removeFromHistory } from './history'
import { testKnobs } from '../testKnobs'
import { DownloadFile } from './downloadFile'
@@ -61,6 +65,7 @@ import { browserContextFrom } from './browserContext'
import { describeTorrent, probedTorrentFile } from './torrent/metadata'
import { TorrentDestination } from './torrent/torrentDestination'
import { TorrentTransfer } from './torrent/torrentTransfer'
+import { TelegramTransfer } from './telegramTransfer'
import { NzbDestination } from './nzb/nzbDestination'
import {
parseNzb,
@@ -83,6 +88,7 @@ import {
type TransferHost,
type HttpTransferTarget,
type NzbTransferTarget,
+ type TelegramTransferTarget,
type TorrentTransferTarget
} from './transfer'
import type { NetworkMonitor } from '../network/interfaces'
@@ -138,12 +144,18 @@ interface TorrentDownloadRuntime extends RuntimeFields, TorrentTransferTarget {
transfer: TorrentTransfer
}
+interface TelegramDownloadRuntime extends RuntimeFields, TelegramTransferTarget {
+ kind: 'telegram'
+ transfer: TelegramTransfer
+}
+
interface NzbDownloadRuntime extends RuntimeFields, NzbTransferTarget {
kind: 'nzb'
transfer: NzbTransfer
}
-type DownloadRuntime = HttpDownloadRuntime | TorrentDownloadRuntime | NzbDownloadRuntime
+type DownloadRuntime =
+ HttpDownloadRuntime | TorrentDownloadRuntime | TelegramDownloadRuntime | NzbDownloadRuntime
interface PersistedDownloadBase {
savedAt: number
@@ -158,6 +170,7 @@ interface PersistedDownloadBase {
type PersistedState =
| Omit<HttpDownloadState, 'blocks' | 'streams'>
| Omit<TorrentDownloadState, 'pieces' | 'peers'>
+ | Omit<TelegramDownloadState, 'blocks' | 'readers'>
| Omit<NzbDownloadState, 'blocks' | 'streams'>
type PersistedDownload = PersistedDownloadBase & {
@@ -280,6 +293,16 @@ function newTorrentNetwork(iface: NetworkInterfaceInfo, enabled: boolean): Torre
}
}
+function newTelegramNetwork(
+ iface: NetworkInterfaceInfo,
+ enabled: boolean
+): TelegramDownloadNetwork {
+ return {
+ ...newHttpNetwork(iface, enabled),
+ transfer: 'telegram'
+ }
+}
+
/** A block that needs nothing more: in, skipped, or missing from the news server (see
* TorrentPieceStatus, NzbSegmentStatus). */
const isDone = (unit: DownloadUnitState): boolean =>
@@ -416,7 +439,8 @@ export class DownloadManager {
constructor(
private getWindow: () => BrowserWindow | null,
- private networks: NetworkMonitor
+ private networks: NetworkMonitor,
+ private readonly telegram: TelegramServiceApi
) {
this.initialization = Promise.all([this.restorePersistedDownloads(), this.limits.loaded]).then(
async () => {
@@ -703,6 +727,39 @@ export class DownloadManager {
return runtime
}
+ private newTelegramRuntime(
+ state: TelegramDownloadState,
+ requestPayload: StartTelegramDownloadRequest,
+ file: DownloadFile,
+ blocks: HttpBlockState[]
+ ): TelegramDownloadRuntime {
+ const target: TelegramTransferTarget = {
+ state,
+ requestPayload,
+ stop: new AbortController(),
+ file,
+ blocks,
+ meters: new Meters()
+ }
+ const host: TransferHost = {
+ networks: this.networks,
+ limits: this.limits,
+ downloadsOn: (networkId) => this.httpDownloadsOn(networkId),
+ reconcile: () => this.reconcile(runtime),
+ failDownload: (message, discard) => this.failDownload(runtime, message, discard),
+ failNetwork: (network, message) => this.failNetwork(runtime, network, message),
+ scheduleUpdate: () => this.scheduleUpdate(runtime),
+ getProxyForInterface: (networkId) => this.networkPreferences[networkId]?.proxy
+ }
+ const runtime: TelegramDownloadRuntime = Object.assign(target, this.runtimeFields(), {
+ kind: 'telegram' as const,
+ transfer: new TelegramTransfer(target, host, () =>
+ this.telegram.fileSource(requestPayload.messageId)
+ )
+ })
+ return runtime
+ }
+
private newNzbRuntime(
state: NzbDownloadState,
requestPayload: StartNzbDownloadRequest,
@@ -815,6 +872,11 @@ export class DownloadManager {
void omittedBlocks
void omittedStreams
entry = { ...state, unitsWritten: state.totalBlocks }
+ } else if (runtime.kind === 'telegram') {
+ const { blocks: omittedBlocks, readers: omittedReaders, ...state } = runtime.state
+ void omittedBlocks
+ void omittedReaders
+ entry = { ...state, unitsWritten: state.totalBlocks }
} else if (runtime.kind === 'nzb') {
const { blocks, streams: omittedStreams, ...state } = runtime.state
void omittedStreams
@@ -957,6 +1019,17 @@ export class DownloadManager {
new DownloadFile(persisted.partialPath),
blocks
)
+ } else if (persisted.state.kind === 'telegram' && requestPayload.kind === 'telegram') {
+ const old = persisted.state
+ const blocks = restoreBlocks(old, saved)
+ if (!blocks) return null
+ state = { ...old, readers: [], blocks, totalBlocks: blocks.length }
+ runtime = this.newTelegramRuntime(
+ state,
+ requestPayload,
+ new DownloadFile(persisted.partialPath),
+ blocks
+ )
} else {
return null
}
@@ -1052,6 +1125,10 @@ export class DownloadManager {
const { blocks, ...state } = runtime.state
return structuredClone({ seq: runtime.sentUpdates, state, blocks })
}
+ if (runtime.kind === 'telegram') {
+ const { blocks, ...state } = runtime.state
+ return structuredClone({ seq: runtime.sentUpdates, state, blocks })
+ }
if (runtime.kind === 'nzb') {
const { blocks, ...state } = runtime.state
return structuredClone({ seq: runtime.sentUpdates, state, blocks })
@@ -1124,6 +1201,43 @@ export class DownloadManager {
startedAt: Date.now()
}
runtime = this.newTorrentRuntime(state, requestPayload, file, pieces, torrentFile)
+ } else if (requestPayload.kind === 'telegram') {
+ // The dialog's idea of the file was a hint; Telegram's answer is the truth (a photo's
+ // size is 0: unknown until the download ends).
+ const info = await this.telegram.mediaInfo(requestPayload.messageId)
+ const totalBytes = info.totalBytes
+ const blockSizeBytes = 1024 * 1024
+ const blocks = planBlocks(totalBytes, blockSizeBytes)
+ await ensureDiskSpace(requestPayload.destinationDir, totalBytes)
+ const destinationPath = await reserveDestinationPath(
+ requestPayload.destinationDir,
+ requestPayload.suggestedFileName
+ )
+ const networks = available.map((iface) => newTelegramNetwork(iface, selected.includes(iface)))
+ const state: TelegramDownloadState = {
+ id,
+ kind: 'telegram',
+ url: requestPayload.url,
+ fileName: basename(destinationPath),
+ destinationPath,
+ totalBytes,
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ status: 'downloading',
+ networks,
+ readers: [],
+ peakReaders: 0,
+ blocks,
+ totalBlocks: blocks.length,
+ blockSizeBytes,
+ startedAt: Date.now()
+ }
+ runtime = this.newTelegramRuntime(
+ state,
+ requestPayload,
+ new DownloadFile(`${destinationPath}.plexo`),
+ blocks
+ )
} else if (requestPayload.kind === 'nzb') {
runtime = await this.startNzb(id, requestPayload, available, selected)
} else {
@@ -1285,7 +1399,7 @@ export class DownloadManager {
}
runtime.state.pausedAt = Date.now()
clearSpeeds(runtime.state)
- if (runtime.kind !== 'torrent') {
+ if (runtime.kind === 'http' || runtime.kind === 'nzb') {
for (const stream of runtime.state.streams) {
if (stream.status !== 'completed') {
stream.status = 'paused'
@@ -1295,6 +1409,14 @@ export class DownloadManager {
stream.split = undefined
}
}
+ if (runtime.kind === 'telegram') {
+ for (const reader of runtime.state.readers) {
+ if (reader.status !== 'completed') {
+ reader.status = 'paused'
+ }
+ reader.currentBlockIndex = undefined
+ }
+ }
for (const unit of unitsOf(runtime)) {
if (unit.status === 'downloading') {
unit.status = 'pending'
@@ -1524,13 +1646,20 @@ export class DownloadManager {
}
if (unit.kind === 'torrent') unit.provisionalBytes = 0
}
- if (runtime.kind !== 'torrent') {
+ if (runtime.kind === 'http' || runtime.kind === 'nzb') {
for (const stream of runtime.state.streams) {
if (stream.status !== 'completed') {
stream.status = 'pending'
}
stream.speedBytesPerSec = 0
}
+ } else if (runtime.kind === 'telegram') {
+ for (const reader of runtime.state.readers) {
+ if (reader.status !== 'completed') {
+ reader.status = 'pending'
+ }
+ reader.speedBytesPerSec = 0
+ }
} else {
runtime.state.peers.length = 0
}
@@ -1741,9 +1870,12 @@ export class DownloadManager {
await runtime.file.discard()
await this.removePersistedDownload(runtime, false)
runtime.state.status = 'cancelled'
- if (runtime.kind !== 'torrent') {
+ if (runtime.kind === 'http' || runtime.kind === 'nzb') {
for (const stream of runtime.state.streams) stream.status = 'cancelled'
}
+ if (runtime.kind === 'telegram') {
+ for (const reader of runtime.state.readers) reader.status = 'cancelled'
+ }
this.pushUpdate(runtime, false)
} catch (error) {
runtime.removed = false
@@ -2037,7 +2169,7 @@ export class DownloadManager {
// Until the monitor has looked, nothing is known to be gone.
const known = present !== null
if (known) {
- if (state.kind !== 'torrent') {
+ if (state.kind === 'http' || state.kind === 'nzb') {
state.networks = state.networks.filter(
(network) =>
network.enabled ||
@@ -2045,6 +2177,14 @@ export class DownloadManager {
present.some((iface) => iface.id === network.id) ||
state.streams.some((stream) => stream.interfaceId === network.id)
)
+ } else if (state.kind === 'telegram') {
+ state.networks = state.networks.filter(
+ (network) =>
+ network.enabled ||
+ network.bytesDownloaded > 0 ||
+ present.some((iface) => iface.id === network.id) ||
+ state.readers.some((reader) => reader.interfaceId === network.id)
+ )
} else {
state.networks = state.networks.filter(
(network) =>
@@ -2057,8 +2197,11 @@ export class DownloadManager {
}
for (const iface of present) {
if (!state.networks.some((network) => network.id === iface.id)) {
- if (state.kind !== 'torrent') state.networks.push(newHttpNetwork(iface, false))
- else state.networks.push(newTorrentNetwork(iface, false))
+ if (state.kind === 'http' || state.kind === 'nzb') {
+ state.networks.push(newHttpNetwork(iface, false))
+ } else if (state.kind === 'telegram') {
+ state.networks.push(newTelegramNetwork(iface, false))
+ } else state.networks.push(newTorrentNetwork(iface, false))
}
}
}
@@ -2183,6 +2326,12 @@ export class DownloadManager {
void omittedBlocks
return structuredClone({ seq: ++runtime.sentUpdates, state, blocks: changed })
}
+ if (runtime.kind === 'telegram') {
+ const changed = this.changedUnits(runtime, runtime.blocks)
+ const { blocks: omittedBlocks, ...state } = runtime.state
+ void omittedBlocks
+ return structuredClone({ seq: ++runtime.sentUpdates, state, blocks: changed })
+ }
if (runtime.kind === 'nzb') {
const changed = this.changedUnits(runtime, runtime.blocks)
const { blocks: omittedBlocks, ...state } = runtime.state
@@ -2259,6 +2408,11 @@ export class DownloadManager {
void omittedBlocks
void omittedStreams
state = rest
+ } else if (runtime.kind === 'telegram') {
+ const { blocks: omittedBlocks, readers: omittedReaders, ...rest } = runtime.state
+ void omittedBlocks
+ void omittedReaders
+ state = rest
} else if (runtime.kind === 'nzb') {
const { blocks, streams: omittedStreams, ...rest } = runtime.state
void omittedStreams
diff --git a/src/main/download/history.ts b/src/main/download/history.ts
index 8ee2845..35cc026 100644
--- a/src/main/download/history.ts
+++ b/src/main/download/history.ts
@@ -24,7 +24,10 @@ function isEntry(value: unknown): value is FinishedDownload {
if (!isRecord(value)) return false
return (
typeof value.id === 'string' &&
- (value.kind === 'http' || value.kind === 'torrent' || value.kind === 'nzb') &&
+ (value.kind === 'http' ||
+ value.kind === 'torrent' ||
+ value.kind === 'telegram' ||
+ value.kind === 'nzb') &&
typeof value.url === 'string' &&
typeof value.fileName === 'string' &&
typeof value.destinationPath === 'string' &&
diff --git a/src/main/download/telegramTransfer.ts b/src/main/download/telegramTransfer.ts
new file mode 100644
index 0000000..105a023
--- /dev/null
+++ b/src/main/download/telegramTransfer.ts
@@ -0,0 +1,505 @@
+import type {
+ DownloadStatus,
+ HttpBlockState,
+ StartTelegramDownloadRequest,
+ TelegramDownloadNetwork,
+ TelegramReaderState
+} from '../../shared/types'
+import { describeError } from '../../shared/errors'
+import { advanceBlock } from './blockProgress'
+import {
+ delay,
+ recomputeAggregates,
+ type Transfer,
+ type TransferHost,
+ type TelegramTransferTarget
+} from './transfer'
+
+/**
+ * Where a Telegram file's bytes come from: the telegram module's client, speaking MTProto. One
+ * request asks for up to 1 MiB at a 4096-aligned offset — upload.GetFile's own shape — and an
+ * empty answer means the end of the file (only a photo's download runs to one: Telegram doesn't
+ * say a photo's size ahead of time).
+ */
+export interface TelegramFileSource {
+ /** True when the size is unknown (a photo): requests run until an empty answer. */
+ unknownSize: boolean
+ request(offset: number, limit: number, signal: AbortSignal): Promise<Buffer>
+ /** The file's reference went stale (Telegram expires them within a day): find the file
+ * again, so the next request carries a fresh one. */
+ refresh(): Promise<void>
+ /** Closes the connections this source opened. Best-effort; safe to repeat. */
+ dispose(): Promise<void>
+}
+
+/** Why a request failed, as the transfer acts on it. */
+export type TelegramFileErrorKind = 'rate' | 'network' | 'auth' | 'missing' | 'other'
+
+export class TelegramFileError extends Error {
+ constructor(
+ readonly kind: TelegramFileErrorKind,
+ message: string,
+ /** For 'rate': how long Telegram asked to be left alone, in seconds. */
+ readonly waitSeconds?: number
+ ) {
+ super(message)
+ }
+}
+
+/** upload.GetFile answers at most 1 MiB, at offsets and limits divisible by 4096 — and
+ * sometimes less, capped per region of the file, so the size adapts (see asOutcome). */
+export const FILE_CHUNK_BYTES = 1024 * 1024
+/** Readers, each holding one dedicated connection to Telegram's DC under the same login —
+ * the shape of a fast download in Telegram's own desktop client. */
+export const READER_POOL = 8
+const MAX_RETRIES = 8
+const RETRY_BASE_MS = 1_000
+const RETRY_MAX_MS = 15_000
+/** A rate-limit wait longer than this ends the download (resumable) rather than holding it. */
+const RATE_WAIT_MAX_MS = 120_000
+/** The most times a download re-locates its file over stale references. */
+const MAX_REFERENCE_REFRESHES = 5
+
+interface ReaderRuntime {
+ id: number
+ controller: AbortController
+ /** Cuts its waits short when the run stops. */
+ wait: AbortSignal
+ failures: number
+}
+
+type BlockOutcome =
+ | { type: 'completed' }
+ | { type: 'stopped' }
+ | { type: 'retry'; waitMs: number }
+ | { type: 'give-up'; error: unknown }
+
+/** A chunk request already in flight, settled with an Error rather than rejecting, so a
+ * prefetch outliving its reader can never be an unhandled rejection. */
+interface Prefetch {
+ block: HttpBlockState
+ /** The file offset this request asks for. */
+ offset: number
+ promise: Promise<Buffer | Error>
+}
+
+/**
+ * Fetches a Telegram file: a pool of readers, each on its own connection to the file's data
+ * center, claiming pending blocks and keeping its connection full — the next chunk request
+ * goes out before the current one is written. Chunks land at their own offsets in the staging
+ * file, the same shape the HTTP transfer writes, so pause/resume, progress and the block grid
+ * all work unchanged. Telegram is reached however the OS routes, so a reader's bytes are
+ * attributed to whichever network was first-enabled when it claimed its block.
+ */
+export class TelegramTransfer implements Transfer {
+ private workers = new Map<number, Promise<void>>()
+ private readers = new Map<number, ReaderRuntime>()
+ private readerIds = 0
+ private stopped = false
+ /** The file source (a promise: it may need a round trip to Telegram to find the file). */
+ private sourcePromise: Promise<TelegramFileSource> | undefined
+ /** Until when Telegram asked every connection to slow down (see asOutcome). */
+ private rateLimitedUntil = 0
+ /** The biggest chunk Telegram will answer for this file right now. It varies by region of
+ * the file (measured: 512 KiB fine at one offset, capped at 64 KiB a megabyte later), so it
+ * starts at the full chunk and halves on LIMIT_INVALID (see asOutcome). */
+ private maxChunkBytes = FILE_CHUNK_BYTES
+ /** When the cap last came down: concurrent failures share one halving (see asOutcome). */
+ private lastHalveAt = 0
+ /** How many times the file was re-located over stale references. */
+ private refreshes = 0
+
+ constructor(
+ private readonly runtime: TelegramTransferTarget,
+ private readonly host: TransferHost,
+ private readonly makeSource: () => Promise<TelegramFileSource> | TelegramFileSource
+ ) {}
+
+ private source(): Promise<TelegramFileSource> {
+ this.sourcePromise ??= Promise.resolve(this.makeSource())
+ return this.sourcePromise
+ }
+
+ /** Closes the source's connections and forgets it, so the next run builds a fresh one
+ * (whose message lookup also refreshes a stale file reference). */
+ private async disposeSource(): Promise<void> {
+ const promise = this.sourcePromise
+ this.sourcePromise = undefined
+ if (!promise) return
+ try {
+ const source = await promise
+ await source.dispose()
+ } catch {
+ // Best-effort: the source may itself have failed to open.
+ }
+ }
+
+ reconcile(): void {
+ if (this.stopped) return
+ const { state } = this.runtime
+ // A photo's size is unknown, so its one block runs sequentially; everything else splits
+ // across the pool.
+ const desired = photoDownload(this.runtime.requestPayload)
+ ? 1
+ : Math.max(
+ 1,
+ Math.min(READER_POOL, state.blocks.filter((block) => block.status !== 'completed').length)
+ )
+ while (this.workers.size < desired && this.readers.size < desired) {
+ this.addReader()
+ }
+ }
+
+ tick(): void {
+ // The manager's reconcile runs from here each tick as it does for HTTP, so a network
+ // turned off, a limit reached or a schedule window closing is noticed mid-run.
+ this.host.reconcile()
+ }
+
+ running(): Iterable<Promise<void>> {
+ return this.workers.values()
+ }
+
+ abort(): void {
+ this.stopped = true
+ for (const reader of this.readers.values()) reader.controller.abort()
+ void this.disposeSource()
+ }
+
+ reset(): void {
+ // A new run starts its pool over: fresh connections and a fresh message lookup; blocks
+ // keep what they have on disk.
+ for (const reader of this.readers.values()) reader.controller.abort()
+ this.readers.clear()
+ this.workers.clear()
+ this.stopped = false
+ this.rateLimitedUntil = 0
+ this.maxChunkBytes = FILE_CHUNK_BYTES
+ this.lastHalveAt = 0
+ this.refreshes = 0
+ void this.disposeSource()
+ }
+
+ wake(): void {
+ // Nothing of this transfer's waits on a backoff that a network change should cut short:
+ // the readers retry on their own.
+ }
+
+ systemResumed(): void {
+ // The sockets under the session are likely dead, though nothing says so until a request
+ // fails; dropping the in-flight ones makes that happen now rather than after a stall.
+ for (const reader of this.readers.values()) reader.controller.abort()
+ this.readers.clear()
+ this.workers.clear()
+ this.stopped = false
+ void this.disposeSource()
+ }
+
+ private addReader(): void {
+ const { state } = this.runtime
+ const controller = new AbortController()
+ const reader: TelegramReaderState = {
+ id: ++this.readerIds,
+ interfaceId: state.networks.find((network) => network.enabled)?.id ?? '',
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ status: 'pending'
+ }
+ state.readers.push(reader)
+ state.peakReaders = Math.max(state.peakReaders, state.readers.length)
+ const self: ReaderRuntime = {
+ id: reader.id,
+ controller,
+ wait: AbortSignal.any([controller.signal, this.runtime.stop.signal]),
+ failures: 0
+ }
+ this.readers.set(reader.id, self)
+ this.workers.set(
+ reader.id,
+ this.runReader(reader, self).finally(() => {
+ this.workers.delete(reader.id)
+ this.readers.delete(reader.id)
+ const index = state.readers.indexOf(reader)
+ if (index >= 0) state.readers.splice(index, 1)
+ if (this.workers.size === 0) void this.disposeSource()
+ this.host.scheduleUpdate()
+ })
+ )
+ }
+
+ private networkOf(reader: TelegramReaderState): TelegramDownloadNetwork | undefined {
+ const { state } = this.runtime
+ const network =
+ state.networks.find((entry) => entry.id === reader.interfaceId && entry.enabled) ??
+ state.networks.find((entry) => entry.enabled)
+ return network
+ }
+
+ /** Claims the first pending block for `reader`, synchronously — no other reader can take
+ * it between the find and here. */
+ private claimBlock(reader: TelegramReaderState): HttpBlockState | undefined {
+ const block = this.runtime.blocks.find((entry) => entry.status === 'pending')
+ if (!block) return undefined
+ block.status = 'downloading'
+ reader.interfaceId = this.networkOf(reader)?.id ?? reader.interfaceId
+ block.interfaceId = reader.interfaceId
+ reader.currentBlockIndex = block.index
+ reader.status = 'downloading'
+ this.host.scheduleUpdate()
+ return block
+ }
+
+ private async runReader(reader: TelegramReaderState, self: ReaderRuntime): Promise<void> {
+ const { state } = this.runtime
+ let source: TelegramFileSource
+ try {
+ source = await this.source()
+ } catch (cause) {
+ this.host.failDownload(describeError(cause))
+ reader.status = 'cancelled'
+ return
+ }
+
+ while (state.status === 'downloading' && !self.controller.signal.aborted) {
+ // Telegram asked everyone to slow down: every reader waits out the remainder.
+ const rateWaitMs = this.rateLimitedUntil - Date.now()
+ if (rateWaitMs > 0) {
+ reader.status = 'retrying'
+ await delay(rateWaitMs, self.wait)
+ if ((this.runtime.state.status as DownloadStatus) !== 'downloading') break
+ continue
+ }
+ if (!this.networkOf(reader)) {
+ // No network is enabled right now: the manager pauses the download for this (see
+ // reconcile), and the reader waits rather than spins.
+ reader.status = 'pending'
+ await delay(250, self.wait)
+ continue
+ }
+
+ const block = this.claimBlock(reader)
+ if (!block) {
+ if (this.runtime.blocks.some((entry) => entry.status === 'downloading')) {
+ // Stay available: a block in flight may be handed back by its reader failing.
+ reader.status = 'pending'
+ await delay(250, self.wait)
+ continue
+ }
+ reader.status = 'completed'
+ reader.currentBlockIndex = undefined
+ break
+ }
+
+ const outcome = await this.runBlockStreamed(reader, self, block, source)
+ if (outcome.type === 'completed') {
+ self.failures = 0
+ continue
+ }
+ if (outcome.type === 'stopped') {
+ reader.status = (state.status as DownloadStatus) === 'paused' ? 'paused' : 'cancelled'
+ reader.currentBlockIndex = undefined
+ break
+ }
+ if (outcome.type === 'retry') {
+ reader.status = 'retrying'
+ this.host.scheduleUpdate()
+ await delay(outcome.waitMs, self.wait)
+ if ((this.runtime.state.status as DownloadStatus) !== 'downloading') {
+ reader.status =
+ (this.runtime.state.status as DownloadStatus) === 'paused' ? 'paused' : 'cancelled'
+ reader.currentBlockIndex = undefined
+ break
+ }
+ continue
+ }
+ // give-up: the reader is done, and the download fails with it.
+ this.host.failDownload(describeError(outcome.error))
+ reader.status = 'cancelled'
+ reader.currentBlockIndex = undefined
+ break
+ }
+ }
+
+ /** Returns a block to the pool, keeping what was written of it. */
+ private handBack(block: HttpBlockState): void {
+ if (block.status === 'downloading') block.status = 'pending'
+ }
+
+ /** The request size for a chunk at `offset` within `block`: 1 MiB mid-file, over-asked up
+ * to the 4096 alignment for a tail smaller than that (the answer is sliced down). */
+ private chunkSize(block: HttpBlockState, offset: number): number {
+ const end = block.rangeEnd === null ? Number.MAX_SAFE_INTEGER : block.rangeEnd + 1
+ const request = Math.min(this.maxChunkBytes, end - offset)
+ const aligned = Math.floor(request / 4096) * 4096
+ return aligned > 0 ? aligned : 4096
+ }
+
+ /**
+ * Fetches `firstBlock` with its connection kept full: the moment a chunk lands, the next
+ * request goes out — for the same block when it runs long, else for the next pending
+ * block, claimed then — and only then is the landed chunk written. The round trip of the
+ * next chunk thus hides behind this one's disk write. All blocks this stream claims are
+ * this function's to hand back when it stops early.
+ */
+ private async runBlockStreamed(
+ reader: TelegramReaderState,
+ self: ReaderRuntime,
+ firstBlock: HttpBlockState,
+ source: TelegramFileSource
+ ): Promise<BlockOutcome> {
+ const { state, meters } = this.runtime
+ const networkId = reader.interfaceId
+ const endOf = (block: HttpBlockState): number =>
+ block.rangeEnd === null ? Number.MAX_SAFE_INTEGER : block.rangeEnd + 1
+
+ const fire = (block: HttpBlockState, offset: number): Prefetch => ({
+ block,
+ offset,
+ promise: source
+ .request(offset, this.chunkSize(block, offset), self.controller.signal)
+ .catch((error: unknown) => (error instanceof Error ? error : new Error(String(error))))
+ })
+
+ let prefetch: Prefetch = fire(firstBlock, firstBlock.rangeStart + firstBlock.bytesDownloaded)
+
+ while (true) {
+ const { block, offset } = prefetch
+ const settled = await prefetch.promise
+ if (settled instanceof Error) {
+ this.handBack(block)
+ if (self.controller.signal.aborted || (state.status as DownloadStatus) !== 'downloading') {
+ return { type: 'stopped' }
+ }
+ const code = (settled as { errorMessage?: string }).errorMessage ?? settled.message ?? ''
+ if (/FILE_REFERENCE/.test(code) && this.refreshes < MAX_REFERENCE_REFRESHES) {
+ // The file's reference expired — Telegram's do, within a day: find the file again
+ // and take the block at the fresh reference.
+ this.refreshes += 1
+ await source.refresh()
+ return { type: 'retry', waitMs: 50 }
+ }
+ return this.asOutcome(self, settled)
+ }
+ if (settled.length === 0) {
+ if (block.rangeEnd !== null) {
+ this.handBack(block)
+ return {
+ type: 'give-up',
+ error: new Error('Telegram closed this file early — resume to try again.')
+ }
+ }
+ // The end of the photo: its size is known now, and the block with it.
+ state.totalBytes = offset
+ advanceBlock(block, networkId, offset - block.rangeStart)
+ block.status = 'completed'
+ recomputeAggregates(state, this.runtime.blocks)
+ this.host.scheduleUpdate()
+ return { type: 'completed' }
+ }
+
+ const remaining = endOf(block) - offset
+ const usable = Math.min(settled.length, remaining)
+ const nextOffset = offset + usable
+ const blockFinished = nextOffset >= endOf(block)
+
+ // Claim and fire the next chunk before writing this one.
+ let next: Prefetch | undefined
+ if ((state.status as DownloadStatus) === 'downloading' && !self.controller.signal.aborted) {
+ if (!blockFinished) {
+ next = fire(block, nextOffset)
+ } else {
+ const claimed = this.claimBlock(reader)
+ if (claimed) next = fire(claimed, claimed.rangeStart + claimed.bytesDownloaded)
+ }
+ }
+
+ try {
+ await this.host.limits.take(networkId, usable)
+ await this.write(offset, settled.subarray(0, usable))
+ } catch (error) {
+ // The write side (a full disk, a dropped drive) isn't Telegram's doing: end the
+ // download with what it says, keeping the download resumable.
+ if (next) await next.promise
+ this.handBack(block)
+ if (next && next.block !== block) this.handBack(next.block)
+ this.host.failDownload(describeError(error))
+ return { type: 'stopped' }
+ }
+
+ const gained = advanceBlock(block, networkId, nextOffset - block.rangeStart)
+ if (gained > 0) {
+ state.bytesDownloaded += gained
+ reader.bytesDownloaded += gained
+ meters.add(reader.id, networkId, gained)
+ }
+ if (blockFinished && block.rangeEnd !== null) {
+ advanceBlock(block, networkId, block.rangeEnd - block.rangeStart + 1)
+ block.status = 'completed'
+ recomputeAggregates(state, this.runtime.blocks)
+ }
+ this.host.scheduleUpdate()
+
+ if (next) {
+ prefetch = next
+ continue
+ }
+ if (blockFinished) return { type: 'completed' }
+ // Nothing more to claim (the download may be ending) — the unfinished block is this
+ // reader's still, so its next chunk goes out now rather than never.
+ prefetch = fire(block, nextOffset)
+ }
+ }
+
+ /** Reads failure kinds the transfer acts on: a rate limit becomes a wait every reader
+ * shares, auth and missing files end the download, the rest retry on this reader. */
+ private asOutcome(self: ReaderRuntime, error: unknown): BlockOutcome {
+ const code =
+ (error as { errorMessage?: string } | null)?.errorMessage ??
+ (error instanceof Error ? error.message : String(error))
+ if (/LIMIT_INVALID/.test(code) && this.maxChunkBytes > 4096) {
+ // Telegram caps how big a single request may be, per region of the file: halve and
+ // take the block again at a size it will answer. One halving per short window — every
+ // reader failing on the same oversized wave must not multiply the cap down to the floor.
+ const now = Date.now()
+ if (now - this.lastHalveAt > 500) {
+ this.lastHalveAt = now
+ this.maxChunkBytes = Math.max(4096, this.maxChunkBytes >> 1)
+ }
+ return { type: 'retry', waitMs: 50 }
+ }
+ if (error instanceof TelegramFileError) {
+ if (error.kind === 'rate') {
+ const waitMs = (error.waitSeconds ?? 1) * 1000
+ if (waitMs > RATE_WAIT_MAX_MS) return { type: 'give-up', error }
+ this.rateLimitedUntil = Math.max(this.rateLimitedUntil, Date.now() + waitMs)
+ return { type: 'retry', waitMs }
+ }
+ if (error.kind === 'auth' || error.kind === 'missing') {
+ return { type: 'give-up', error }
+ }
+ }
+ // A connection or server failure: back off and take the block again. Progress made resets
+ // the count, as the HTTP transfer's does.
+ self.failures += 1
+ if (self.failures > MAX_RETRIES) return { type: 'give-up', error }
+ const exact = Math.min(RETRY_BASE_MS * 2 ** (self.failures - 1), RETRY_MAX_MS)
+ return { type: 'retry', waitMs: exact * (0.8 + 0.4 * Math.random()) }
+ }
+
+ private write(offset: number, buffer: Buffer): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const writer = this.runtime.file.writer(offset)
+ writer.on('error', reject)
+ writer.end(buffer, () => {
+ writer.off('error', reject)
+ resolve()
+ })
+ })
+ }
+}
+
+/** A download of a photo, whose byte size Telegram doesn't say ahead of time: one reader runs
+ * it to the end, and the size is known once the last chunk lands. */
+export function photoDownload(request: StartTelegramDownloadRequest): boolean {
+ return request.mediaType === 'photo'
+}
diff --git a/src/main/download/transfer.ts b/src/main/download/transfer.ts
index 6a91b54..ff1c988 100644
--- a/src/main/download/transfer.ts
+++ b/src/main/download/transfer.ts
@@ -9,7 +9,9 @@ import type {
ProxyConfig,
StartHttpDownloadRequest,
StartNzbDownloadRequest,
+ StartTelegramDownloadRequest,
StartTorrentDownloadRequest,
+ TelegramDownloadState,
TorrentDownloadState,
TorrentPieceState
} from '../../shared/types'
@@ -71,6 +73,14 @@ export interface TorrentTransferTarget extends TransferTargetBase {
uploadMeters: Meters
}
+export interface TelegramTransferTarget extends TransferTargetBase {
+ state: TelegramDownloadState
+ requestPayload: StartTelegramDownloadRequest
+ blocks: HttpBlockState[]
+ /** What each reader, and each network, has received (see updateSpeeds). */
+ meters: Meters
+}
+
export interface NzbTransferTarget extends TransferTargetBase {
file: NzbDestination
state: NzbDownloadState
@@ -80,7 +90,8 @@ export interface NzbTransferTarget extends TransferTargetBase {
meters: Meters
}
-export type TransferTarget = HttpTransferTarget | TorrentTransferTarget | NzbTransferTarget
+export type TransferTarget =
+ HttpTransferTarget | TorrentTransferTarget | TelegramTransferTarget | NzbTransferTarget
/** What a transfer asks of the manager. */
export interface TransferHost {
@@ -164,7 +175,13 @@ export function updateSpeeds(runtime: TransferTarget, now: number): boolean {
target[key] = value
}
const connections: Array<{ id: number; status: string; speedBytesPerSec: number }> =
- state.kind === 'torrent' ? state.peers : state.streams
+ state.kind === 'http'
+ ? state.streams
+ : state.kind === 'telegram'
+ ? state.readers
+ : state.kind === 'torrent'
+ ? state.peers
+ : state.streams
for (const connection of connections) {
// Read every tick, moving or not, so its window is never stale when it moves again.
const speed = runtime.meters.connections.get(connection.id)?.read(now) ?? 0
@@ -246,7 +263,12 @@ export function updateTimeLeft(state: DownloadState, elapsedSeconds: number): bo
export function clearSpeeds(state: DownloadState): void {
state.speedBytesPerSec = 0
state.timeLeftSeconds = undefined
- const connections = state.kind === 'torrent' ? state.peers : state.streams
+ const connections =
+ state.kind === 'http' || state.kind === 'nzb'
+ ? state.streams
+ : state.kind === 'telegram'
+ ? state.readers
+ : state.peers
for (const connection of connections) connection.speedBytesPerSec = 0
for (const network of state.networks) network.speedBytesPerSec = 0
if (state.kind === 'http') state.diskLimited = undefined
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index ac2163d..cd1d4ce 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -21,6 +21,8 @@ import { DownloadManager } from '../download/downloadManager'
import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'
import { listHistory } from '../download/history'
import { probeUrl } from '../download/probe'
+import { FakeTelegramService } from '../telegram/fake'
+import { TelegramService, type TelegramServiceApi } from '../telegram/service'
import { testUsenetServer } from '../download/nzb/nntp'
import {
loadUsenetServer,
@@ -29,6 +31,7 @@ import {
viewOf
} from '../download/nzb/usenetServer'
import { onMagnetCheckStatus } from '../download/torrent/metadata'
+import { testKnobs } from '../testKnobs'
import { deviceBindingSupported } from '../network/deviceBinding'
import { pendingLink, pendingLinks, releaseLink } from '../openLinks'
import { NetworkMonitor } from '../network/interfaces'
@@ -84,7 +87,19 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
const window = getWindow()
if (window && !window.isDestroyed()) window.webContents.send(IpcChannels.networksChanged, list)
})
- const manager = new DownloadManager(getWindow, networks)
+ // Telegram (Saved Messages): its sign-in state changes push to the window, and a stored
+ // session reconnects in the background at startup.
+ const telegram: TelegramServiceApi = testKnobs.telegramFake
+ ? new FakeTelegramService()
+ : new TelegramService()
+ telegram.onChange = (state) => {
+ const window = getWindow()
+ if (window && !window.isDestroyed()) {
+ window.webContents.send(IpcChannels.telegramAuthChanged, state)
+ }
+ }
+ void telegram.restore().catch((error) => console.error('[plexo] telegram restore', error))
+ const manager = new DownloadManager(getWindow, networks, telegram)
// Waking from sleep, the networks may have changed without a poll in between to see it.
powerMonitor.on('resume', () => {
manager.systemResumed()
@@ -273,5 +288,25 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
handle('updateState', () => updateState())
handle('showUpdateMenu', () => showUpdateMenu())
+ handle('telegramState', () => telegram.authState())
+ handle('telegramStartLogin', async (_event, credentials) => {
+ await telegram.startLogin(credentials)
+ })
+ handle('telegramStartQrLogin', async () => {
+ await telegram.startQrLogin()
+ })
+ handle('telegramSubmitCode', async (_event, code) => {
+ await telegram.submitCode(code)
+ })
+ handle('telegramSubmitPassword', async (_event, password) => {
+ await telegram.submitPassword(password)
+ })
+ handle('telegramLogout', async () => {
+ await telegram.logout()
+ })
+ handle('telegramListMedia', async (_event, offsetId, limit) => {
+ return telegram.listMediaPage(offsetId, limit)
+ })
+
return manager
}
diff --git a/src/main/telegram/fake.ts b/src/main/telegram/fake.ts
new file mode 100644
index 0000000..fb91f81
--- /dev/null
+++ b/src/main/telegram/fake.ts
@@ -0,0 +1,225 @@
+/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function --
+ the double's shape: interface-conforming args it doesn't need, and steps that are no-ops. */
+import type {
+ TelegramAuthState,
+ TelegramCredentials,
+ TelegramMediaItem,
+ TelegramMediaPage,
+ TelegramMediaType
+} from '../../shared/types'
+import { testKnobs } from '../testKnobs'
+import type { TelegramFileSource } from '../download/telegramTransfer'
+import { TelegramFileError } from '../download/telegramTransfer'
+import type { TelegramServiceApi } from './service'
+
+/**
+ * The Telegram service's double for end-to-end tests (PLEXO_E2E_TELEGRAM_FAKE=1): signs in
+ * instantly, lists a page of Saved Messages media that isn't really there, and serves its
+ * bytes the way a DC would — including the faults the real one inflicts (FLOOD_WAITs, stale
+ * file references, per-region caps on the request size, a photo whose size only the download
+ * learns). The transfer and the manager run against it unchanged, which is the point.
+ */
+
+const KB = 1024
+
+interface FakeFile {
+ messageId: number
+ type: TelegramMediaType
+ name: string
+ mimeType: string
+ /** 0 marks a photo: its size is only known once the download reaches its end. */
+ size: number
+ seed: number
+ /** The first request this many times answers with a FLOOD_WAIT of one second. */
+ floodWaits?: number
+ /** The first request this many times answers with a stale file reference. */
+ staleReference?: number
+ /** Requests larger than this answer LIMIT_INVALID — a per-region cap, as the real server. */
+ limitCap?: number
+}
+
+const FAKE_MEDIA: FakeFile[] = [
+ {
+ messageId: 1,
+ type: 'video',
+ name: 'clip.mp4',
+ mimeType: 'video/mp4',
+ size: 3 * KB * KB,
+ seed: 11
+ },
+ { messageId: 2, type: 'photo', name: 'shot.jpg', mimeType: 'image/jpeg', size: 0, seed: 22 },
+ {
+ messageId: 3,
+ type: 'document',
+ name: 'flaky.zip',
+ mimeType: 'application/zip',
+ size: 3 * KB * KB,
+ seed: 33,
+ floodWaits: 1,
+ staleReference: 1,
+ limitCap: 64 * KB
+ }
+]
+
+/** The photo's real length: the download learns it at the empty answer. */
+const PHOTO_ACTUAL_BYTES = 2 * KB * KB
+
+/** xorshift32 — the same deterministic pattern the test origin serves. */
+class SeededBytes {
+ private state: number
+ constructor(seed: number) {
+ this.state = seed >>> 0 || 1
+ }
+ next(): number {
+ this.state ^= this.state << 13
+ this.state ^= this.state >>> 17
+ this.state ^= this.state << 5
+ return this.state & 0xff
+ }
+ slice(offset: number, length: number): Buffer {
+ // Walks to the offset rather than storing megabytes nobody reads in a test.
+ const walker = new SeededBytes(this.state)
+ for (let at = 0; at < offset; at++) walker.next()
+ const out = Buffer.alloc(length)
+ for (let i = 0; i < length; i++) out[i] = walker.next()
+ return out
+ }
+}
+
+class FakeFileSource {
+ private requests = 0
+ private readonly generator: SeededBytes
+ constructor(private readonly file: FakeFile) {
+ this.generator = new SeededBytes(file.seed)
+ }
+
+ get unknownSize(): boolean {
+ return this.file.size === 0
+ }
+
+ /** The photo's real length; a known file's length. */
+ get servedBytes(): number {
+ return this.file.size === 0 ? PHOTO_ACTUAL_BYTES : this.file.size
+ }
+
+ async request(offset: number, limit: number, _signal?: AbortSignal): Promise<Buffer> {
+ this.requests += 1
+ if (testKnobs.telegramDelayMs > 0) {
+ await new Promise((resolve) => setTimeout(resolve, testKnobs.telegramDelayMs))
+ }
+ if (this.file.staleReference !== undefined && this.requests <= this.file.staleReference) {
+ throw new TelegramFileError('other', 'FILE_REFERENCE_EXPIRED')
+ }
+ if (this.file.floodWaits !== undefined && this.requests <= this.file.floodWaits) {
+ throw new TelegramFileError('rate', 'FLOOD_WAIT_1', 1)
+ }
+ if (this.file.limitCap !== undefined && limit > this.file.limitCap) {
+ throw new TelegramFileError('other', 'LIMIT_INVALID')
+ }
+ if (offset >= this.servedBytes) return Buffer.alloc(0)
+ return this.generator.slice(offset, Math.min(limit, this.servedBytes - offset))
+ }
+
+ /** The transfer re-locates the file over a stale reference through this (see
+ * telegramTransfer.ts): the double marks the reference fresh again, and the retry that
+ * follows succeeds — the same contract the real service's re-locate keeps. */
+ async refresh(): Promise<void> {
+ if (this.file.staleReference !== undefined) {
+ this.requests = Math.max(this.requests, this.file.staleReference)
+ }
+ }
+}
+
+export class FakeTelegramService implements TelegramServiceApi {
+ private auth: TelegramAuthState = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false
+ }
+ onChange: ((state: TelegramAuthState) => void) | undefined
+
+ private push(update: Partial<TelegramAuthState>): void {
+ this.auth = { ...this.auth, ...update, error: undefined }
+ this.onChange?.(this.authState())
+ }
+
+ authState(): TelegramAuthState {
+ return structuredClone(this.auth)
+ }
+
+ /** Nothing to restore: a fresh fake starts signed out, and the spec signs in. */
+ async restore(): Promise<void> {}
+
+ async startLogin(_credentials: TelegramCredentials): Promise<void> {
+ this.push({
+ signedIn: true,
+ hasOwnKeys: true,
+ apiId: _credentials.apiId,
+ phone: _credentials.phone,
+ userName: 'Fake User'
+ })
+ }
+
+ async startQrLogin(): Promise<void> {
+ this.push({ signedIn: true, hasOwnKeys: false, userName: 'Fake User' })
+ }
+
+ async submitCode(_code: string): Promise<void> {}
+
+ async submitPassword(_password: string): Promise<void> {}
+
+ async logout(): Promise<void> {
+ this.push({
+ signedIn: false,
+ hasOwnKeys: false,
+ apiId: undefined,
+ phone: undefined,
+ userName: undefined
+ })
+ }
+
+ async listMediaPage(_offsetId?: number, _limit?: number): Promise<TelegramMediaPage> {
+ const items: TelegramMediaItem[] = FAKE_MEDIA.map((file) => ({
+ messageId: file.messageId,
+ type: file.type,
+ fileName: file.name,
+ mimeType: file.mimeType,
+ totalBytes: file.size,
+ ...(file.type === 'video' ? { width: 1280, height: 720 } : {}),
+ date: Math.floor(Date.now() / 1000) - file.messageId * 3600
+ }))
+ return { items, exhausted: true }
+ }
+
+ async mediaInfo(messageId: number): Promise<{
+ fileName: string
+ totalBytes: number
+ mimeType: string
+ mediaType: TelegramMediaType
+ }> {
+ const file = FAKE_MEDIA.find((entry) => entry.messageId === messageId)
+ if (!file) throw new Error("That message's media is gone from Saved Messages.")
+ return {
+ fileName: file.name,
+ totalBytes: file.size,
+ mimeType: file.mimeType,
+ mediaType: file.type
+ }
+ }
+
+ async fileSource(messageId: number): Promise<TelegramFileSource> {
+ const file = FAKE_MEDIA.find((entry) => entry.messageId === messageId)
+ if (!file)
+ throw new TelegramFileError('missing', "That message's media is gone from Saved Messages.")
+ const source = new FakeFileSource(file)
+ return {
+ get unknownSize(): boolean {
+ return source.unknownSize
+ },
+ request: (offset: number, limit: number, signal?: AbortSignal) =>
+ source.request(offset, limit, signal),
+ refresh: (): Promise<void> => source.refresh(),
+ dispose: async (): Promise<void> => {}
+ }
+ }
+}
diff --git a/src/main/telegram/injected.d.ts b/src/main/telegram/injected.d.ts
new file mode 100644
index 0000000..db7e17a
--- /dev/null
+++ b/src/main/telegram/injected.d.ts
@@ -0,0 +1,5 @@
+/** Replaced at build time from TELEGRAM_API_ID / TELEGRAM_API_HASH (electron.vite.config.ts →
+ * define). Unset in dev builds and any build without the env — the app then falls back to
+ * asking the user for their own credentials. */
+declare const __PLEXO_TG_API_ID__: number | undefined
+declare const __PLEXO_TG_API_HASH__: string | undefined
diff --git a/src/main/telegram/service.ts b/src/main/telegram/service.ts
new file mode 100644
index 0000000..2b38132
--- /dev/null
+++ b/src/main/telegram/service.ts
@@ -0,0 +1,1032 @@
+import { Api, TelegramClient } from 'telegram'
+import { LAYER } from 'telegram/tl/AllTLObjects'
+import { StringSession } from 'telegram/sessions'
+import { sendCode, signInUserWithQrCode } from 'telegram/client/auth'
+import { computeCheck } from 'telegram/Password'
+import { FloodWaitError, FileMigrateError } from 'telegram/errors'
+import { strippedPhotoToJpg } from 'telegram/Utils'
+import { LogLevel } from 'telegram/extensions/Logger'
+import type { MTProtoSender } from 'telegram/network'
+import QRCode from 'qrcode'
+import bigInt from 'big-integer'
+import { app, safeStorage } from 'electron'
+import { readFile, rm, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import type { TelegramFileSource } from '../download/telegramTransfer'
+import { TelegramFileError } from '../download/telegramTransfer'
+import type {
+ TelegramAuthState,
+ TelegramCredentials,
+ TelegramMediaItem,
+ TelegramMediaPage,
+ TelegramMediaType
+} from '../../shared/types'
+
+/**
+ * The user's Telegram session, its Saved Messages listing, and the file sources its downloads
+ * fetch from. Signed in with the user's own api_id/api_hash (my.telegram.org) and a phone code
+ * — a bot token can't read a user's Saved Messages — the session is used only ever against the
+ * "me" peer: this module has no way to address any other chat.
+ */
+
+const STORE_PATH = (): string => join(app.getPath('userData'), 'telegram-auth.json')
+
+/** Listing page size, and the most messages one listing request may return. */
+const LIST_PAGE = 50
+
+/** Independent connections a download may open to its file's data center, all under the one
+ * login — the shape of a fast download in Telegram's own desktop client. */
+const FILE_SENDER_POOL = 8
+
+/** Plexo's own api credentials, replaced into release builds at build time (see
+ * electron.vite.config.ts). When present, signing in needs only a phone or the QR — the api
+ * form becomes an advanced fallback. */
+const BUNDLED_CREDENTIALS: { apiId: number; apiHash: string } | undefined =
+ typeof __PLEXO_TG_API_ID__ === 'number' &&
+ __PLEXO_TG_API_ID__ > 0 &&
+ typeof __PLEXO_TG_API_HASH__ === 'string' &&
+ __PLEXO_TG_API_HASH__ !== ''
+ ? { apiId: __PLEXO_TG_API_ID__, apiHash: __PLEXO_TG_API_HASH__ }
+ : undefined
+
+interface StoredAuth {
+ /** Sealed (safeStorage) or plain JSON of TelegramCredentials. */
+ credentials?: string
+ /** Sealed (safeStorage) or plain GramJS session string. */
+ session?: string
+ /** The stored credentials are the user's own, not the bundled pair: they keep winning over
+ * it until the fields are emptied or new keys are typed. */
+ ownKeys?: boolean
+}
+
+/** A message's media as a download needs it: its location, and its byte size when Telegram
+ * reports one (a photo's is only known once downloaded). */
+interface LocatedMedia {
+ location: Api.TypeInputFileLocation
+ dcId: number
+ /** null when the size is unknown (a photo). */
+ size: number | null
+ mediaType: TelegramMediaType
+ fileName: string
+ mimeType: string
+}
+
+function seal(value: string): string | undefined {
+ if (!safeStorage.isEncryptionAvailable()) return undefined
+ // Linux without a keyring reports itself as available but stores basic_text — close to
+ // plain text. A full-account session (or its api registration) isn't saved at all there,
+ // the same call sealBrowser makes for cookies: keep it in memory only.
+ if (process.platform === 'linux' && safeStorage.getSelectedStorageBackend() === 'basic_text') {
+ return undefined
+ }
+ try {
+ return safeStorage.encryptString(value).toString('base64')
+ } catch {
+ return undefined
+ }
+}
+
+function unseal(sealed: string): string | undefined {
+ try {
+ return safeStorage.decryptString(Buffer.from(sealed, 'base64'))
+ } catch {
+ return undefined
+ }
+}
+
+async function loadStore(): Promise<StoredAuth> {
+ try {
+ const parsed = JSON.parse(await readFile(STORE_PATH(), 'utf-8')) as StoredAuth
+ return typeof parsed === 'object' && parsed !== null ? parsed : {}
+ } catch {
+ return {}
+ }
+}
+
+async function saveStore(update: StoredAuth): Promise<void> {
+ // 0o600: the session is full account access — other local users read nothing.
+ await writeFile(STORE_PATH(), JSON.stringify(update), { encoding: 'utf-8', mode: 0o600 })
+}
+
+/** The message's media as Telegram files name themselves: the file attribute's name when there
+ * is one, or by kind and message id otherwise. */
+function defaultName(mediaType: TelegramMediaType, messageId: number, mimeType: string): string {
+ const extension =
+ {
+ photo: '.jpg',
+ video: '.mp4',
+ audio: '.mp3',
+ voice: '.ogg',
+ animation: '.mp4',
+ sticker: '.webp',
+ document: ''
+ }[mediaType] ?? ''
+ const idPart = mediaType === 'document' ? 'file' : mediaType
+ return mimeType === '' && extension === ''
+ ? `${idPart}_${messageId}`
+ : `${idPart}_${messageId}${extension}`
+}
+
+/** The message's media, classified and named, as both the listing and the downloads use it. */
+function describeMedia(
+ messageId: number,
+ media: Api.TypeMessageMedia
+):
+ | (Omit<TelegramMediaItem, 'messageId' | 'date' | 'thumbnail'> & { media: Api.TypeMessageMedia })
+ | null {
+ if (media instanceof Api.MessageMediaPhoto) {
+ const photo = media.photo
+ if (!(photo instanceof Api.Photo)) return null
+ const size = photo.sizes
+ .filter((entry): entry is Api.PhotoSize => entry instanceof Api.PhotoSize)
+ .sort((a, b) => b.w * b.h - a.w * a.h)[0]
+ return {
+ type: 'photo',
+ fileName: defaultName('photo', messageId, 'image/jpeg'),
+ mimeType: 'image/jpeg',
+ totalBytes: 0,
+ width: size?.w,
+ height: size?.h,
+ media
+ }
+ }
+ if (media instanceof Api.MessageMediaDocument) {
+ const document = media.document
+ if (!(document instanceof Api.Document)) return null
+ let type: TelegramMediaType = 'document'
+ let width: number | undefined
+ let height: number | undefined
+ let fileName = ''
+ for (const attribute of document.attributes) {
+ if (attribute instanceof Api.DocumentAttributeFilename) {
+ fileName = attribute.fileName
+ } else if (attribute instanceof Api.DocumentAttributeAnimated) {
+ type = 'animation'
+ } else if (attribute instanceof Api.DocumentAttributeSticker) {
+ type = 'sticker'
+ } else if (attribute instanceof Api.DocumentAttributeVideo) {
+ type = 'video'
+ width = attribute.w
+ height = attribute.h
+ } else if (attribute instanceof Api.DocumentAttributeAudio) {
+ type = attribute.voice ? 'voice' : 'audio'
+ }
+ }
+ return {
+ type,
+ fileName: fileName || defaultName(type, messageId, document.mimeType),
+ mimeType: document.mimeType,
+ totalBytes: Number(document.size),
+ width,
+ height,
+ media
+ }
+ }
+ // Web previews, contacts, maps and the rest aren't downloadable media.
+ return null
+}
+
+/** The tiny inline thumbnail Telegram carries in the message itself — no download, decoded by
+ * GramJS into a JPEG — as a data URL for the media browser. */
+function thumbnailOf(media: Api.TypeMessageMedia): string | undefined {
+ let stripped: Buffer | undefined
+ if (media instanceof Api.MessageMediaPhoto) {
+ const photo = media.photo
+ if (photo instanceof Api.Photo) {
+ stripped = photo.sizes.find(
+ (entry): entry is Api.PhotoStrippedSize => entry instanceof Api.PhotoStrippedSize
+ )?.bytes
+ }
+ } else if (media instanceof Api.MessageMediaDocument) {
+ const document = media.document
+ if (document instanceof Api.Document) {
+ stripped = document.thumbs?.find(
+ (entry): entry is Api.PhotoStrippedSize => entry instanceof Api.PhotoStrippedSize
+ )?.bytes
+ }
+ }
+ if (!stripped || stripped.length === 0) return undefined
+ try {
+ const jpeg = strippedPhotoToJpg(stripped)
+ return jpeg ? `data:image/jpeg;base64,${jpeg.toString('base64')}` : undefined
+ } catch {
+ return undefined
+ }
+}
+
+function describeError(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+/** Runs `promise` against `signal`: rejects as soon as the signal aborts, even though the
+ * request underneath keeps going (its answer is then discarded). */
+function raceSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) {
+ reject(new TelegramFileError('other', 'Aborted'))
+ void promise.catch(() => {})
+ return
+ }
+ const onAbort = (): void => {
+ signal.removeEventListener('abort', onAbort)
+ reject(new TelegramFileError('other', 'Aborted'))
+ }
+ signal.addEventListener('abort', onAbort, { once: true })
+ promise.then(
+ (value) => {
+ signal.removeEventListener('abort', onAbort)
+ resolve(value)
+ },
+ (error) => {
+ signal.removeEventListener('abort', onAbort)
+ reject(error)
+ }
+ )
+ })
+}
+
+/** The failures of a getFile request, as kinds the transfer acts on. */
+function asFileError(error: unknown): TelegramFileError {
+ if (error instanceof FloodWaitError) {
+ return new TelegramFileError(
+ 'rate',
+ `Telegram rate limit: wait ${error.seconds}s`,
+ error.seconds
+ )
+ }
+ const message = describeError(error)
+ const code = (error as { errorMessage?: string } | null)?.errorMessage ?? message
+ if (
+ /AUTH_KEY_UNREGISTERED|AUTH_KEY_DUPLICATED|SESSION_REVOKED|USER_DEACTIVATED|SESSION_EXPIRED/.test(
+ code
+ )
+ ) {
+ return new TelegramFileError('auth', 'This Telegram session signed out. Sign in again.')
+ }
+ if (/LOCATION_INVALID|FILE_ID_INVALID|FILE_INVALID|ENTITY_EMPTY|MESSAGE_ID_INVALID/.test(code)) {
+ return new TelegramFileError('missing', "That message's media is gone from Saved Messages.")
+ }
+ if (
+ /TIMEOUT|TIMEOUT_NOT_ENOUGHT| disconnect|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE/.test(code)
+ ) {
+ return new TelegramFileError('network', 'The connection to Telegram dropped.')
+ }
+ return new TelegramFileError('other', message)
+}
+
+/** Telegram rejected the login itself — a revoked, expired or killed session. Sign-in is
+ * genuinely required again; the app's job is to say so cleanly and keep the api registration. */
+const isAuthLossError = (error: unknown): boolean =>
+ /AUTH_KEY_UNREGISTERED|AUTH_KEY_DUPLICATED|SESSION_REVOKED|USER_DEACTIVATED|SESSION_EXPIRED|AUTH_KEY_PERM_EMPTY/.test(
+ (error as { errorMessage?: string; message?: string } | null)?.errorMessage ??
+ describeError(error)
+ )
+
+/** What the window's handlers and the download manager need of the Telegram service — one
+ * interface, so the e2e double (fake.ts) can stand in for the real one. */
+export interface TelegramServiceApi {
+ /** Set by registerIpcHandlers: pushes state changes to the window. */
+ onChange: ((state: TelegramAuthState) => void) | undefined
+ authState(): TelegramAuthState
+ restore(): Promise<void>
+ startLogin(credentials: TelegramCredentials): Promise<void>
+ startQrLogin(): Promise<void>
+ submitCode(code: string): Promise<void>
+ submitPassword(password: string): Promise<void>
+ logout(): Promise<void>
+ listMediaPage(offsetId?: number, limit?: number): Promise<TelegramMediaPage>
+ mediaInfo(messageId: number): Promise<{
+ fileName: string
+ totalBytes: number
+ mimeType: string
+ mediaType: TelegramMediaType
+ }>
+ fileSource(messageId: number): Promise<TelegramFileSource>
+}
+
+export class TelegramService implements TelegramServiceApi {
+ private client?: TelegramClient
+ private credentials?: TelegramCredentials
+ private phoneCodeHash?: string
+ /** The live QR sign-in, so switching to the phone flow or signing out can stop its polling. */
+ private qrAbort?: AbortController
+ /** Whether the credentials in play are the user's own, not the bundled pair — what
+ * `hasOwnKeys` in the state says, and what keeps them winning over the bundle. */
+ private usingOwnKeys = false
+ private auth: TelegramAuthState = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined
+ }
+ /** Set by registerIpcHandlers: pushes state changes to the window. */
+ onChange: ((state: TelegramAuthState) => void) | undefined
+
+ authState(): TelegramAuthState {
+ return structuredClone(this.auth)
+ }
+
+ /** Reads the stored credentials and session and, if there is one, reconnects in the
+ * background — its answer (signed in, or the session was revoked) pushes when it lands. */
+ async restore(): Promise<void> {
+ const stored = await loadStore()
+ const credentials = stored.credentials
+ ? (JSON.parse(unseal(stored.credentials) ?? 'null') as TelegramCredentials | null)
+ : null
+ if (!credentials?.apiId || !credentials.apiHash) {
+ // No credentials of the user's own: a bundled build can still offer the QR.
+ if (BUNDLED_CREDENTIALS) this.onChange?.(this.authState())
+ return
+ }
+ this.credentials = credentials
+ this.usingOwnKeys = stored.ownKeys === true
+ this.auth = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ apiId: credentials.apiId,
+ phone: credentials.phone
+ }
+ if (!stored.session) {
+ this.onChange?.(this.authState())
+ return
+ }
+ try {
+ await this.openWithSession(unseal(stored.session) ?? '')
+ const me = await this.client!.getMe()
+ this.auth = {
+ ...this.auth,
+ signedIn: true,
+ userName: userNameOf(me)
+ }
+ } catch {
+ // A dead session is a sign-in prompt, not an error.
+ this.client = undefined
+ }
+ this.onChange?.(this.authState())
+ }
+
+ private async openWithSession(session: string): Promise<TelegramClient> {
+ if (!this.credentials) throw new Error('Telegram credentials are missing.')
+ const client = new TelegramClient(
+ new StringSession(session),
+ this.credentials.apiId,
+ this.credentials.apiHash,
+ {
+ connectionRetries: 3,
+ autoReconnect: true
+ }
+ )
+ client.setLogLevel(LogLevel.ERROR)
+ await client.connect()
+ this.client = client
+ return client
+ }
+
+ /** Connects and sends the login code. A release build has Plexo's own credentials bundled,
+ * so only the phone is asked for; otherwise the user's api_id/api_hash come in too. Stops
+ * any QR sign-in that was waiting. */
+ async startLogin(input: TelegramCredentials): Promise<void> {
+ this.qrAbort?.abort()
+ // Priority: keys the user just typed, then his own stored pair, then the bundled one.
+ const ownApiId = Math.floor(Number(input.apiId))
+ const ownGiven = Number.isSafeInteger(ownApiId) && ownApiId > 0 && input.apiHash.trim() !== ''
+ const storedOwn =
+ this.usingOwnKeys && this.credentials?.apiId && this.credentials.apiHash
+ ? this.credentials
+ : undefined
+ const apiId = ownGiven ? ownApiId : (storedOwn?.apiId ?? BUNDLED_CREDENTIALS?.apiId)
+ const apiHash = ownGiven
+ ? input.apiHash.trim()
+ : (storedOwn?.apiHash ?? BUNDLED_CREDENTIALS?.apiHash)
+ const phone = input.phone.trim()
+ if (apiId === undefined || !Number.isSafeInteger(apiId) || apiId <= 0)
+ throw new Error('Enter the api_id from my.telegram.org.')
+ if (!apiHash) throw new Error('Enter the api_hash from my.telegram.org.')
+ if (!phone) throw new Error('Enter your phone number.')
+ this.usingOwnKeys = ownGiven || !!storedOwn
+ this.credentials = { apiId, apiHash, phone }
+ try {
+ const client = await this.openWithSession('')
+ const { phoneCodeHash } = await sendCode(client, { apiId, apiHash }, phone)
+ this.phoneCodeHash = phoneCodeHash
+ this.auth = {
+ signedIn: false,
+ awaitingCode: true,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ apiId,
+ phone
+ }
+ this.onChange?.(this.authState())
+ } catch (error) {
+ this.auth = {
+ ...this.auth,
+ awaitingCode: false,
+ awaitingPassword: false,
+ error: describeError(error)
+ }
+ this.onChange?.(this.authState())
+ throw error
+ }
+ }
+
+ /** Starts a QR sign-in: the dialog is fed fresh login tokens (rendered as a QR that Telegram
+ * rotates) until the user scans one from Settings → Devices. Needs credentials — Plexo's
+ * own when bundled, else the user's from an earlier sign-in. A two-step-verification
+ * account moves the dialog on to its password step after the scan. */
+ async startQrLogin(): Promise<void> {
+ this.qrAbort?.abort()
+ const credentials =
+ this.credentials ?? (BUNDLED_CREDENTIALS ? { ...BUNDLED_CREDENTIALS, phone: '' } : undefined)
+ if (!credentials) {
+ throw new Error(
+ 'This build has no Telegram credentials — enter your own api_id/api_hash once and the QR works from the next launch.'
+ )
+ }
+ this.credentials = credentials
+ const abort = new AbortController()
+ this.qrAbort = abort
+ const client = await this.openWithSession('')
+ const pushQr = async (token: Buffer): Promise<void> => {
+ const dataUrl = await QRCode.toDataURL(`tg://login?token=${token.toString('base64url')}`, {
+ margin: 1,
+ width: 232
+ })
+ this.auth = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ awaitingQr: true,
+ qrDataUrl: dataUrl,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ apiId: credentials.apiId,
+ error: undefined
+ }
+ this.onChange?.(this.authState())
+ }
+ this.auth = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ awaitingQr: true,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ apiId: credentials.apiId
+ }
+ this.onChange?.(this.authState())
+ try {
+ await signInUserWithQrCode(
+ client,
+ { apiId: credentials.apiId, apiHash: credentials.apiHash },
+ {
+ qrCode: async ({ token }) => {
+ // GramJS's QR params carry no abort hook: cancelling throws from inside the
+ // callback instead, which ends the helper's polling loop.
+ if (abort.signal.aborted) throw new Error('QR sign-in cancelled')
+ await pushQr(token)
+ },
+ onError: (error) => {
+ this.auth = { ...this.auth, error: describeError(error) }
+ this.onChange?.(this.authState())
+ }
+ }
+ )
+ if (abort.signal.aborted) return
+ await this.completeSignIn(client)
+ } catch (error) {
+ if (abort.signal.aborted) return
+ if (
+ /SESSION_PASSWORD_NEEDED/.test(
+ (error as { errorMessage?: string } | null)?.errorMessage ?? ''
+ )
+ ) {
+ // The scan went through and the account has two-step verification: the dialog asks
+ // for its password, and CheckPassword finishes the sign-in as in the phone flow.
+ this.auth = {
+ ...this.auth,
+ awaitingQr: false,
+ awaitingPassword: true,
+ error: undefined
+ }
+ this.onChange?.(this.authState())
+ return
+ }
+ this.auth = { ...this.auth, awaitingQr: false, error: describeError(error) }
+ this.onChange?.(this.authState())
+ }
+ }
+
+ /** Accepts the login code. Wrong codes keep the dialog asking; a password requirement moves
+ * it on to the password. */
+ async submitCode(code: string): Promise<void> {
+ const client = this.client
+ if (!client || !this.credentials || !this.phoneCodeHash) {
+ throw new Error('Start the sign-in again: the code was sent too long ago.')
+ }
+ try {
+ const result = await client.invoke(
+ new Api.auth.SignIn({
+ phoneNumber: this.credentials.phone,
+ phoneCodeHash: this.phoneCodeHash,
+ phoneCode: code.trim()
+ })
+ )
+ await this.completeSignIn(client)
+ void result
+ } catch (error) {
+ if (/SESSION_PASSWORD_NEEDED/.test((error as { errorMessage?: string }).errorMessage ?? '')) {
+ this.auth = { ...this.auth, awaitingCode: false, awaitingPassword: true, error: undefined }
+ this.onChange?.(this.authState())
+ return
+ }
+ this.auth = { ...this.auth, error: describeError(error) }
+ this.onChange?.(this.authState())
+ return
+ }
+ }
+
+ /** Accepts the two-step-verification password. */
+ async submitPassword(password: string): Promise<void> {
+ const client = this.client
+ if (!client) throw new Error('Start the sign-in again.')
+ try {
+ const pwdInfo = await client.invoke(new Api.account.GetPassword())
+ const srp = await computeCheck(pwdInfo, password)
+ await client.invoke(new Api.auth.CheckPassword({ password: srp }))
+ await this.completeSignIn(client)
+ } catch (error) {
+ this.auth = { ...this.auth, error: describeError(error) }
+ this.onChange?.(this.authState())
+ }
+ }
+
+ private async completeSignIn(client: TelegramClient): Promise<void> {
+ // The session is the StringSession this client was built with; its base class types save()
+ // as void.
+ const session = (client.session as StringSession).save()
+ const credentials = this.credentials!
+ let userName: string | undefined
+ try {
+ userName = userNameOf(await client.getMe())
+ } catch {
+ // The name is display-only.
+ }
+ this.auth = {
+ signedIn: true,
+ awaitingCode: false,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ apiId: credentials.apiId,
+ phone: credentials.phone,
+ userName,
+ error: undefined
+ }
+ await saveStore({
+ credentials: seal(JSON.stringify(credentials)),
+ session: seal(session),
+ ownKeys: this.usingOwnKeys === true || undefined
+ })
+ this.onChange?.(this.authState())
+ }
+
+ /** Signs out and forgets everything stored. Downloads under way fail with "signed out". */
+ async logout(): Promise<void> {
+ this.qrAbort?.abort()
+ try {
+ await this.client?.invoke(new Api.auth.LogOut())
+ } catch {
+ // Logging out server-side is best-effort; the local session goes regardless.
+ }
+ try {
+ await this.client?.disconnect()
+ } catch {
+ // Same.
+ }
+ this.client = undefined
+ this.phoneCodeHash = undefined
+ // The api registration isn't the account — the session was. Keeping it lets the next
+ // sign-in lead with the QR instead of the api form.
+ const credentials =
+ this.credentials ?? (BUNDLED_CREDENTIALS ? { ...BUNDLED_CREDENTIALS, phone: '' } : undefined)
+ this.credentials = credentials
+ this.auth = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ ...(credentials && { apiId: credentials.apiId })
+ }
+ if (credentials) {
+ await saveStore({
+ credentials: seal(JSON.stringify(credentials)),
+ ownKeys: this.usingOwnKeys === true || undefined
+ }).catch(() => {})
+ } else {
+ await rm(STORE_PATH(), { force: true }).catch(() => {})
+ }
+ this.onChange?.(this.authState())
+ }
+
+ /** The signed-in client, connecting if this is the first use this launch. */
+ private async ready(): Promise<TelegramClient> {
+ if (!this.client) {
+ const stored = await loadStore()
+ const session = stored.session ? (unseal(stored.session) ?? '') : ''
+ if (!session || !this.credentials) throw new Error('Sign in to Telegram first.')
+ await this.openWithSession(session)
+ }
+ return this.client!
+ }
+
+ /** One page of Saved Messages media, newest first; `offsetId` asks for older ones. */
+ async listMediaPage(offsetId?: number, limit?: number): Promise<TelegramMediaPage> {
+ const client = await this.ready()
+ const count = Math.min(Math.max(limit ?? LIST_PAGE, 1), 100)
+ let messages
+ try {
+ messages = await client.getMessages('me', {
+ limit: count,
+ ...(offsetId !== undefined ? { offsetId } : {})
+ })
+ } catch (error) {
+ if (isAuthLossError(error)) {
+ await this.authLoss()
+ throw new TelegramFileError('auth', 'This Telegram session signed out. Sign in again.')
+ }
+ throw error
+ }
+ const items: TelegramMediaItem[] = []
+ for (const message of messages) {
+ if (!message.media) continue
+ const described = describeMedia(message.id, message.media)
+ if (!described) continue
+ const { media, ...item } = described
+ items.push({
+ ...item,
+ messageId: message.id,
+ date: message.date ?? 0,
+ thumbnail: thumbnailOf(media)
+ })
+ }
+ const exhausted = messages.length < count
+ const oldest = messages.at(-1)?.id
+ return {
+ items,
+ nextOffsetId: !exhausted && oldest !== undefined ? oldest : undefined,
+ exhausted
+ }
+ }
+
+ /** A message's media, classified and sized, as starting a download of it needs. */
+ private async locate(messageId: number): Promise<LocatedMedia> {
+ const client = await this.ready()
+ const [message] = await client.getMessages('me', { ids: [messageId] })
+ if (!message?.media) {
+ throw new Error("That message's media is gone from Saved Messages.")
+ }
+ const described = describeMedia(message.id, message.media)
+ if (!described) throw new Error("That message's media isn't downloadable.")
+ if (described.type === 'photo' && described.media instanceof Api.MessageMediaPhoto) {
+ const photo = described.media.photo
+ if (photo instanceof Api.Photo) {
+ const largest = photo.sizes
+ .filter((entry): entry is Api.PhotoSize => entry instanceof Api.PhotoSize)
+ .sort((a, b) => b.w * b.h - a.w * a.h)[0]
+ return {
+ location: new Api.InputPhotoFileLocation({
+ id: photo.id,
+ accessHash: photo.accessHash,
+ fileReference: photo.fileReference,
+ thumbSize: largest?.type ?? ''
+ }),
+ dcId: photo.dcId,
+ size: null,
+ mediaType: 'photo',
+ fileName: described.fileName,
+ mimeType: described.mimeType
+ }
+ }
+ } else if (described.media instanceof Api.MessageMediaDocument) {
+ const document = described.media.document
+ if (document instanceof Api.Document) {
+ return {
+ location: new Api.InputDocumentFileLocation({
+ id: document.id,
+ accessHash: document.accessHash,
+ fileReference: document.fileReference,
+ thumbSize: ''
+ }),
+ dcId: document.dcId,
+ size: Number(document.size),
+ mediaType: described.type,
+ fileName: described.fileName,
+ mimeType: described.mimeType
+ }
+ }
+ }
+ throw new Error("That message's media isn't downloadable.")
+ }
+
+ /** What starting a download shows before it begins: its name and size. */
+ async mediaInfo(messageId: number): Promise<{
+ fileName: string
+ totalBytes: number
+ mimeType: string
+ mediaType: TelegramMediaType
+ }> {
+ const located = await this.locate(messageId)
+ return {
+ fileName: located.fileName,
+ totalBytes: located.size ?? 0,
+ mimeType: located.mimeType,
+ mediaType: located.mediaType
+ }
+ }
+
+ /** The bytes of one media file, for a download's transfer. The location is looked up lazily
+ * (on the first request), and refetched when Telegram says its reference went stale — which
+ * it does within a day, so a paused download's resume rebuilds it rather than failing.
+ *
+ * Chunks go through teleproto's media scheduler, which owns the download sessions: it
+ * spreads requests across several properly-registered connections per data center (hand
+ * rolled senders trip Telegram's duplicate-session protection and get the login killed),
+ * retries on its own, follows data-center migrations, and speaks CDN when the file lives
+ * there. */
+ async fileSource(messageId: number): Promise<TelegramFileSource> {
+ // The returned source object's methods call back into the service through this.
+ const authLoss = (): Promise<void> => this.authLoss()
+ const client = await this.ready()
+ let located: LocatedMedia | null = null
+ const locateNow = async (): Promise<LocatedMedia> => {
+ try {
+ return await this.locate(messageId)
+ } catch (error) {
+ throw new TelegramFileError('missing', describeError(error))
+ }
+ }
+
+ // One entry per connection: `owned` marks the ones dispose() may close (a GramJS-borrowed
+ // fallback is the client's own shared sender, which must outlive this download), and
+ // `load` is its requests in flight — chunks go to the least-loaded connection.
+ interface Connection {
+ sender: MTProtoSender
+ owned: boolean
+ load: number
+ }
+ const pool: Connection[] = []
+ let sourceDisposed = false
+
+ const disposePool = async (): Promise<void> => {
+ const entries = pool.splice(0, pool.length)
+ for (const entry of entries) {
+ if (!entry.owned) continue
+ await entry.sender.disconnect().catch(() => {})
+ }
+ }
+
+ const requestChunk = async (
+ offset: number,
+ limit: number,
+ guard: AbortSignal
+ ): Promise<Buffer> => {
+ // A connection with nothing in flight takes the chunk without an await in between, so
+ // simultaneous readers spread out instead of piling onto the same one.
+ let entry: Connection | undefined
+ for (const candidate of pool) {
+ if (candidate.load === 0) {
+ entry = candidate
+ break
+ }
+ if (!entry || candidate.load < entry.load) entry = candidate
+ }
+ if (!entry || (entry.load >= 1 && pool.length < FILE_SENDER_POOL)) {
+ const created = await this.createSender(located!.dcId)
+ entry = { sender: created.sender, owned: created.owned, load: 0 }
+ pool.push(entry)
+ }
+ entry.load += 1
+ try {
+ const request = client.invokeWithSender(
+ new Api.upload.GetFile({
+ location: located!.location,
+ offset: bigInt(offset),
+ limit
+ }),
+ entry.sender
+ )
+ const result = await raceSignal(request, guard)
+ if (result instanceof Api.upload.FileCdnRedirect) {
+ throw new TelegramFileError(
+ 'other',
+ 'Telegram served this file from a CDN, which Plexo can’t fetch.'
+ )
+ }
+ return result.bytes
+ } catch (error) {
+ // A connection that hung until the guard's timeout is dropped: the next acquire
+ // builds a fresh one. (The reader's own abort leaves it be — the run is ending.)
+ if (guard.reason?.name === 'TimeoutError') {
+ const at = pool.indexOf(entry)
+ if (at >= 0) pool.splice(at, 1)
+ if (entry.owned) void entry.sender.disconnect().catch(() => {})
+ }
+ throw error
+ } finally {
+ entry.load -= 1
+ }
+ }
+
+ return {
+ get unknownSize(): boolean {
+ return located?.size === null
+ },
+ dispose: async (): Promise<void> => {
+ sourceDisposed = true
+ await disposePool()
+ },
+ refresh: async (): Promise<void> => {
+ // The reference went stale (Telegram's expire within a day): find the message again,
+ // so the next request carries a fresh reference. The transfer drives this — see
+ // telegramTransfer.ts.
+ located = await locateNow()
+ },
+ async request(offset: number, limit: number, signal: AbortSignal): Promise<Buffer> {
+ if (sourceDisposed) {
+ throw new TelegramFileError('other', 'This download was stopped.')
+ }
+ if (!located) located = await locateNow()
+ // A hung connection must not hold a reader past half a minute; the transfer retries
+ // on this connection if it recovers, or the pool replaces it if it doesn't.
+ const guard = AbortSignal.any([signal, AbortSignal.timeout(30_000)])
+ try {
+ return await requestChunk(offset, limit, guard)
+ } catch (error) {
+ if (error instanceof TelegramFileError || signal.aborted) throw error
+ if (isAuthLossError(error)) {
+ // Telegram rejected the login itself. The dialog goes back to sign-in — the stored
+ // session is dead server-side either way, so it's cleared rather than reconnected
+ // (and failing) at every launch.
+ await authLoss()
+ throw new TelegramFileError('auth', 'This Telegram session signed out. Sign in again.')
+ }
+ if (error instanceof FileMigrateError) {
+ // The connections target the wrong DC now: drop them and follow the file.
+ await disposePool()
+ located = { ...located!, dcId: error.newDc }
+ return await requestChunk(offset, limit, guard)
+ }
+ throw asFileError(error)
+ }
+ }
+ }
+ }
+
+ /** Telegram rejected the login itself (a revoked or expired session, or a killed key): the
+ * dialog goes back to sign-in, the api registration stays so the QR still leads, and the
+ * dead session is cleared so a relaunch doesn't reconnect (and fail) every time. */
+ private async authLoss(): Promise<void> {
+ this.qrAbort?.abort()
+ try {
+ await this.client?.disconnect()
+ } catch {
+ // Same.
+ }
+ this.client = undefined
+ this.phoneCodeHash = undefined
+ const credentials = this.credentials
+ this.auth = {
+ signedIn: false,
+ awaitingCode: false,
+ awaitingPassword: false,
+ bundled: BUNDLED_CREDENTIALS !== undefined,
+ hasOwnKeys: this.usingOwnKeys,
+ ...(credentials && {
+ apiId: credentials.apiId,
+ phone: credentials.phone
+ })
+ }
+ if (credentials) {
+ await saveStore({
+ credentials: seal(JSON.stringify(credentials)),
+ ownKeys: this.usingOwnKeys === true || undefined
+ }).catch(() => {})
+ } else {
+ await rm(STORE_PATH(), { force: true }).catch(() => {})
+ }
+ this.onChange?.(this.authState())
+ }
+
+ /** One fresh connection to `dcId` under this login: a GramJS exported sender, connected and
+ * authorized explicitly. The client's own connect helper is deliberately not used — it
+ * writes the authorization handshake into a shared init object, so several connections
+ * created at once clobber each other's handshake (AUTH_BYTES_INVALID). Falls back to the
+ * client's shared pooled sender when any of this fails. */
+ private async createSender(dcId: number): Promise<{ sender: MTProtoSender; owned: boolean }> {
+ const client = await this.ready()
+ const internals = client as unknown as {
+ _createExportedSender(dcId: number): MTProtoSender
+ _connection: new (options: {
+ ip: string
+ port: number
+ dcId: number
+ loggers: unknown
+ proxy: unknown
+ testServers: unknown
+ socket: unknown
+ }) => Parameters<MTProtoSender['connect']>[0]
+ _proxy: unknown
+ _log: unknown
+ testServers: unknown
+ networkSocket: unknown
+ _initRequest: Api.InvokeWithLayer
+ getSender(dcId: number): Promise<MTProtoSender>
+ }
+ let sender: MTProtoSender | undefined
+ try {
+ sender = internals._createExportedSender(dcId)
+ // The data center's address; an existing key for it says to ask the -1 test DC list
+ // instead, as the client's own connect helper does.
+ const hasKey = !!sender.authKey?.getKey()
+ const dc = await client.getDC(dcId, hasKey)
+ const connection = new internals._connection({
+ ip: dc.ipAddress,
+ port: dc.port,
+ dcId,
+ loggers: internals._log,
+ proxy: internals._proxy,
+ testServers: internals.testServers,
+ socket: internals.networkSocket
+ })
+ // A connection attempt that hangs (an unreachable DC) must not hold the download; the
+ // loser of the race is disconnected and the client's shared sender carries on instead.
+ const connecting = (async (): Promise<void> => {
+ await sender!.connect(connection, false)
+ // Another data center needs this login's authorization exported to it — per sender,
+ // with the client's own identity copied in rather than its shared init object.
+ if ((client.session.dcId ?? 0) !== dcId) {
+ const auth = await client.invoke(new Api.auth.ExportAuthorization({ dcId }))
+ const identity =
+ internals._initRequest.query instanceof Api.InitConnection
+ ? internals._initRequest.query
+ : undefined
+ await sender!.send(
+ new Api.InvokeWithLayer({
+ layer: LAYER,
+ query: new Api.InitConnection({
+ apiId: identity?.apiId ?? this.credentials!.apiId,
+ deviceModel: identity?.deviceModel ?? 'Desktop',
+ systemVersion: identity?.systemVersion ?? 'unknown',
+ appVersion: identity?.appVersion ?? 'Plexo',
+ systemLangCode: identity?.systemLangCode ?? 'en',
+ langPack: identity?.langPack ?? '',
+ langCode: identity?.langCode ?? 'en',
+ query: new Api.auth.ImportAuthorization({ id: auth.id, bytes: auth.bytes })
+ })
+ })
+ )
+ }
+ ;(sender as unknown as { dcId: number }).dcId = dcId
+ })()
+ void connecting.catch(() => {})
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error('Timed out connecting to Telegram')),
+ 15_000
+ )
+ timer.unref()
+ connecting.then(
+ () => {
+ clearTimeout(timer)
+ resolve()
+ },
+ (cause: unknown) => {
+ clearTimeout(timer)
+ reject(cause)
+ }
+ )
+ })
+ return { sender, owned: true }
+ } catch {
+ if (sender) void sender.disconnect().catch(() => {})
+ try {
+ return { sender: await internals.getSender(dcId), owned: false }
+ } catch (cause) {
+ throw new TelegramFileError('network', describeError(cause))
+ }
+ }
+ }
+}
+
+function userNameOf(user: Api.TypeUser): string | undefined {
+ if (user instanceof Api.User) {
+ return [user.firstName, user.lastName].filter(Boolean).join(' ') || user.username || undefined
+ }
+ return undefined
+}
diff --git a/src/main/testKnobs.ts b/src/main/testKnobs.ts
index d5bcb05..6a7d7f1 100644
--- a/src/main/testKnobs.ts
+++ b/src/main/testKnobs.ts
@@ -13,6 +13,11 @@ function positiveNumber(name: string, fallback: number): number {
export const testKnobs = {
userDataDir: env['PLEXO_USER_DATA'],
+ /** The Telegram service's e2e double (src/main/telegram/fake.ts): instant sign-in, fake
+ * Saved Messages media, and a file source that inflicts the DC's faults on demand. */
+ telegramFake: env['PLEXO_E2E_TELEGRAM_FAKE'] === '1',
+ /** Milliseconds the fake source's every chunk takes — a pause window for tests. */
+ telegramDelayMs: positiveNumber('PLEXO_E2E_TELEGRAM_DELAY_MS', 0),
/** Keeps the window off-screen so a test run doesn't pop windows up over the desktop. */
hideWindow: env['PLEXO_E2E_HIDE_WINDOW'] === '1',
blockBytes: positiveNumber('PLEXO_E2E_BLOCK_BYTES', 8 * 1024 * 1024),
diff --git a/src/preload/index.ts b/src/preload/index.ts
index fa5b176..137773c 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -7,6 +7,8 @@ import type {
InitialState,
MagnetCheckStatus,
NetworkInterfaceInfo,
+ TelegramAuthState,
+ TelegramCredentials,
UpdateState,
UsenetServerInput
} from '../shared/types'
@@ -67,6 +69,23 @@ const plexoApi = {
saveUsenetServer: (server: UsenetServerInput) => invoke('saveUsenetServer', server),
testUsenetServer: (server: UsenetServerInput) => invoke('testUsenetServer', server),
+ telegramState: () => invoke('telegramState'),
+ telegramStartLogin: (credentials: TelegramCredentials) =>
+ invoke('telegramStartLogin', credentials),
+ telegramStartQrLogin: () => invoke('telegramStartQrLogin'),
+ telegramSubmitCode: (code: string) => invoke('telegramSubmitCode', code),
+ telegramSubmitPassword: (password: string) => invoke('telegramSubmitPassword', password),
+ telegramLogout: () => invoke('telegramLogout'),
+ telegramListMedia: (offsetId?: number, limit?: number) =>
+ invoke('telegramListMedia', offsetId, limit),
+
+ /** Where Telegram sign-in stands changed (see TelegramAuthState). */
+ onTelegramAuth: (callback: (state: TelegramAuthState) => void): (() => void) => {
+ const listener = (_event: IpcRendererEvent, state: TelegramAuthState): void => callback(state)
+ ipcRenderer.on(IpcChannels.telegramAuthChanged, listener)
+ return () => ipcRenderer.removeListener(IpcChannels.telegramAuthChanged, listener)
+ },
+
/** pendingLinks() has the new link. */
onLinkReceived: (callback: () => void): (() => void) => {
const listener = (): void => callback()
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 8d29d13..5ae4c71 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -3,6 +3,7 @@ import { DownloadActionsProvider } from './components/DownloadActionsProvider'
import { NetworkBindingDialog } from './components/NetworkBindingDialog'
import { NewDownloadDialog } from './components/NewDownloadDialog'
import { StatusBar } from './components/StatusBar'
+import { TelegramDialog } from './components/TelegramDialog'
import { TitleBar } from './components/TitleBar'
import { TooltipProvider } from './components/ui/tooltip'
import { useDownloadEvents } from './hooks/useDownloadEvents'
@@ -68,6 +69,7 @@ function App(): React.JSX.Element {
</div>
<StatusBar />
<NewDownloadDialog />
+ <TelegramDialog />
<NetworkBindingDialog />
</div>
</DownloadActionsProvider>
diff --git a/src/renderer/src/components/TelegramDialog.tsx b/src/renderer/src/components/TelegramDialog.tsx
new file mode 100644
index 0000000..1511deb
--- /dev/null
+++ b/src/renderer/src/components/TelegramDialog.tsx
@@ -0,0 +1,558 @@
+import type { TelegramAuthState, TelegramMediaItem, TelegramMediaType } from '@shared/types'
+import { cn } from 'cn'
+import {
+ Clapperboard,
+ File,
+ Film,
+ FolderOpen,
+ Image as ImageIcon,
+ Music,
+ RotateCw,
+ Send,
+ Smile,
+ X
+} from 'lucide-react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
+import { describeError, formatBytes, formatWhen } from '../utils/format'
+import { Button } from './ui/button'
+import { Checkbox } from './ui/checkbox'
+import { Dialog, DialogContent, DialogTitle } from './ui/dialog'
+import { Input } from './ui/input'
+import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
+
+/** Telegram, as Plexo reaches it: the user's own session, and only Saved Messages — the "me"
+ * peer every request here is hard-pinned to. Signed in, it lists the media there; a pick of it
+ * starts downloads the manager runs like any other. */
+
+export function TelegramDialog(): React.JSX.Element {
+ const open = useAppStore((store) => store.telegramOpen)
+ const close = useAppStore((store) => store.closeTelegram)
+
+ return (
+ <Dialog open={open} disablePointerDismissal onOpenChange={(next) => !next && close()}>
+ <DialogContent
+ showCloseButton={false}
+ className="flex max-h-[calc(100%-2rem)] flex-col gap-0 p-0 sm:max-w-[560px]"
+ >
+ {open && <TelegramPanel onDone={close} />}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function TelegramPanel({ onDone }: { onDone: () => void }): React.JSX.Element {
+ const [auth, setAuth] = useState<TelegramAuthState | null>(null)
+
+ useEffect(() => {
+ let stale = false
+ void window.plexo.telegramState().then((state) => {
+ if (!stale) setAuth(state)
+ })
+ const unsubscribe = window.plexo.onTelegramAuth((state) => setAuth(state))
+ return () => {
+ stale = true
+ unsubscribe()
+ }
+ }, [])
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="border-b-[0.5px] border-border px-5 py-4">
+ <div className="flex items-center justify-between gap-3">
+ <DialogTitle>Telegram — Saved Messages</DialogTitle>
+ <div className="flex items-center gap-1">
+ {auth?.signedIn && <SignOut />}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Close"
+ onClick={onDone}
+ >
+ <X aria-hidden />
+ </Button>
+ </div>
+ </div>
+ <p className="mt-1.5 text-[12px] leading-[1.5] text-[var(--text-secondary)]">
+ Plexo is an unofficial Telegram client: signing in grants it full access to your account,
+ though it reads nothing but Saved Messages.
+ </p>
+ </div>
+ {auth === null ? (
+ <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">
+ Checking Telegram…
+ </div>
+ ) : auth.signedIn ? (
+ <SavedMessagesBrowser onDone={onDone} />
+ ) : (
+ <TelegramLogin auth={auth} />
+ )}
+ </div>
+ )
+}
+
+function SignOut(): React.JSX.Element {
+ const [busy, setBusy] = useState(false)
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={busy}
+ onClick={() => {
+ setBusy(true)
+ void window.plexo.telegramLogout().catch(() => setBusy(false))
+ }}
+ >
+ Sign out
+ </Button>
+ )
+}
+
+const fieldLabelClass = 'w-24 shrink-0 text-[12.5px] text-[var(--text-secondary)]'
+const errorClass = 'text-[12px] leading-[1.4] text-[var(--color-danger)]'
+
+/** The sign-in steps, driven by what main reports: a QR to scan (default, when credentials to
+ * power one exist — Plexo's own in a bundled release, else the user's from an earlier
+ * sign-in), then the code or the two-step-verification password if those flows are used. */
+function TelegramLogin({ auth }: { auth: TelegramAuthState }): React.JSX.Element {
+ const canQr = auth.bundled === true || auth.hasOwnKeys === true
+ const [mode, setMode] = useState<'qr' | 'form'>(canQr ? 'qr' : 'form')
+ const [apiId, setApiId] = useState(auth.apiId ? String(auth.apiId) : '')
+ const [apiHash, setApiHash] = useState('')
+ const [phone, setPhone] = useState(auth.phone ?? '')
+ const [code, setCode] = useState('')
+ const [password, setPassword] = useState('')
+ const [busy, setBusy] = useState(false)
+ // Bundled builds lead with Plexo's own credentials; the user's own api keys are one toggle
+ // away — the api_hash never comes prefilled (main never sends it), and stored own keys keep
+ // winning while the fields stay empty (see main's startLogin).
+ const [showApi, setShowApi] = useState(auth.bundled !== true)
+
+ const run = (work: () => Promise<void>): void => {
+ setBusy(true)
+ void work().finally(() => setBusy(false))
+ }
+
+ const startQr = useCallback((): void => {
+ // Failures arrive as state pushes from main; the dialog just shows them.
+ void window.plexo.telegramStartQrLogin().catch(() => {})
+ }, [])
+
+ useEffect(() => {
+ if (mode === 'qr') startQr()
+ }, [mode, startQr])
+
+ if (auth.awaitingPassword) {
+ return (
+ <form
+ className="flex flex-col gap-3 px-5 py-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ run(() => window.plexo.telegramSubmitPassword(password))
+ }}
+ >
+ <p className="text-[12.5px] leading-[1.5]">
+ Your account has two-step verification. Enter its password.
+ </p>
+ <div className="flex items-center gap-3">
+ <label htmlFor="tg-password" className={fieldLabelClass}>
+ Password
+ </label>
+ <Input
+ id="tg-password"
+ type="password"
+ value={password}
+ onChange={(event) => setPassword(event.target.value)}
+ autoFocus
+ />
+ </div>
+ {auth.error && (
+ <p role="alert" className={errorClass}>
+ {auth.error}
+ </p>
+ )}
+ <Button type="submit" disabled={busy || password.length === 0}>
+ {busy ? 'Signing in…' : 'Sign in'}
+ </Button>
+ </form>
+ )
+ }
+
+ if (auth.awaitingCode) {
+ return (
+ <form
+ className="flex flex-col gap-3 px-5 py-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ run(() => window.plexo.telegramSubmitCode(code))
+ }}
+ >
+ <p className="text-[12.5px] leading-[1.5]">
+ Telegram sent a code to <span className="font-medium">{auth.phone}</span>. Enter it here.
+ </p>
+ <div className="flex items-center gap-3">
+ <label htmlFor="tg-code" className={fieldLabelClass}>
+ Code
+ </label>
+ <Input
+ id="tg-code"
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ inputMode="numeric"
+ autoFocus
+ />
+ </div>
+ {auth.error && (
+ <p role="alert" className={errorClass}>
+ {auth.error}
+ </p>
+ )}
+ <Button type="submit" disabled={busy || code.trim().length === 0}>
+ {busy ? 'Checking…' : 'Continue'}
+ </Button>
+ </form>
+ )
+ }
+
+ if (mode === 'qr') {
+ return (
+ <div className="flex flex-col items-center gap-3 px-5 py-4">
+ {auth.qrDataUrl ? (
+ <img
+ src={auth.qrDataUrl}
+ alt="Telegram login QR code"
+ className="size-[232px] rounded-lg border-[0.5px] border-border bg-white p-1"
+ />
+ ) : (
+ <div
+ aria-live="polite"
+ className="flex size-[232px] items-center justify-center rounded-lg border-[0.5px] border-border font-mono text-[11.5px] text-muted-foreground"
+ >
+ {auth.error ? '—' : 'Preparing QR…'}
+ </div>
+ )}
+ <p className="text-center text-[12.5px] leading-[1.5]">
+ Open Telegram on your phone →{' '}
+ <span className="font-medium">Settings → Devices → Link Desktop Device</span>, and scan
+ this. The code refreshes itself until scanned.
+ </p>
+ {auth.error && (
+ <>
+ <p role="alert" className={cn('text-center', errorClass)}>
+ {auth.error}
+ </p>
+ <Button type="button" variant="outline" size="xs" onClick={startQr}>
+ Retry
+ </Button>
+ </>
+ )}
+ {!auth.error && (
+ <p aria-live="polite" className="font-mono text-[11px] text-muted-foreground">
+ Waiting for scan…
+ </p>
+ )}
+ <Button type="button" variant="ghost" size="xs" onClick={() => setMode('form')}>
+ Sign in with a phone number instead
+ </Button>
+ </div>
+ )
+ }
+
+ const needsApiFields = showApi
+ return (
+ <form
+ className="flex flex-col gap-3 px-5 py-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ run(() =>
+ window.plexo.telegramStartLogin({
+ apiId: Number(apiId),
+ apiHash,
+ phone
+ })
+ )
+ }}
+ >
+ {needsApiFields ? (
+ <p className="text-[12.5px] leading-[1.5]">
+ Plexo needs an <span className="font-medium">api_id</span> and{' '}
+ <span className="font-medium">api_hash</span> of your own: create an app at
+ my.telegram.org → API development tools, and enter them here with your phone number.
+ </p>
+ ) : (
+ <p className="text-[12.5px] leading-[1.5]">
+ Enter your phone number and Telegram will send a login code.
+ </p>
+ )}
+ {needsApiFields && (
+ <>
+ <div className="flex items-center gap-3">
+ <label htmlFor="tg-api-id" className={fieldLabelClass}>
+ api_id
+ </label>
+ <Input
+ id="tg-api-id"
+ value={apiId}
+ onChange={(event) => setApiId(event.target.value)}
+ inputMode="numeric"
+ autoFocus
+ />
+ </div>
+ <div className="flex items-center gap-3">
+ <label htmlFor="tg-api-hash" className={fieldLabelClass}>
+ api_hash
+ </label>
+ <Input
+ id="tg-api-hash"
+ value={apiHash}
+ onChange={(event) => setApiHash(event.target.value)}
+ placeholder={auth.hasOwnKeys ? 'stored — leave empty to keep it' : undefined}
+ />
+ </div>
+ </>
+ )}
+ <div className="flex items-center gap-3">
+ <label htmlFor="tg-phone" className={fieldLabelClass}>
+ Phone
+ </label>
+ <Input
+ id="tg-phone"
+ value={phone}
+ onChange={(event) => setPhone(event.target.value)}
+ placeholder="+1 555 010 1234"
+ inputMode="tel"
+ autoFocus={!needsApiFields}
+ />
+ </div>
+ {(auth.bundled === true || auth.hasOwnKeys === true) && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => setShowApi((shown) => !shown)}
+ >
+ {showApi ? 'Use Plexo’s api keys instead' : 'Use your own api keys (advanced)'}
+ </Button>
+ )}
+ {auth.error && (
+ <p role="alert" className={errorClass}>
+ {auth.error}
+ </p>
+ )}
+ <Button type="submit" disabled={busy || !phone || (needsApiFields && (!apiId || !apiHash))}>
+ {busy ? 'Sending code…' : 'Send code'}
+ </Button>
+ {canQr && (
+ <Button type="button" variant="ghost" size="xs" onClick={() => setMode('qr')}>
+ Use the QR code instead
+ </Button>
+ )}
+ </form>
+ )
+}
+
+const TYPE_ICON: Record<TelegramMediaType, React.ReactNode> = {
+ photo: <ImageIcon aria-hidden className="size-4" />,
+ video: <Film aria-hidden className="size-4" />,
+ audio: <Music aria-hidden className="size-4" />,
+ voice: <Music aria-hidden className="size-4" />,
+ document: <File aria-hidden className="size-4" />,
+ animation: <Clapperboard aria-hidden className="size-4" />,
+ sticker: <Smile aria-hidden className="size-4" />
+}
+
+function itemSize(item: TelegramMediaItem): string {
+ if (item.totalBytes > 0) return formatBytes(item.totalBytes)
+ if (item.width && item.height) return `${item.width}×${item.height}`
+ return 'Photo'
+}
+
+/** Saved Messages' downloadable media: pages of it, oldest page last, each row ticked to be
+ * downloaded. Starting them hands each to the manager, queue and all. */
+function SavedMessagesBrowser({ onDone }: { onDone: () => void }): React.JSX.Element {
+ const destinationDir = useAppStore((store) => store.destinationDir)
+ const setDestinationDir = useAppStore((store) => store.setDestinationDir)
+ const interfaces = useAppStore((store) => store.interfaces)
+ const loadInterfaces = useAppStore((store) => store.loadInterfaces)
+
+ const [items, setItems] = useState<TelegramMediaItem[]>([])
+ const [nextOffsetId, setNextOffsetId] = useState<number | undefined>(undefined)
+ const [exhausted, setExhausted] = useState(false)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+ const [selected, setSelected] = useState<Set<number>>(new Set())
+ const [starting, setStarting] = useState(false)
+ const startedRef = useRef(false)
+ // Read on a clock, not in render (impure), like the downloads list's "when"s.
+ const [now, setNow] = useState(() => Date.now())
+ useEffect(() => {
+ const interval = setInterval(() => setNow(Date.now()), 30_000)
+ return () => clearInterval(interval)
+ }, [])
+
+ const loadPage = useCallback(async (olderThan?: number): Promise<void> => {
+ setLoading(true)
+ setError(null)
+ try {
+ const page = await window.plexo.telegramListMedia(olderThan)
+ setItems((previous) => (olderThan === undefined ? page.items : [...previous, ...page.items]))
+ setNextOffsetId(page.nextOffsetId)
+ setExhausted(page.exhausted)
+ } catch (cause) {
+ setError(describeError(cause))
+ } finally {
+ setLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ if (startedRef.current) return
+ startedRef.current = true
+ void loadPage()
+ if (interfaces.length === 0) void loadInterfaces()
+ }, [loadPage, interfaces.length, loadInterfaces])
+
+ const chooseDestination = async (): Promise<void> => {
+ const dir = await window.plexo.chooseDestinationFolder(destinationDir).catch(() => null)
+ if (dir) setDestinationDir(dir)
+ }
+
+ const downloadSelected = (): void => {
+ if (selected.size === 0) return
+ setStarting(true)
+ const interfaceIds = interfaces.map((iface) => iface.id)
+ const picks = items.filter((item) => selected.has(item.messageId))
+ for (const item of picks) {
+ window.plexo
+ .startDownload({
+ kind: 'telegram',
+ messageId: item.messageId,
+ mediaType: item.type,
+ url: `telegram://saved-messages/${item.messageId}`,
+ destinationDir,
+ suggestedFileName: item.fileName,
+ totalBytes: item.totalBytes,
+ supportsRanges: true,
+ interfaceIds,
+ etag: null,
+ lastModified: null
+ })
+ .catch((cause) => setError(describeError(cause)))
+ }
+ onDone()
+ }
+
+ const toggle = (messageId: number, on: boolean): void =>
+ setSelected((previous) => {
+ const next = new Set(previous)
+ if (on) next.add(messageId)
+ else next.delete(messageId)
+ return next
+ })
+
+ const picked = items.filter((item) => selected.has(item.messageId))
+ const pickedBytes = picked.reduce((sum, item) => sum + item.totalBytes, 0)
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {/* Always visible above the scrolling list: the chat may have gained files while this
+ was open, so the list can be asked for its newest page again. Ticks stay on rows
+ that are still there. */}
+ <div className="flex items-center justify-between px-5 pt-2">
+ <span className="font-mono text-[11px] leading-none text-muted-foreground">
+ {items.length > 0 && `${items.length} ${items.length === 1 ? 'item' : 'items'}`}
+ </span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Refresh"
+ disabled={loading}
+ onClick={() => void loadPage()}
+ >
+ <RotateCw aria-hidden />
+ </Button>
+ }
+ />
+ <TooltipContent>Refresh — list the newest files again</TooltipContent>
+ </Tooltip>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-3">
+ {items.length === 0 && !loading && !error ? (
+ <p className="py-8 text-center text-[12.5px] text-muted-foreground">
+ No downloadable media in Saved Messages.
+ </p>
+ ) : (
+ <div role="group" aria-label="Saved Messages media">
+ {items.map((item) => (
+ <label
+ key={item.messageId}
+ className="flex items-center gap-3 rounded-lg px-1 py-1.5"
+ >
+ <Checkbox
+ checked={selected.has(item.messageId)}
+ onCheckedChange={(checked) => toggle(item.messageId, checked)}
+ />
+ {item.thumbnail ? (
+ <img
+ src={item.thumbnail}
+ alt=""
+ className="size-9 shrink-0 rounded-md border-[0.5px] border-border object-cover"
+ />
+ ) : (
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-md border-[0.5px] border-border bg-secondary text-muted-foreground">
+ {TYPE_ICON[item.type]}
+ </span>
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[12.5px] font-medium">{item.fileName}</span>
+ <span className="block font-mono text-[11px] text-[var(--text-secondary)]">
+ {item.type} · {itemSize(item)} · {formatWhen(item.date * 1000, now)}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ )}
+ {loading && (
+ <p className="py-3 text-center font-mono text-[11px] text-muted-foreground">Loading…</p>
+ )}
+ {error && (
+ <p role="alert" className={cn('py-2 text-center', errorClass)}>
+ {error}
+ </p>
+ )}
+ {!loading && !exhausted && nextOffsetId !== undefined && (
+ <div className="flex justify-center py-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => void loadPage(nextOffsetId)}
+ >
+ Load older
+ </Button>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-2 border-t-[0.5px] border-border px-5 py-3">
+ <Button type="button" variant="ghost" size="xs" onClick={() => void chooseDestination()}>
+ <FolderOpen data-icon="inline-start" />
+ {destinationDir.split(/[\\/]/).pop() || destinationDir}
+ </Button>
+ <div className="flex-1" />
+ <Button type="button" disabled={starting || selected.size === 0} onClick={downloadSelected}>
+ <Send data-icon="inline-start" />
+ {selected.size === 0
+ ? 'Download'
+ : `Download ${selected.size}${pickedBytes > 0 ? ` · ${formatBytes(pickedBytes)}` : ''}`}
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/src/renderer/src/screens/CompleteScreen.tsx b/src/renderer/src/screens/CompleteScreen.tsx
index 2493dae..74d0689 100644
--- a/src/renderer/src/screens/CompleteScreen.tsx
+++ b/src/renderer/src/screens/CompleteScreen.tsx
@@ -164,8 +164,20 @@ export function CompleteScreen({
{ label: 'Networks', value: String(groups.length) },
// The most it ran at once: streams that didn't make it faster were closed along the way.
{
- label: isTorrent ? 'Peers' : download.kind === 'nzb' ? 'Connections' : 'Streams',
- value: String(isTorrent ? download.peakPeers : download.peakStreams)
+ label: isTorrent
+ ? 'Peers'
+ : download.kind === 'telegram'
+ ? 'Readers'
+ : download.kind === 'nzb'
+ ? 'Connections'
+ : 'Streams',
+ value: String(
+ isTorrent
+ ? download.peakPeers
+ : download.kind === 'telegram'
+ ? download.peakReaders
+ : download.peakStreams
+ )
}
].map((stat, index) => (
<div
diff --git a/src/renderer/src/screens/DownloadsScreen.tsx b/src/renderer/src/screens/DownloadsScreen.tsx
index 7f23071..258f4ab 100644
--- a/src/renderer/src/screens/DownloadsScreen.tsx
+++ b/src/renderer/src/screens/DownloadsScreen.tsx
@@ -1,5 +1,5 @@
import type { DownloadState, FinishedDownload } from '@shared/types'
-import { ChevronRight, Plus, X } from 'lucide-react'
+import { ChevronRight, Plus, Send, X } from 'lucide-react'
import { cn } from 'cn'
import { Fragment, memo, useCallback, useEffect, useState } from 'react'
import { DownloadContextMenu } from '../components/DownloadContextMenu'
@@ -91,6 +91,7 @@ export function DownloadsScreen(): React.JSX.Element {
const history = useAppStore((store) => store.history)
const setView = useAppStore((store) => store.setView)
const openNewDownload = useAppStore((store) => store.openNewDownload)
+ const openTelegram = useAppStore((store) => store.openTelegram)
const filter = useAppStore((store) => store.downloadFilter)
const setFilter = useAppStore((store) => store.setDownloadFilter)
const [selected, setSelected] = useState<Set<string>>(new Set())
@@ -209,6 +210,10 @@ export function DownloadsScreen(): React.JSX.Element {
setLimitsOpen(true)
}}
/>
+ <Button type="button" variant="secondary" onClick={() => openTelegram()}>
+ <Send data-icon="inline-start" />
+ Telegram
+ </Button>
<Button type="button" onClick={() => openNewDownload()}>
<Plus data-icon="inline-start" />
New download
@@ -369,6 +374,7 @@ function EmptyState(): React.JSX.Element {
)
const loadInterfaces = useAppStore((store) => store.loadInterfaces)
const openNewDownload = useAppStore((store) => store.openNewDownload)
+ const openTelegram = useAppStore((store) => store.openTelegram)
return (
<div className="flex flex-col items-center gap-4 px-5 pt-16 pb-10 text-center">
@@ -399,11 +405,17 @@ function EmptyState(): React.JSX.Element {
<div className="max-w-[380px] text-[12.5px] leading-[1.6] text-[var(--text-secondary)]">
Paste a link ({PASTE_SHORTCUT}) or drop a .torrent or .nzb anywhere in this window.
</div>
- <Button type="button" className="mt-1" onClick={() => openNewDownload()}>
- <Plus data-icon="inline-start" />
- New download
- <span className="ml-1 font-mono text-[11px] opacity-70">{NEW_SHORTCUT}</span>
- </Button>
+ <div className="mt-1 flex gap-2">
+ <Button type="button" variant="secondary" onClick={() => openTelegram()}>
+ <Send data-icon="inline-start" />
+ Telegram
+ </Button>
+ <Button type="button" onClick={() => openNewDownload()}>
+ <Plus data-icon="inline-start" />
+ New download
+ <span className="ml-1 font-mono text-[11px] opacity-70">{NEW_SHORTCUT}</span>
+ </Button>
+ </div>
</>
)}
</div>
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index f7d3454..d9b7c7e 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -44,6 +44,10 @@ interface AppStore {
downloadSchedule: DownloadSchedule | undefined
/** The New download dialog, over whatever the window shows. */
newDownloadOpen: boolean
+ /** The Telegram dialog: sign-in, then the Saved Messages media browser. */
+ telegramOpen: boolean
+ openTelegram: () => void
+ closeTelegram: () => void
/** Persisted — how many downloads run at once; the rest wait in the queue. */
downloadsAtOnce: number
/** Persisted — the speed limits (see AppSettings). */
@@ -128,6 +132,9 @@ export const useAppStore = create<AppStore>((set, get) => ({
setDownloadFilter: (downloadFilter) => set({ downloadFilter }),
downloadSchedule: initial.downloadSchedule,
newDownloadOpen: false,
+ telegramOpen: false,
+ openTelegram: () => set({ telegramOpen: true }),
+ closeTelegram: () => set({ telegramOpen: false }),
downloadsAtOnce: initial.downloadsAtOnce,
speedLimit: initial.speedLimit,
slowMode: initial.slowMode,
diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.ts
index ad0ec5b..d67f376 100644
--- a/src/renderer/src/utils/format.ts
+++ b/src/renderer/src/utils/format.ts
@@ -236,12 +236,23 @@ export interface TorrentNetworkGroup extends TorrentDownloadNetwork {
export type NetworkGroup = HttpNetworkGroup | TorrentNetworkGroup
export function groupByNetwork(download: DownloadState): NetworkGroup[] {
- if (download.kind !== 'torrent') {
+ if (download.kind === 'http' || download.kind === 'nzb') {
return download.networks.map((network) => ({
...network,
streams: download.streams.filter((stream) => stream.interfaceId === network.id)
}))
}
+ if (download.kind === 'telegram') {
+ // Telegram isn't reached through any one network the OS picks for it, so its readers are
+ // shown as the rows a download's networks table knows (their bytes attributed per block).
+ return download.networks.map((network) => ({
+ ...network,
+ transfer: 'http',
+ streams: download.readers
+ .filter((reader) => reader.interfaceId === network.id)
+ .map((reader) => ({ ...reader, rangeStart: 0, rangeEnd: null }))
+ }))
+ }
return download.networks.map((network) => ({
...network,
peers: download.peers.filter((peer) => peer.interfaceId === network.id)
diff --git a/src/shared/downloadUpdate.ts b/src/shared/downloadUpdate.ts
index d51479f..effcdc7 100644
--- a/src/shared/downloadUpdate.ts
+++ b/src/shared/downloadUpdate.ts
@@ -3,6 +3,7 @@ import type {
DownloadUpdate,
HttpDownloadUpdate,
NzbDownloadUpdate,
+ TelegramDownloadUpdate,
TorrentDownloadUpdate
} from './types'
@@ -48,9 +49,11 @@ export function applyDownloadUpdate(
)
return blocks ? { ...state, blocks, seq } : current
}
- const { state, blocks: changed } = update as HttpDownloadUpdate
+ // HTTP and Telegram downloads both keep blocks; kinds must match so a snapshot of one
+ // never lands on a live download of the other.
+ const { state, blocks: changed } = update as HttpDownloadUpdate | TelegramDownloadUpdate
const blocks = withChanged(
- same?.kind === 'http' ? same.blocks : undefined,
+ same?.kind === 'http' || same?.kind === 'telegram' ? same.blocks : undefined,
changed,
state.totalBlocks
)
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index 8bbed01..b533b12 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -36,6 +36,14 @@ export const IpcChannels = {
updateState: 'update:state',
updateStateChanged: 'update:state-changed',
showUpdateMenu: 'update:show-menu',
+ telegramState: 'telegram:state',
+ telegramStartLogin: 'telegram:start-login',
+ telegramStartQrLogin: 'telegram:start-qr-login',
+ telegramSubmitCode: 'telegram:submit-code',
+ telegramSubmitPassword: 'telegram:submit-password',
+ telegramLogout: 'telegram:logout',
+ telegramListMedia: 'telegram:list-media',
+ telegramAuthChanged: 'telegram:auth-changed',
usenetServer: 'usenet:server',
saveUsenetServer: 'usenet:save-server',
testUsenetServer: 'usenet:test-server'
diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.ts
index c18330a..98c408b 100644
--- a/src/shared/ipc-contract.ts
+++ b/src/shared/ipc-contract.ts
@@ -6,6 +6,9 @@ import type {
PendingLink,
ProbeResult,
StartDownloadRequest,
+ TelegramAuthState,
+ TelegramCredentials,
+ TelegramMediaPage,
TorrentFileEntry,
UpdateState,
UsenetServer,
@@ -69,6 +72,20 @@ export interface IpcContract {
resumeFromLink: { args: [linkId: string, downloadId: string]; result: void }
/** Forgets the sign-in of a link that won't be started. */
dismissLink: { args: [id: string]; result: void }
+ /** Where Telegram sign-in stands (see TelegramAuthState). */
+ telegramState: { args: []; result: TelegramAuthState }
+ /** Connects with the user's own credentials and sends a login code to `credentials.phone`. */
+ telegramStartLogin: { args: [credentials: TelegramCredentials]; result: void }
+ /** Starts a QR sign-in: the dialog gets rotating login tokens to render, until scanned. */
+ telegramStartQrLogin: { args: []; result: void }
+ /** Accepts the login code Telegram sent. Stays awaiting when it was wrong. */
+ telegramSubmitCode: { args: [code: string]; result: void }
+ /** Accepts the two-step-verification password. Stays awaiting when it was wrong. */
+ telegramSubmitPassword: { args: [password: string]; result: void }
+ /** Signs out and forgets the session. */
+ telegramLogout: { args: []; result: void }
+ /** One page of Saved Messages media, `offsetId` messages back (unset: the newest). */
+ telegramListMedia: { args: [offsetId?: number, limit?: number]; result: TelegramMediaPage }
/** The news server NZB downloads come from; null until one is set up. */
usenetServer: { args: []; result: UsenetServer | null }
saveUsenetServer: { args: [server: UsenetServerInput]; result: UsenetServer }
diff --git a/src/shared/taskbarProgress.ts b/src/shared/taskbarProgress.ts
index 921f300..2fc3c89 100644
--- a/src/shared/taskbarProgress.ts
+++ b/src/shared/taskbarProgress.ts
@@ -11,7 +11,7 @@ export interface TaskbarDownload {
status: DownloadStatus
totalBytes: number
bytesDownloaded: number
- kind?: 'http' | 'torrent' | 'nzb'
+ kind?: 'http' | 'torrent' | 'nzb' | 'telegram'
skippedBytes?: number
missingBytes?: number
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 08592f7..dc15448 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -181,6 +181,85 @@ export interface NzbSegmentState extends WorkUnitState {
export type DownloadUnitState = HttpBlockState | TorrentPieceState | NzbSegmentState
+/** What a Saved Messages attachment is, as the media browser groups it. */
+export type TelegramMediaType =
+ 'photo' | 'video' | 'audio' | 'voice' | 'document' | 'animation' | 'sticker'
+
+/** One media attachment in Saved Messages. */
+export interface TelegramMediaItem {
+ /** The message's id in Saved Messages: what a download of it is started by. */
+ messageId: number
+ type: TelegramMediaType
+ fileName: string
+ mimeType: string
+ /** 0 for photos: Telegram doesn't reveal a photo's byte size ahead of its download. */
+ totalBytes: number
+ width?: number
+ height?: number
+ /** Unix seconds the message was sent. */
+ date: number
+ /** Inline JPEG thumbnail as a data URL, when the message carries one small enough to embed. */
+ thumbnail?: string
+}
+
+/** One page of Saved Messages media, oldest entry last, for the browser's paging. */
+export interface TelegramMediaPage {
+ items: TelegramMediaItem[]
+ /** The oldest message id seen; the next page asks for older ones than it. Unset when exhausted. */
+ nextOffsetId?: number
+ exhausted: boolean
+}
+
+/** The user's own Telegram API credentials (my.telegram.org) and phone, as the login form
+ * sends them. */
+export interface TelegramCredentials {
+ apiId: number
+ apiHash: string
+ phone: string
+}
+
+/** Where Telegram sign-in stands, as the login dialog shows it. Credentials are the user's own
+ * api_id/api_hash from my.telegram.org — unless the release build bundles Plexo's own
+ * (`bundled`), in which case the api form becomes an advanced fallback. The api_hash itself
+ * never crosses to the window: it's the bundled secret in release builds, and the user's own
+ * is a stored secret either way. */
+export interface TelegramAuthState {
+ signedIn: boolean
+ /** The release build ships Plexo's own credentials: sign in with a phone (or the QR) alone. */
+ bundled?: boolean
+ /** The stored api registration is the user's own (not the bundled pair) — its api_hash field
+ * can stay empty and the stored keys keep winning. */
+ hasOwnKeys?: boolean
+ apiId?: number
+ phone?: string
+ /** A code was sent and not yet accepted: the dialog asks for it. */
+ awaitingCode: boolean
+ /** The account has two-step verification: the dialog asks for its password. */
+ awaitingPassword: boolean
+ /** A QR login is live: `qrDataUrl` holds the current code, which Telegram rotates. */
+ awaitingQr?: boolean
+ qrDataUrl?: string
+ /** The signed-in account's name, as Telegram reports it. */
+ userName?: string
+ error?: string
+}
+
+/** A live Telegram connection fetching the file. Like an HTTP stream without its range: each
+ * reader takes blocks as they free up. */
+export interface TelegramReaderState {
+ id: number
+ /** The network its bytes are attributed to (see TelegramDownloadState). */
+ interfaceId: string
+ bytesDownloaded: number
+ speedBytesPerSec: number
+ status: 'pending' | 'downloading' | 'retrying' | 'paused' | 'completed' | 'cancelled'
+ currentBlockIndex?: number
+}
+
+export interface TelegramDownloadNetwork extends DownloadNetworkBase {
+ transfer: 'telegram'
+}
+
/**
* - on: in use.
* - off: the user switched it off. A network that turns up mid-download starts off.
@@ -222,7 +301,7 @@ export interface TorrentDownloadNetwork extends DownloadNetworkBase {
uploadSpeedBytesPerSec: number
}
-export type DownloadNetwork = HttpDownloadNetwork | TorrentDownloadNetwork
+export type DownloadNetwork = HttpDownloadNetwork | TorrentDownloadNetwork | TelegramDownloadNetwork
interface DownloadStateBase {
id: string
@@ -290,6 +369,19 @@ export interface TorrentDownloadState extends DownloadStateBase {
uploadSpeedBytesPerSec: number
}
+export interface TelegramDownloadState extends DownloadStateBase {
+ kind: 'telegram'
+ networks: TelegramDownloadNetwork[]
+ /** The connections fetching from Telegram. Unlike HTTP streams they aren't pinned to a
+ * network — Telegram is always reached the way the OS routes — so their bytes are attributed
+ * to whichever network was first-enabled as each block was claimed. */
+ readers: TelegramReaderState[]
+ peakReaders: number
+ blocks: HttpBlockState[]
+ totalBlocks: number
+ blockSizeBytes: number
+}
+
/** One file of an NZB download. */
export interface NzbFileState {
/** As it is saved, in the download's folder. */
@@ -319,13 +411,15 @@ export interface NzbDownloadState extends DownloadStateBase {
server: string
}
-export type DownloadState = HttpDownloadState | TorrentDownloadState | NzbDownloadState
+export type DownloadState =
+ HttpDownloadState | TorrentDownloadState | TelegramDownloadState | NzbDownloadState
/** A finished download as history keeps it: its state without the work units and connections,
* which only a running download needs. */
export type FinishedDownload = (
| Omit<HttpDownloadState, 'blocks' | 'streams'>
| Omit<TorrentDownloadState, 'pieces' | 'peers'>
+ | Omit<TelegramDownloadState, 'blocks' | 'readers'>
| Omit<NzbDownloadState, 'blocks' | 'streams'>
) & {
/** The blocks or pieces it was written in (a torrent's: those its chosen files needed; an
@@ -354,13 +448,20 @@ export interface TorrentDownloadUpdate {
pieces: TorrentPieceState[]
}
+export interface TelegramDownloadUpdate {
+ seq: number
+ state: Omit<TelegramDownloadState, 'blocks'>
+ blocks: HttpBlockState[]
+}
+
export interface NzbDownloadUpdate {
seq: number
state: Omit<NzbDownloadState, 'blocks'>
blocks: NzbSegmentState[]
}
-export type DownloadUpdate = HttpDownloadUpdate | TorrentDownloadUpdate | NzbDownloadUpdate
+export type DownloadUpdate =
+ HttpDownloadUpdate | TorrentDownloadUpdate | TelegramDownloadUpdate | NzbDownloadUpdate
/** User customization for one physical network, keyed by NetworkInterfaceInfo.id — lets a
* cryptic OS device name (e.g. "feth0") get a real label, and a color distinct from its
@@ -527,6 +628,14 @@ export interface StartTorrentDownloadRequest extends StartDownloadRequestBase {
selectedFiles?: number[]
}
+export interface StartTelegramDownloadRequest extends StartDownloadRequestBase {
+ kind: 'telegram'
+ /** The Saved Messages message the media is on; its media is looked up as the download starts
+ * (and again whenever Telegram says the file reference went stale). */
+ messageId: number
+ mediaType: TelegramMediaType
+}
+
export interface StartNzbDownloadRequest extends StartDownloadRequestBase {
kind: 'nzb'
/** The download starts from the NZB retained when it was probed (see NzbInfo.hash). */
@@ -534,7 +643,10 @@ export interface StartNzbDownloadRequest extends StartDownloadRequestBase {
}
export type StartDownloadRequest =
- StartHttpDownloadRequest | StartTorrentDownloadRequest | StartNzbDownloadRequest
+ | StartHttpDownloadRequest
+ | StartTorrentDownloadRequest
+ | StartTelegramDownloadRequest
+ | StartNzbDownloadRequest
/** The news server NZB downloads come from, as the window sees it: never its password. */
export interface UsenetServer {