This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 547
/
downloads.js
248 lines (206 loc) · 6.98 KB
/
downloads.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import path from 'path'
import fs from 'fs'
import { app, dialog, shell } from 'electron'
import mime from 'mime'
import speedometer from 'speedometer'
import emitStream from 'emit-stream'
import EventEmitter from 'events'
import parseDataURL from 'data-urls'
import { requestPermission } from './permissions'
import { openOrFocusDownloadsPage } from './view-manager'
// globals
// =
// downloads list
// - shared across all windows
var downloads = []
// used for rpc
var downloadsEvents = new EventEmitter()
// exported api
// =
export function setup () {
}
export const WEBAPI = { createEventsStream, getDownloads, pause, resume, cancel, remove, open, showInFolder }
export function registerListener (win, opts = {}) {
const listener = async (e, item, wc) => {
// dont touch if already being handled
// - if `opts.saveAs` is being used, there may be multiple active event handlers
if (item.isHandled) { return }
// track as an active download
item.id = ('' + Date.now()) + ('' + Math.random())
if (opts.saveAs) item.setSavePath(opts.saveAs)
item.isHandled = true
item.downloadSpeed = speedometer()
downloads.push(item)
// This is to prevent the browser-dropdown-menu from opening
// For now it is being used when downloading `.html` pages
if (!opts.suppressNewDownloadEvent) {
downloadsEvents.emit('new-download', toJSON(item))
openOrFocusDownloadsPage(win)
}
var lastBytes = 0
item.on('updated', () => {
// set name if not already done
if (!item.name) {
item.name = path.basename(item.getSavePath())
}
var sumProgress = {
receivedBytes: getSumReceivedBytes(),
totalBytes: getSumTotalBytes()
}
// track rate of download
item.downloadSpeed(item.getReceivedBytes() - lastBytes)
lastBytes = item.getReceivedBytes()
// emit
downloadsEvents.emit('updated', toJSON(item))
downloadsEvents.emit('sum-progress', sumProgress)
win.setProgressBar(sumProgress.receivedBytes / sumProgress.totalBytes)
})
item.on('done', (e, state) => {
// inform users of error conditions
var overrides = false
if (state === 'interrupted') {
// this can sometimes happen because the link is a data: URI
// in that case, we can manually parse and save it
if (item.getURL().startsWith('data:')) {
let parsed = parseDataURL(item.getURL())
if (parsed) {
fs.writeFileSync(item.getSavePath(), parsed.body)
overrides = {
state: 'completed',
receivedBytes: parsed.body.length,
totalBytes: parsed.body.length
}
}
}
if (!overrides) {
dialog.showErrorBox('Download error', `The download of ${item.getFilename()} was interrupted`)
}
}
downloadsEvents.emit('done', toJSON(item, overrides))
// replace entry with a clone that captures the final state
downloads.splice(downloads.indexOf(item), 1, capture(item, overrides))
// reset progress bar when done
if (isNoActiveDownloads() && !win.isDestroyed()) {
win.setProgressBar(-1)
}
if (state === 'completed') {
// flash the dock on osx
if (process.platform === 'darwin') {
app.dock.downloadFinished(item.getSavePath())
}
}
// optional, for one-time downloads
if (opts.unregisterWhenDone) {
wc.session.removeListener('will-download', listener)
}
})
}
win.webContents.session.prependListener('will-download', listener)
win.on('close', () => win.webContents.session.removeListener('will-download', listener))
}
export function download (win, wc, url, opts) {
// register for onetime use of the download system
opts = Object.assign({}, opts, {unregisterWhenDone: true, trusted: true})
registerListener(win, opts)
wc.downloadURL(url)
}
// rpc api
// =
function createEventsStream () {
return emitStream(downloadsEvents)
}
function getDownloads () {
return Promise.resolve(downloads.map(toJSON))
}
function pause (id) {
var download = downloads.find(d => d.id == id)
if (download) { download.pause() }
return Promise.resolve()
}
function resume (id) {
var download = downloads.find(d => d.id == id)
if (download) { download.resume() }
return Promise.resolve()
}
function cancel (id) {
var download = downloads.find(d => d.id == id)
if (download) { download.cancel() }
return Promise.resolve()
}
function remove (id) {
var download = downloads.find(d => d.id == id)
if (download && download.getState() != 'progressing') { downloads.splice(downloads.indexOf(download), 1) }
return Promise.resolve()
}
function open (id) {
return new Promise((resolve, reject) => {
// find the download
var download = downloads.find(d => d.id == id)
if (!download || download.state != 'completed') { return reject() }
// make sure the file is still there
fs.stat(download.getSavePath(), err => {
if (err) { return reject() }
// open
shell.openItem(download.getSavePath())
resolve()
})
})
}
function showInFolder (id) {
return new Promise((resolve, reject) => {
// find the download
var download = downloads.find(d => d.id == id)
if (!download || download.state != 'completed') { return reject() }
// make sure the file is still there
fs.stat(download.getSavePath(), err => {
if (err) { return reject() }
// open
shell.showItemInFolder(download.getSavePath())
resolve()
})
})
}
// internal helpers
// =
// reduce down to attributes
function toJSON (item, overrides) {
return {
id: item.id,
name: item.name,
url: item.getURL(),
state: overrides ? overrides.state : item.getState(),
isPaused: item.isPaused(),
receivedBytes: overrides ? overrides.receivedBytes : item.getReceivedBytes(),
totalBytes: overrides ? overrides.totalBytes : item.getTotalBytes(),
downloadSpeed: item.downloadSpeed()
}
}
// create a capture of the final state of an item
function capture (item, overrides) {
var savePath = item.getSavePath()
var dlspeed = item.download
item = toJSON(item, overrides)
item.getURL = () => item.url
item.getState = () => overrides === true ? 'completed' : item.state
item.isPaused = () => false
item.getReceivedBytes = () => overrides ? overrides.receivedBytes : item.receivedBytes
item.getTotalBytes = () => overrides ? overrides.totalBytes : item.totalBytes
item.getSavePath = () => savePath
item.downloadSpeed = () => dlspeed
return item
}
// sum of received bytes
function getSumReceivedBytes () {
return getActiveDownloads().reduce((acc, item) => acc + item.getReceivedBytes(), 0)
}
// sum of total bytes
function getSumTotalBytes () {
return getActiveDownloads().reduce((acc, item) => acc + item.getTotalBytes(), 0)
}
function getActiveDownloads () {
return downloads.filter(d => d.getState() == 'progressing')
}
// all downloads done?
function isNoActiveDownloads () {
return getActiveDownloads().length === 0
}