-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreload.js
329 lines (320 loc) · 9.9 KB
/
preload.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
function getElectron() {
const ret = {}, keys = ['contextBridge', 'ipcRenderer', 'getGlobal', 'screen', 'app', 'shell', 'Tray', 'Menu']
const extract = electron => {
keys.forEach(k => {
if (electron[k]) ret[k] = electron[k]
})
}
const electron = require('electron')
extract(electron)
if (electron.remote) {
extract(electron.remote)
} else {
try {
const remote = require('@electron/remote')
extract(remote)
} catch (e) { }
}
keys.forEach(k => {
if (!ret[k]) ret[k] = null
})
return ret
}
const { contextBridge, ipcRenderer, getGlobal, screen, app, shell, Tray, Menu } = getElectron()
const Events = require('events'), path = require('path'), fs = require('fs')
const paths = getGlobal('paths')
const { spawn } = require('child_process')
function download(opts) {
let _reject
const dl = new Download(opts)
const promise = new Promise((resolve, reject) => {
_reject = reject
dl.once('response', statusCode => {
if(statusCode < 200 && statusCode >= 400){
dl.destroy()
reject('http error '+ statusCode)
}
})
dl.on('error', e => {
err = e
})
dl.once('end', buf => {
dl.destroy()
resolve(buf)
})
if(opts.progress) {
dl.on('progress', opts.progress)
}
dl.start()
})
promise.cancel = () => {
if(dl && !dl.ended){
_reject('Promise was cancelled')
dl.destroy()
}
}
return promise
}
const window = getGlobal('window')
class FFmpegDownloader {
constructor(){}
async download(target, osd, mask) {
const tmpZipFile = path.join(target, 'ffmpeg.zip')
const arch = process.arch == 'x64' ? 64 : 32
let osName
switch (process.platform) {
case 'darwin':
osName = 'macos'
break
case 'win32':
osName = 'windows'
break
default:
osName = 'linux'
break
}
const variant = osName + '-' + arch
const url = await this.getVariantURL(variant)
osd.show(mask.replace('{0}', '0%'), 'fas fa-circle-notch fa-spin', 'ffmpeg-dl', 'persistent')
await download({
url,
file: tmpZipFile,
progress: p => {
osd.show(mask.replace('{0}', p + '%'), 'fas fa-circle-notch fa-spin', 'ffmpeg-dl', 'persistent')
}
})
const AdmZip = require('adm-zip')
const zip = new AdmZip(tmpZipFile)
const entryName = process.platform == 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
const targetFile = path.join(target, entryName)
zip.extractEntryTo(entryName, target, false, true)
fs.unlink(tmpZipFile, () => {})
return targetFile
}
async check(osd, mask, folder){
try {
await fs.promises.access(path.join(this.executableDir, this.executable), fs.constants.F_OK)
return true
} catch (error) {
try {
await fs.promises.access(path.join(folder, this.executable), fs.constants.F_OK)
this.executableDir = folder
return true
} catch (error) {
let err
const file = await this.download(folder, osd, mask).catch(e => err = e)
if (err) {
osd.show(String(err), 'fas fa-exclamation-triangle faclr-red', 'ffmpeg-dl', 'normal')
} else {
osd.show(mask.replace('{0}', '100%'), 'fas fa-circle-notch fa-spin', 'ffmpeg-dl', 'normal')
this.executableDir = path.dirname(file)
this.executable = path.basename(file)
return true
}
}
}
return false
}
async getVariantURL(variant){
const data = await download({url: 'https://ffbinaries.com/api/v1/versions', responseType: 'json'})
for(const version of Object.keys(data.versions).sort().reverse()){
const versionInfo = await download({url: data.versions[version], responseType: 'json'})
if(versionInfo.bin && typeof(versionInfo.bin[variant]) != 'undefined'){
return versionInfo.bin[variant].ffmpeg
}
}
}
}
class FFMpeg extends FFmpegDownloader {
constructor(){
super()
this.childs = {}
this.executable = 'ffmpeg'
if(process.platform == 'win32'){
this.executable += '.exe'
}
this.executableDir = process.resourcesPath || path.resolve('ffmpeg')
this.executableDir = this.executableDir.replace(new RegExp('\\\\', 'g'), '/')
if(this.executableDir.indexOf('resources/app') != -1) {
this.executableDir = this.executableDir.split('resources/app').shift() +'resources'
}
this.executable = path.basename(this.executable)
this.tmpdir = paths.temp;
['exec', 'cleanup', 'check', 'abort'].forEach(k => {
this[k] = this[k].bind(this) // allow export on contextBridge
})
}
isMetadata(s){
return s.indexOf('Stream mapping:') != -1
}
exec(cmd, events){
let exe, gotMetadata, output = ''
if(process.platform == 'linux' || process.platform == 'darwin'){ // cwd was not being honored on Linux/macOS
exe = this.executableDir +'/'+ this.executable
} else {
exe = this.executable
}
const child = spawn(exe, cmd, {
cwd: this.executableDir,
killSignal: 'SIGINT'
})
const maxLogLength = 1 * (1024 * 1024), log = s => {
s = String(s)
output += s
if(output.length > maxLogLength){
output = output.substr(-maxLogLength)
}
if(!gotMetadata && this.isMetadata(s)){
gotMetadata = true
events.metadata && events.metadata(output)
}
events.data(s)
}
child.stdout.on('data', log)
child.stderr.on('data', log)
child.on('error', err => {
console.log('FFEXEC ERR', cmd, child, err, output)
events.error(err)
})
child.once('close', () => {
delete this.childs[child.pid]
console.log('FFEXEC DONE', cmd.join(' '), child, output)
events.finish(output)
child.removeAllListeners()
})
console.log('FFEXEC '+ this.executable, cmd, child)
this.childs[child.pid] = child
events.start && events.start(child.pid)
return child
}
abort(pid){
if(typeof(this.childs[pid]) != 'undefined'){
const child = this.childs[pid]
delete this.childs[pid]
child.kill('SIGINT')
} else {
console.log('CANTKILL', pid)
}
}
cleanup(keepIds){
Object.keys(this.childs).forEach(pid => {
if(keepIds.includes(pid)){
console.log("Cleanup keeping " + pid)
} else {
console.log("Cleanup kill " + pid)
this.abort(pid)
}
})
}
}
class ExternalPlayer {
constructor() {
this.players = [
{processName: 'vlc', playerName: 'VLC Media Player'},
{processName: 'smplayer', playerName: 'SMPlayer'},
{processName: 'mpv', playerName: 'MPV'},
{processName: 'mplayer', playerName: 'MPlayer'},
{processName: 'xine', playerName: 'Xine'},
{processName: 'wmplayer', playerName: 'Windows Media Player'},
{processName: 'mpc-hc64', playerName: 'Media Player Classic - Home Cinema (64-bit)'},
{processName: 'mpc-hc', playerName: 'Media Player Classic - Home Cinema (32-bit)'},
{processName: 'mpc-be64', playerName: 'MPC-BE (64-bit)'},
{processName: 'mpc-be', playerName: 'MPC-BE (32-bit)'},
{processName: 'GOM', playerName: 'GOM Player'}
]
this.play = async (url, chosen) => {
const availables = await this.available()
const player = spawn(availables[chosen], [url], {detached: true, stdio: 'ignore'})
player.unref()
return true
}
this.available = async () => {
const results = {}
if(!this.finder) {
const ExecFinder = require('exec-finder')
this.finder = new ExecFinder({recursion: 3})
}
const available = await this.finder.find(this.players.map(p => p.processName))
Object.keys(available).filter(name => available[name].length).forEach(p => {
const name = this.players.filter(r => r.processName == p).shift().playerName
results[name] = available[p].sort((a, b) => a.length - b.length).shift()
})
return results
}
}
}
class WindowProxy extends Events {
constructor() {
super()
this.localEmit = super.emit.bind(this)
this.on = super.on.bind(this)
this.main = getGlobal('ui')
this.port = this.main.opts.port
this.removeAllListeners = super.removeAllListeners.bind(this)
this.emit = (...args) => {
this.main.channel.originalEmit(...args)
}
ipcRenderer.on('message', (_, args) => this.localEmit('message', args));
['focus', 'blur', 'show', 'hide', 'minimize', 'maximize', 'restore', 'close', 'isMaximized', 'getPosition', 'getSize', 'setSize', 'setAlwaysOnTop', 'setFullScreen', 'setPosition'].forEach(k => {
this[k] = (...args) => window[k](...args)
});
['maximize', 'enter-fullscreen', 'leave-fullscreen', 'restore', 'minimize', 'close'].forEach(k => {
window.on(k, (...args) => this.localEmit(k, ...args))
})
}
}
const windowProxy = new WindowProxy()
const externalPlayer = new ExternalPlayer()
const ffmpeg = new FFMpeg()
const screenScaleFactor = screen.getPrimaryDisplay().scaleFactor || 1
const getScreen = () => {
const primaryDisplay = screen.getPrimaryDisplay()
const scaleFactor = primaryDisplay.scaleFactor
const bounds = primaryDisplay.bounds
const workArea = primaryDisplay.workArea
const screenData = {
width: bounds.width,
height: bounds.height,
availWidth: workArea.width,
availHeight: workArea.height,
screenScaleFactor: scaleFactor
}
return screenData
}
const restart = () => {
setTimeout(() => {
app.relaunch()
app.quit()
setTimeout(() => app.exit(), 2000) // some deadline
}, 0)
}
if (parseFloat(process.versions.electron) < 22) {
api = {
platform: process.platform,
window: windowProxy,
openExternal: f => shell.openExternal(f),
openPath: f => shell.openPath(f),
screenScaleFactor, externalPlayer, getScreen,
download, restart, ffmpeg, paths
}
} else {
// On older Electron version (9.1.1) exposing 'require' doesn't works as expected.
contextBridge.exposeInMainWorld(
'api', {
platform: process.platform,
openExternal: f => shell.openExternal(f),
openPath: f => shell.openPath(f),
window: windowProxy,
screenScaleFactor,
externalPlayer: {
play: externalPlayer.play,
setContext: externalPlayer.setContext
},
getScreen,
download,
restart,
ffmpeg,
paths
}
)
}