Repository navigation
feat: download manager #256
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iamEvanYT
wants to merge
16
commits into
main
Choose a base branch
from
evan/download-manager
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
50a633f
feat: new download controller with finder progress bar handling
iamEvanYT a4c620e
feat: download manager backend
iamEvanYT f0de032
chore: format
iamEvanYT e2c63b4
feat: download manager UI
iamEvanYT fc594c2
feat: downloads popover menu on sidebar
iamEvanYT 5c22e32
feat: add strikethrough for missing files
iamEvanYT 999787e
chore: update styling
iamEvanYT c240dd2
refactor: remove polling, add DownloadsProvider and reorganise
iamEvanYT c08a893
feat: use actual file icons
iamEvanYT 644e5b1
chore: redesign downloads popover
iamEvanYT 26df532
fix: issues
iamEvanYT d34a590
chore: bump dependencies
iamEvanYT ac210f4
chore: upgrade typescript
iamEvanYT 84335aa
chore: update `@types/node` to match electron node version
iamEvanYT 69c9fb9
chore: bump eslint plugin versions
iamEvanYT 9aa4d99
fix: lint warnings
iamEvanYT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
feat: new download controller with finder progress bar handling
- Loading branch information
commit 50a633fedad83dabd58443de44538b5f43510587
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| import { app, type DownloadItem, type Session } from "electron"; | ||
| import path from "path"; | ||
| import { debugError, debugPrint } from "@/modules/output"; | ||
|
|
||
| type MacOSProgressModule = typeof import("./macos-progress"); | ||
|
|
||
| interface DownloadMetadata { | ||
| progressId: string | null; | ||
| savePath: string | null; | ||
| lastUpdate: number; | ||
| lastBytes: number; | ||
| initialTotalBytes: number; | ||
| syncingProgress: boolean; | ||
| } | ||
|
|
||
| class DownloadsController { | ||
| private readonly activeDownloads = new WeakMap<DownloadItem, DownloadMetadata>(); | ||
| private readonly registeredSessions = new WeakSet<Session>(); | ||
| private macosProgress: MacOSProgressModule | null = null; | ||
| private macosProgressLoad: Promise<MacOSProgressModule | null> | null = null; | ||
|
|
||
| public registerSession(session: Session): void { | ||
| if (this.registeredSessions.has(session)) { | ||
| return; | ||
| } | ||
|
|
||
| session.on("will-download", (_event, item) => { | ||
| this.handleWillDownload(item); | ||
| }); | ||
|
|
||
| this.registeredSessions.add(session); | ||
| debugPrint("DOWNLOADS", "Download handler registered for session"); | ||
| } | ||
|
|
||
| private async ensureMacosProgressModule(): Promise<MacOSProgressModule | null> { | ||
| if (process.platform !== "darwin") return null; | ||
| if (this.macosProgress) return this.macosProgress; | ||
|
|
||
| if (!this.macosProgressLoad) { | ||
| this.macosProgressLoad = import("./macos-progress") | ||
| .then((module) => { | ||
| this.macosProgress = module; | ||
| return module; | ||
| }) | ||
| .catch((err) => { | ||
| debugError("DOWNLOADS", "Failed to load macOS progress module:", err); | ||
| return null; | ||
| }); | ||
| } | ||
|
|
||
| return this.macosProgressLoad; | ||
| } | ||
|
|
||
| private handleWillDownload(item: DownloadItem): void { | ||
| const suggestedFilename = item.getFilename(); | ||
| const defaultPath = path.join(app.getPath("downloads"), suggestedFilename); | ||
|
|
||
| item.setSaveDialogOptions({ | ||
| defaultPath, | ||
| properties: ["createDirectory", "showOverwriteConfirmation"] | ||
| }); | ||
|
|
||
| const metadata: DownloadMetadata = { | ||
| progressId: null, | ||
| savePath: null, | ||
| lastUpdate: Date.now(), | ||
| lastBytes: 0, | ||
| initialTotalBytes: item.getTotalBytes(), | ||
| syncingProgress: false | ||
| }; | ||
|
|
||
| this.activeDownloads.set(item, metadata); | ||
|
|
||
| debugPrint("DOWNLOADS", `Download requested: ${suggestedFilename}`); | ||
|
|
||
| this.queueProgressSync(item, metadata); | ||
|
|
||
| item.on("updated", (_event, state) => { | ||
| const current = this.activeDownloads.get(item); | ||
| if (!current) return; | ||
|
|
||
| this.queueProgressSync(item, current); | ||
|
|
||
| if (state === "progressing") { | ||
| this.updateMacProgress(current, item); | ||
| } else if (state === "interrupted") { | ||
| debugPrint("DOWNLOADS", `Download interrupted: ${item.getFilename()}`); | ||
| } | ||
| }); | ||
|
|
||
| item.once("done", (_event, state) => { | ||
| const current = this.activeDownloads.get(item); | ||
| if (!current) return; | ||
|
|
||
| this.activeDownloads.delete(item); | ||
| void this.handleDone(item, current, state); | ||
| }); | ||
| } | ||
|
|
||
| private queueProgressSync(item: DownloadItem, meta: DownloadMetadata): void { | ||
| if (meta.syncingProgress) return; | ||
|
|
||
| meta.syncingProgress = true; | ||
| void this.syncMacProgress(item, meta).finally(() => { | ||
| meta.syncingProgress = false; | ||
| }); | ||
| } | ||
|
|
||
| private async syncMacProgress(item: DownloadItem, meta: DownloadMetadata): Promise<void> { | ||
| const mp = await this.ensureMacosProgressModule(); | ||
| if (!mp) return; | ||
|
|
||
| const savePath = this.getSavePath(item); | ||
| if (!savePath) return; | ||
|
|
||
| if (!meta.progressId) { | ||
| meta.savePath = savePath; | ||
| meta.initialTotalBytes = item.getTotalBytes(); | ||
| meta.progressId = mp.createFileProgress(savePath, meta.initialTotalBytes, () => { | ||
| debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`); | ||
| item.cancel(); | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| if (meta.savePath && meta.savePath !== savePath) { | ||
| const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => { | ||
| debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`); | ||
| item.cancel(); | ||
| }); | ||
|
|
||
| if (nextProgressId) { | ||
| meta.progressId = nextProgressId; | ||
| } | ||
| meta.savePath = savePath; | ||
| } | ||
| } | ||
|
|
||
| private updateMacProgress(meta: DownloadMetadata, item: DownloadItem): void { | ||
| if (!this.macosProgress || !meta.progressId) return; | ||
|
|
||
| const receivedBytes = item.getReceivedBytes(); | ||
| const totalBytes = item.getTotalBytes(); | ||
|
|
||
| this.macosProgress.updateFileProgress(meta.progressId, receivedBytes); | ||
|
|
||
| if (totalBytes > 0 && totalBytes !== meta.initialTotalBytes) { | ||
| this.macosProgress.updateFileProgressTotal(meta.progressId, totalBytes); | ||
| meta.initialTotalBytes = totalBytes; | ||
| } | ||
|
|
||
| const now = Date.now(); | ||
| const timeDelta = (now - meta.lastUpdate) / 1000; | ||
|
|
||
| if (timeDelta >= 0.5) { | ||
| const bytesDelta = receivedBytes - meta.lastBytes; | ||
| const bytesPerSecond = bytesDelta / timeDelta; | ||
|
|
||
| this.macosProgress.updateFileProgressThroughput(meta.progressId, bytesPerSecond); | ||
|
|
||
| if (bytesPerSecond > 0 && totalBytes > 0) { | ||
| const remainingBytes = totalBytes - receivedBytes; | ||
| const secondsRemaining = remainingBytes / bytesPerSecond; | ||
| this.macosProgress.updateFileProgressEstimatedTime(meta.progressId, secondsRemaining); | ||
| } | ||
|
|
||
| meta.lastUpdate = now; | ||
| meta.lastBytes = receivedBytes; | ||
| } | ||
| } | ||
|
|
||
| private async handleDone( | ||
| item: DownloadItem, | ||
| meta: DownloadMetadata, | ||
| state: "completed" | "cancelled" | "interrupted" | ||
| ): Promise<void> { | ||
| await this.syncMacProgress(item, meta); | ||
|
|
||
| if (!this.macosProgress || !meta.progressId) { | ||
| debugPrint("DOWNLOADS", `Download ${state}: ${item.getFilename()}`); | ||
| return; | ||
| } | ||
|
|
||
| if (state === "completed") { | ||
| this.macosProgress.completeFileProgress(meta.progressId, item.getReceivedBytes()); | ||
| } else { | ||
| this.macosProgress.cancelFileProgress(meta.progressId); | ||
| } | ||
|
|
||
| debugPrint("DOWNLOADS", `Download ${state}: ${this.getSavePath(item) ?? item.getFilename()}`); | ||
| } | ||
|
|
||
| private getSavePath(item: DownloadItem): string | null { | ||
| try { | ||
| const savePath = item.getSavePath(); | ||
| return savePath || null; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const downloadsController = new DownloadsController(); | ||
155 changes: 155 additions & 0 deletions
155
src/main/controllers/downloads-controller/macos-progress.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import { NSProgress, NSURL, NSNumber, type _NSProgress } from "objcjs-types/Foundation"; | ||
| import { NSProgressFileOperationKind, NSProgressKind } from "objcjs-types/Foundation"; | ||
| import { NSStringFromString } from "objcjs-types/helpers"; | ||
| import { debugError, debugPrint } from "@/modules/output"; | ||
|
|
||
| const activeProgressMap = new Map<string, _NSProgress>(); | ||
| const cancelCallbackMap = new Map<string, () => void>(); | ||
|
|
||
| export function createFileProgress(filePath: string, totalBytes: number, onCancel?: () => void): string | null { | ||
| try { | ||
| const progressId = `${filePath}-${Date.now()}`; | ||
| const progress = NSProgress.discreteProgressWithTotalUnitCount$(Math.max(totalBytes, 0)); | ||
|
|
||
| progress.setKind$(NSStringFromString(NSProgressKind.File)); | ||
| progress.setFileOperationKind$(NSStringFromString(NSProgressFileOperationKind.Downloading)); | ||
| progress.setFileURL$(NSURL.fileURLWithPath$(NSStringFromString(filePath))); | ||
| progress.setCompletedUnitCount$(0); | ||
| progress.setCancellable$(true); | ||
| progress.setPausable$(false); | ||
|
|
||
| if (onCancel) { | ||
| cancelCallbackMap.set(progressId, onCancel); | ||
| progress.setCancellationHandler$(() => { | ||
| const callback = cancelCallbackMap.get(progressId); | ||
| if (callback) { | ||
| debugPrint("DOWNLOADS", `macOS: cancel requested from Finder for ${filePath}`); | ||
| callback(); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| progress.publish(); | ||
| activeProgressMap.set(progressId, progress); | ||
|
|
||
| debugPrint("DOWNLOADS", `macOS: created progress for ${filePath}`); | ||
| return progressId; | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: createFileProgress failed:", err); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| export function updateFileProgress(progressId: string, completedBytes: number): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
| progress.setCompletedUnitCount$(Math.max(completedBytes, 0)); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: updateFileProgress failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function updateFileProgressTotal(progressId: string, totalBytes: number): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
| progress.setTotalUnitCount$(Math.max(totalBytes, 0)); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: updateFileProgressTotal failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function updateFileProgressThroughput(progressId: string, bytesPerSecond: number): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
| progress.setThroughput$(NSNumber.numberWithDouble$(Math.max(bytesPerSecond, 0))); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: updateFileProgressThroughput failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function updateFileProgressEstimatedTime(progressId: string, seconds: number): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
| progress.setEstimatedTimeRemaining$(NSNumber.numberWithDouble$(Math.max(seconds, 0))); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: updateFileProgressEstimatedTime failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function completeFileProgress(progressId: string, completedBytes: number): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
|
|
||
| const finalCount = Math.max(completedBytes, progress.totalUnitCount(), 0); | ||
| progress.setTotalUnitCount$(finalCount); | ||
| progress.setCompletedUnitCount$(finalCount); | ||
| progress.setCancellationHandler$(null); | ||
| cancelCallbackMap.delete(progressId); | ||
| progress.unpublish(); | ||
| activeProgressMap.delete(progressId); | ||
|
|
||
| debugPrint("DOWNLOADS", `macOS: completed progress for ID ${progressId}`); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: completeFileProgress failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function cancelFileProgress(progressId: string): void { | ||
| try { | ||
| const progress = activeProgressMap.get(progressId); | ||
| if (!progress) return; | ||
|
|
||
| progress.setCancellationHandler$(null); | ||
| cancelCallbackMap.delete(progressId); | ||
| progress.cancel(); | ||
| progress.unpublish(); | ||
| activeProgressMap.delete(progressId); | ||
|
|
||
| debugPrint("DOWNLOADS", `macOS: cancelled progress for ID ${progressId}`); | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: cancelFileProgress failed:", err); | ||
| } | ||
| } | ||
|
|
||
| export function recreateFileProgressAtPath( | ||
| progressId: string, | ||
| newFilePath: string, | ||
| onCancel?: () => void | ||
| ): string | null { | ||
| try { | ||
| const oldProgress = activeProgressMap.get(progressId); | ||
| if (!oldProgress) return null; | ||
|
|
||
| const completedBytes = oldProgress.completedUnitCount(); | ||
| const totalBytes = oldProgress.totalUnitCount(); | ||
| const throughput = oldProgress.throughput(); | ||
| const estimatedTime = oldProgress.estimatedTimeRemaining(); | ||
|
|
||
| cancelFileProgress(progressId); | ||
|
|
||
| const newProgressId = createFileProgress(newFilePath, totalBytes, onCancel); | ||
| if (!newProgressId) return null; | ||
|
|
||
| const newProgress = activeProgressMap.get(newProgressId); | ||
| if (newProgress) { | ||
| newProgress.setCompletedUnitCount$(completedBytes); | ||
| if (throughput) { | ||
| newProgress.setThroughput$(throughput); | ||
| } | ||
| if (estimatedTime) { | ||
| newProgress.setEstimatedTimeRemaining$(estimatedTime); | ||
| } | ||
| } | ||
|
|
||
| debugPrint("DOWNLOADS", `macOS: recreated progress at ${newFilePath}`); | ||
| return newProgressId; | ||
| } catch (err) { | ||
| debugError("DOWNLOADS", "macOS: recreateFileProgressAtPath failed:", err); | ||
| return null; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep macOS progress recreation retryable on failure.
recreateFileProgressAtPath()can returnnull. This branch still advancesmeta.savePath, so later syncs stop retrying whilemeta.progressIdstill points at a removed progress entry.💡 Suggested fix
const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => { debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`); item.cancel(); }); if (nextProgressId) { meta.progressId = nextProgressId; + meta.savePath = savePath; + } else { + meta.progressId = null; } - meta.savePath = savePath; } }📝 Committable suggestion
🤖 Prompt for AI Agents