From 8bf7a5972114129a4196d427aa7a9fcbed41a07e Mon Sep 17 00:00:00 2001 From: Devin Binnie <52460000+devinbinnie@users.noreply.github.com> Date: Fri, 1 Sep 2023 11:46:22 -0400 Subject: [PATCH] [MM-54279] Fix issues around working with saved downloads (#2812) --- src/common/JsonFileManager.ts | 15 +++++++++++++-- src/main/downloadsManager.ts | 17 +++++++++++------ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/common/JsonFileManager.ts b/src/common/JsonFileManager.ts index 2a6a2920..ef31ff3a 100644 --- a/src/common/JsonFileManager.ts +++ b/src/common/JsonFileManager.ts @@ -6,6 +6,7 @@ import fs from 'fs'; export default class JsonFileManager { jsonFile: string; json: T; + private saving?: Promise; constructor(file: string) { this.jsonFile = file; @@ -16,9 +17,9 @@ export default class JsonFileManager { } } - writeToFile(): Promise { + write(json: string): Promise { return new Promise((resolve, reject) => { - fs.writeFile(this.jsonFile, JSON.stringify(this.json, undefined, 2), (err) => { + fs.writeFile(this.jsonFile, json, (err) => { if (err) { // No real point in bringing electron-log into this otherwise electron-free file // eslint-disable-next-line no-console @@ -31,6 +32,16 @@ export default class JsonFileManager { }); } + writeToFile(): Promise { + const json = JSON.stringify(this.json, undefined, 2); + if (this.saving) { + this.saving = this.saving.then(() => this.write(json)); + } else { + this.saving = this.write(json); + } + return this.saving; + } + setJson(json: T): void { this.json = json; this.writeToFile(); diff --git a/src/main/downloadsManager.ts b/src/main/downloadsManager.ts index 1d39bc06..dfbb336b 100644 --- a/src/main/downloadsManager.ts +++ b/src/main/downloadsManager.ts @@ -174,14 +174,19 @@ export class DownloadsManager extends JsonFileManager { } for (const file of Object.values(this.downloads)) { - if (file.bookmark) { - this.bookmarks.set(this.getDownloadedFileId(file), {originalPath: file.location, bookmark: file.bookmark}); + try { + if (file.bookmark) { + this.bookmarks.set(this.getDownloadedFileId(file), {originalPath: file.location, bookmark: file.bookmark}); - if (file.mimeType?.toLowerCase().startsWith('image/')) { - const func = app.startAccessingSecurityScopedResource(file.bookmark); - fs.copyFileSync(file.location, path.resolve(app.getPath('temp'), path.basename(file.location))); - func(); + if (file.mimeType?.toLowerCase().startsWith('image/')) { + const func = app.startAccessingSecurityScopedResource(file.bookmark); + fs.copyFileSync(file.location, path.resolve(app.getPath('temp'), path.basename(file.location))); + func(); + } } + } catch (e) { + log.warn('could not load bookmark', file.filename, e); + this.clearFile(file); } } }