refactor: implement safe download method for url app window

This commit is contained in:
Xymorot 2021-01-04 23:35:01 +01:00
parent 02df7e739a
commit 72bac8e06a
3 changed files with 30 additions and 24 deletions

View File

@ -2,5 +2,7 @@ import { LoadURLOptions } from 'electron';
import { IAppWindow } from './i-app-window';
export interface IUrlAppWindow extends IAppWindow {
downloadUrlSafe(url: string, savePath: string, options?: LoadURLOptions): Promise<void>;
loadUrlSafe(url: string, options?: LoadURLOptions): Promise<void>;
}

View File

@ -28,6 +28,33 @@ export abstract class UrlAppWindow extends AppWindow implements IUrlAppWindow {
this.loadOptions = loadOptions;
}
public downloadUrlSafe(url: string, savePath: string, options?: LoadURLOptions): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (!this._window) {
throw new WindowClosedError();
}
this._window.webContents.session.once('will-download', (event, item) => {
item.setSavePath(savePath);
item.once('done', (doneEvent, state) => {
switch (state) {
case 'completed':
resolve();
break;
case 'cancelled':
case 'interrupted':
default:
reject(new Error(state));
break;
}
});
item.on('updated', () => {
item.resume();
});
});
void this.loadUrlSafe(url, options);
});
}
public async loadUrlSafe(url: string, options?: LoadURLOptions): Promise<void> {
if (!this._window) {
throw new WindowClosedError();

View File

@ -190,30 +190,7 @@ export class NhentaiAppWindow extends UrlAppWindow implements INhentaiAppWindow
const downloadLink: string = (await this._window.webContents.executeJavaScript(
`document.getElementById('${downloadLinkId}').href`
)) as string;
await new Promise<void>((resolve, reject) => {
if (!this._window) {
throw new WindowClosedError();
}
this._window.webContents.session.once('will-download', (event, item) => {
item.setSavePath(filePath);
item.once('done', (doneEvent, state) => {
switch (state) {
case 'completed':
resolve();
break;
case 'cancelled':
case 'interrupted':
default:
reject(new Error(state));
break;
}
});
item.on('updated', () => {
item.resume();
});
});
void this.loadUrlSafe(downloadLink);
});
await this.downloadUrlSafe(downloadLink, filePath);
const readable = createReadStream(filePath, { emitClose: true });