From 63b55df63722254e142837683463e9a60e741ba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Rodr=C3=ADguez=20Baquero?= Date: Sun, 10 Oct 2021 13:49:13 -0500 Subject: [PATCH] fix: modernify code --- src/main/dialog.js | 2 +- src/main/index.js | 8 ++-- src/main/ipc.js | 26 +++++------ src/main/menu.js | 8 ++-- src/main/shell.js | 2 +- src/main/squirrel-win32.js | 2 +- src/main/tray.js | 4 +- src/main/windows/about.js | 4 +- src/main/windows/webtorrent.js | 2 +- src/renderer/controllers/media-controller.js | 4 +- src/renderer/controllers/prefs-controller.js | 2 +- .../controllers/subtitles-controller.js | 13 +++--- .../controllers/torrent-controller.js | 2 +- .../controllers/torrent-list-controller.js | 21 +++++---- src/renderer/lib/cast.js | 43 ++++++++++--------- src/renderer/lib/dispatcher.js | 4 +- src/renderer/lib/migrations.js | 18 ++++---- src/renderer/lib/state.js | 6 +-- src/renderer/lib/telemetry.js | 19 ++++---- src/renderer/lib/torrent-poster.js | 37 ++++++---------- src/renderer/main.js | 12 +++--- src/renderer/pages/app.js | 4 +- src/renderer/pages/create-torrent-page.js | 4 +- src/renderer/pages/player-page.js | 23 +++++----- src/renderer/webtorrent.js | 40 ++++++++--------- 25 files changed, 146 insertions(+), 164 deletions(-) diff --git a/src/main/dialog.js b/src/main/dialog.js index 5b349430..02866a5a 100644 --- a/src/main/dialog.js +++ b/src/main/dialog.js @@ -82,7 +82,7 @@ function openTorrentFile () { const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts) resetTitle() if (!Array.isArray(selectedPaths)) return - selectedPaths.forEach(function (selectedPath) { + selectedPaths.forEach(selectedPath => { windows.main.dispatch('addTorrent', selectedPath) }) } diff --git a/src/main/index.js b/src/main/index.js index 428da727..606f7343 100644 --- a/src/main/index.js +++ b/src/main/index.js @@ -110,13 +110,13 @@ function init () { ipc.init() - app.once('ipcReady', function () { + app.once('ipcReady', () => { log('Command line args:', argv) processArgv(argv) console.timeEnd('init') }) - app.on('before-quit', function (e) { + app.on('before-quit', e => { if (app.isQuitting) return app.isQuitting = true @@ -129,7 +129,7 @@ function init () { }, 4000) // quit after 4 secs, at most }) - app.on('activate', function () { + app.on('activate', () => { if (isReady) windows.main.show() }) } @@ -207,7 +207,7 @@ function sliceArgv (argv) { function processArgv (argv) { const torrentIds = [] - argv.forEach(function (arg) { + argv.forEach(arg => { if (arg === '-n' || arg === '-o' || arg === '-u') { // Critical path: Only load the 'dialog' package if it is needed const dialog = require('./dialog') diff --git a/src/main/ipc.js b/src/main/ipc.js index 9aea69ee..a18a5bb1 100644 --- a/src/main/ipc.js +++ b/src/main/ipc.js @@ -21,16 +21,16 @@ function setModule (name, module) { } function init () { - ipcMain.once('ipcReady', function (e) { + ipcMain.once('ipcReady', e => { app.ipcReady = true app.emit('ipcReady') }) - ipcMain.once('ipcReadyWebTorrent', function (e) { + ipcMain.once('ipcReadyWebTorrent', e => { app.ipcReadyWebTorrent = true log('sending %d queued messages from the main win to the webtorrent window', messageQueueMainToWebTorrent.length) - messageQueueMainToWebTorrent.forEach(function (message) { + messageQueueMainToWebTorrent.forEach(message => { windows.webtorrent.send(message.name, ...message.args) log('webtorrent: sent queued %s', message.name) }) @@ -66,7 +66,7 @@ function init () { * Player Events */ - ipcMain.on('onPlayerOpen', function () { + ipcMain.on('onPlayerOpen', () => { const powerSaveBlocker = require('./power-save-blocker') const shortcuts = require('./shortcuts') const thumbar = require('./thumbar') @@ -77,14 +77,14 @@ function init () { thumbar.enable() }) - ipcMain.on('onPlayerUpdate', function (e, ...args) { + ipcMain.on('onPlayerUpdate', (e, ...args) => { const thumbar = require('./thumbar') menu.onPlayerUpdate(...args) thumbar.onPlayerUpdate(...args) }) - ipcMain.on('onPlayerClose', function () { + ipcMain.on('onPlayerClose', () => { const powerSaveBlocker = require('./power-save-blocker') const shortcuts = require('./shortcuts') const thumbar = require('./thumbar') @@ -95,7 +95,7 @@ function init () { thumbar.disable() }) - ipcMain.on('onPlayerPlay', function () { + ipcMain.on('onPlayerPlay', () => { const powerSaveBlocker = require('./power-save-blocker') const thumbar = require('./thumbar') @@ -103,7 +103,7 @@ function init () { thumbar.onPlayerPlay() }) - ipcMain.on('onPlayerPause', function () { + ipcMain.on('onPlayerPause', () => { const powerSaveBlocker = require('./power-save-blocker') const thumbar = require('./thumbar') @@ -115,7 +115,7 @@ function init () { * Folder Watcher Events */ - ipcMain.on('startFolderWatcher', function () { + ipcMain.on('startFolderWatcher', () => { if (!modules.folderWatcher) { log('IPC ERR: folderWatcher module is not defined.') return @@ -124,7 +124,7 @@ function init () { modules.folderWatcher.start() }) - ipcMain.on('stopFolderWatcher', function () { + ipcMain.on('stopFolderWatcher', () => { if (!modules.folderWatcher) { log('IPC ERR: folderWatcher module is not defined.') return @@ -190,10 +190,10 @@ function init () { * External Media Player */ - ipcMain.on('checkForExternalPlayer', function (e, path) { + ipcMain.on('checkForExternalPlayer', (e, path) => { const externalPlayer = require('./external-player') - externalPlayer.checkInstall(path, function (err) { + externalPlayer.checkInstall(path, err => { windows.main.send('checkForExternalPlayer', !err) }) }) @@ -219,7 +219,7 @@ function init () { */ const oldEmit = ipcMain.emit - ipcMain.emit = function (name, e, ...args) { + ipcMain.emit = (name, e, ...args) => { // Relay messages between the main window and the WebTorrent hidden window if (name.startsWith('wt-') && !app.isQuitting) { console.dir(e.sender.getTitle()) diff --git a/src/main/menu.js b/src/main/menu.js index 1611e142..26bdf6d8 100644 --- a/src/main/menu.js +++ b/src/main/menu.js @@ -68,11 +68,9 @@ function onToggleFullScreen (flag) { } function getMenuItem (label) { - for (let i = 0; i < menu.items.length; i++) { - const menuItem = menu.items[i].submenu.items.find(function (item) { - return item.label === label - }) - if (menuItem) return menuItem + for (const menuItem of menu.items) { + const submenuItem = menuItem.submenu.items.find(item => item.label === label) + if (submenuItem) return submenuItem } return {} } diff --git a/src/main/shell.js b/src/main/shell.js index b67c3de4..80588800 100644 --- a/src/main/shell.js +++ b/src/main/shell.js @@ -38,5 +38,5 @@ function showItemInFolder (path) { */ function moveItemToTrash (path) { log(`moveItemToTrash: ${path}`) - shell.moveItemToTrash(path) + shell.trashItem(path) } diff --git a/src/main/squirrel-win32.js b/src/main/squirrel-win32.js index cc657ec7..16db39c8 100644 --- a/src/main/squirrel-win32.js +++ b/src/main/squirrel-win32.js @@ -12,7 +12,7 @@ const handlers = require('./handlers') const EXE_NAME = path.basename(process.execPath) const UPDATE_EXE = path.join(process.execPath, '..', '..', 'Update.exe') -const run = function (args, done) { +const run = (args, done) => { spawn(UPDATE_EXE, args, { detached: true }) .on('close', done) } diff --git a/src/main/tray.js b/src/main/tray.js index c2a8a665..937eb9e9 100644 --- a/src/main/tray.js +++ b/src/main/tray.js @@ -34,7 +34,7 @@ function setWindowFocus (flag) { } function initLinux () { - checkLinuxTraySupport(function (err) { + checkLinuxTraySupport(err => { if (!err) createTray() }) } @@ -50,7 +50,7 @@ function checkLinuxTraySupport (cb) { const cp = require('child_process') // Check that libappindicator libraries are installed in system. - cp.exec('ldconfig -p | grep libappindicator', function (err, stdout) { + cp.exec('ldconfig -p | grep libappindicator', (err, stdout) => { if (err) return cb(err) cb(null) }) diff --git a/src/main/windows/about.js b/src/main/windows/about.js index bb74f15d..0f097036 100644 --- a/src/main/windows/about.js +++ b/src/main/windows/about.js @@ -37,7 +37,7 @@ function init () { win.loadURL(config.WINDOW_ABOUT) - win.once('ready-to-show', function () { + win.once('ready-to-show', () => { win.show() // No menu on the About window // Hack: BrowserWindow removeMenu method not working on electron@7 @@ -45,7 +45,7 @@ function init () { win.setMenuBarVisibility(false) }) - win.once('closed', function () { + win.once('closed', () => { about.win = null }) } diff --git a/src/main/windows/webtorrent.js b/src/main/windows/webtorrent.js index 6806668e..b93af68d 100644 --- a/src/main/windows/webtorrent.js +++ b/src/main/windows/webtorrent.js @@ -38,7 +38,7 @@ function init () { win.loadURL(config.WINDOW_WEBTORRENT) // Prevent killing the WebTorrent process - win.on('close', function (e) { + win.on('close', e => { if (app.isQuitting) { return } diff --git a/src/renderer/controllers/media-controller.js b/src/renderer/controllers/media-controller.js index e57be056..0ad6f73f 100644 --- a/src/renderer/controllers/media-controller.js +++ b/src/renderer/controllers/media-controller.js @@ -23,7 +23,7 @@ module.exports = class MediaController { telemetry.logPlayAttempt('error') state.playing.location = 'error' ipcRenderer.send('checkForExternalPlayer', state.saved.prefs.externalPlayerPath) - ipcRenderer.once('checkForExternalPlayer', function (e, isInstalled) { + ipcRenderer.once('checkForExternalPlayer', (e, isInstalled) => { state.modal = { id: 'unsupported-media-modal', error, @@ -56,7 +56,7 @@ module.exports = class MediaController { const state = this.state state.playing.location = 'external' - const onServerRunning = function () { + const onServerRunning = () => { state.playing.isReady = true telemetry.logPlayAttempt('external') diff --git a/src/renderer/controllers/prefs-controller.js b/src/renderer/controllers/prefs-controller.js index cd94a2f1..736ac982 100644 --- a/src/renderer/controllers/prefs-controller.js +++ b/src/renderer/controllers/prefs-controller.js @@ -13,7 +13,7 @@ module.exports = class PrefsController { const state = this.state state.location.go({ url: 'preferences', - setup: function (cb) { + setup(cb) { // initialize preferences state.window.title = 'Preferences' ipcRenderer.send('setAllowNav', false) diff --git a/src/renderer/controllers/subtitles-controller.js b/src/renderer/controllers/subtitles-controller.js index 092014ed..2faf5bc9 100644 --- a/src/renderer/controllers/subtitles-controller.js +++ b/src/renderer/controllers/subtitles-controller.js @@ -37,12 +37,11 @@ module.exports = class SubtitlesController { // Read the files concurrently, then add all resulting subtitle tracks const tasks = files.map((file) => (cb) => loadSubtitle(file, cb)) - parallel(tasks, function (err, tracks) { + parallel(tasks, (err, tracks) => { if (err) return dispatch('error', err) - for (let i = 0; i < tracks.length; i++) { - // No dupes allowed - const track = tracks[i] + // No dupes allowed + tracks.forEach((track, i) => { let trackIndex = subtitles.tracks.findIndex((t) => track.filePath === t.filePath) @@ -55,7 +54,7 @@ module.exports = class SubtitlesController { if (autoSelect && (i === 0 || isSystemLanguage(track.language))) { subtitles.selectedIndex = trackIndex } - } + }); // Finally, make sure no two tracks have the same label relabelSubtitles(subtitles) @@ -94,7 +93,7 @@ function loadSubtitle (file, cb) { const vttStream = fs.createReadStream(filePath).pipe(srtToVtt()) - concat(vttStream, function (err, buf) { + concat(vttStream, (err, buf) => { if (err) return dispatch('error', 'Can\'t parse subtitles file.') // Detect what language the subtitles are in @@ -127,7 +126,7 @@ function isSystemLanguage (language) { // Labels each track by language, eg 'German', 'English', 'English 2', ... function relabelSubtitles (subtitles) { const counts = {} - subtitles.tracks.forEach(function (track) { + subtitles.tracks.forEach(track => { const lang = track.language counts[lang] = (counts[lang] || 0) + 1 track.label = counts[lang] > 1 ? (lang + ' ' + counts[lang]) : lang diff --git a/src/renderer/controllers/torrent-controller.js b/src/renderer/controllers/torrent-controller.js index 83f32c2d..de32ec01 100644 --- a/src/renderer/controllers/torrent-controller.js +++ b/src/renderer/controllers/torrent-controller.js @@ -177,7 +177,7 @@ function showDoneNotification (torrent) { silent: true }) - notif.onclick = function () { + notif.onclick = () => { ipcRenderer.send('show') } diff --git a/src/renderer/controllers/torrent-list-controller.js b/src/renderer/controllers/torrent-list-controller.js index c4ff658e..5a8038b2 100644 --- a/src/renderer/controllers/torrent-list-controller.js +++ b/src/renderer/controllers/torrent-list-controller.js @@ -94,7 +94,7 @@ module.exports = class TorrentListController { if (!fileOrFolder) return start() // Existing torrent: check that the path is still there - fs.stat(fileOrFolder, function (err) { + fs.stat(fileOrFolder, err => { if (err) { s.error = 'path-missing' dispatch('backToList') @@ -156,9 +156,8 @@ module.exports = class TorrentListController { prioritizeTorrent (infoHash) { this.state.saved.torrents - .filter((torrent) => { // We're interested in active torrents only. - return (['downloading', 'seeding'].indexOf(torrent.status) !== -1) - }) + .filter(torrent => // We're interested in active torrents only. + ['downloading', 'seeding'].indexOf(torrent.status) !== -1) .forEach((torrent) => { // Pause all active torrents except the one that started playing. if (infoHash === torrent.infoHash) return @@ -331,9 +330,9 @@ module.exports = class TorrentListController { if (!savePath) return // They clicked Cancel console.log('Saving torrent ' + torrentKey + ' to ' + savePath) const torrentPath = TorrentSummary.getTorrentPath(torrentSummary) - fs.readFile(torrentPath, function (err, torrentFile) { + fs.readFile(torrentPath, (err, torrentFile) => { if (err) return dispatch('error', err) - fs.writeFile(savePath, torrentFile, function (err) { + fs.writeFile(savePath, torrentFile, err => { if (err) return dispatch('error', err) }) }) @@ -346,8 +345,8 @@ function findFilesRecursive (paths, cb_) { if (paths.length > 1) { let numComplete = 0 const ret = [] - paths.forEach(function (path) { - findFilesRecursive([path], function (fileObjs) { + paths.forEach(path => { + findFilesRecursive([path], fileObjs => { ret.push(...fileObjs) if (++numComplete === paths.length) { ret.sort((a, b) => a.path < b.path ? -1 : Number(a.path > b.path)) @@ -359,7 +358,7 @@ function findFilesRecursive (paths, cb_) { } const fileOrFolder = paths[0] - fs.stat(fileOrFolder, function (err, stat) { + fs.stat(fileOrFolder, (err, stat) => { if (err) return dispatch('error', err) // Files: return name, path, and size @@ -374,7 +373,7 @@ function findFilesRecursive (paths, cb_) { // Folders: recurse, make a list of all the files const folderPath = fileOrFolder - fs.readdir(folderPath, function (err, fileNames) { + fs.readdir(folderPath, (err, fileNames) => { if (err) return dispatch('error', err) const paths = fileNames.map((fileName) => path.join(folderPath, fileName)) findFilesRecursive(paths, cb_) @@ -384,7 +383,7 @@ function findFilesRecursive (paths, cb_) { function deleteFile (path) { if (!path) return - fs.unlink(path, function (err) { + fs.unlink(path, err => { if (err) dispatch('error', err) }) } diff --git a/src/renderer/lib/cast.js b/src/renderer/lib/cast.js index c0ffc103..d1339446 100644 --- a/src/renderer/lib/cast.js +++ b/src/renderer/lib/cast.js @@ -19,7 +19,10 @@ const config = require('../../config') const { CastingError } = require('./errors') // Lazy load these for a ~300ms improvement in startup time -let airplayer, chromecasts, dlnacasts +let airplayer; + +let chromecasts; +let dlnacasts; // App state. Cast modifies state.playing and state.errors in response to events let state @@ -54,17 +57,17 @@ function init (appState, callback) { state.devices.airplay = airplayPlayer() // Listen for devices: Chromecast, DLNA and Airplay - chromecasts.on('update', function (device) { + chromecasts.on('update', device => { // TODO: how do we tell if there are *no longer* any Chromecasts available? // From looking at the code, chromecasts.players only grows, never shrinks state.devices.chromecast.addDevice(device) }) - dlnacasts.on('update', function (device) { + dlnacasts.on('update', device => { state.devices.dlna.addDevice(device) }) - airplayer.on('update', function (device) { + airplayer.on('update', device => { state.devices.airplay.addDevice(device) }) } @@ -116,7 +119,7 @@ function chromecastPlayer () { } function addDevice (device) { - device.on('error', function (err) { + device.on('error', err => { if (device !== ret.device) return state.playing.location = 'local' state.errors.push({ @@ -125,7 +128,7 @@ function chromecastPlayer () { }) update() }) - device.on('disconnect', function () { + device.on('disconnect', () => { if (device !== ret.device) return state.playing.location = 'local' update() @@ -145,7 +148,7 @@ function chromecastPlayer () { 'Transfer-Encoding': 'chunked' }) res.end(Buffer.from(selectedSubtitle.buffer.substr(21), 'base64')) - }).listen(0, function () { + }).listen(0, () => { const port = ret.subServer.address().port const subtitlesUrl = 'http://' + state.server.networkAddress + ':' + port + '/' callback(subtitlesUrl) @@ -155,13 +158,13 @@ function chromecastPlayer () { function open () { const torrentSummary = state.saved.torrents.find((x) => x.infoHash === state.playing.infoHash) - serveSubtitles(function (subtitlesUrl) { + serveSubtitles(subtitlesUrl => { ret.device.play(state.server.networkURL + '/' + state.playing.fileIndex, { type: 'video/mp4', title: config.APP_NAME + ' - ' + torrentSummary.name, subtitles: subtitlesUrl ? [subtitlesUrl] : [], autoSubtitles: !!subtitlesUrl - }, function (err) { + }, err => { if (err) { state.playing.location = 'local' state.errors.push({ @@ -221,7 +224,7 @@ function airplayPlayer () { return ret function addDevice (player) { - player.on('event', function (event) { + player.on('event', event => { switch (event.state) { case 'loading': break @@ -243,7 +246,7 @@ function airplayPlayer () { } function open () { - ret.device.play(state.server.networkURL + '/' + state.playing.fileIndex, function (err, res) { + ret.device.play(state.server.networkURL + '/' + state.playing.fileIndex, (err, res) => { if (err) { state.playing.location = 'local' state.errors.push({ @@ -270,7 +273,7 @@ function airplayPlayer () { } function status () { - ret.device.playbackInfo(function (err, res, status) { + ret.device.playbackInfo((err, res, status) => { if (err) { state.playing.location = 'local' state.errors.push({ @@ -317,7 +320,7 @@ function dlnaPlayer (player) { } function addDevice (device) { - device.on('error', function (err) { + device.on('error', err => { if (device !== ret.device) return state.playing.location = 'local' state.errors.push({ @@ -326,7 +329,7 @@ function dlnaPlayer (player) { }) update() }) - device.on('disconnect', function () { + device.on('disconnect', () => { if (device !== ret.device) return state.playing.location = 'local' update() @@ -339,7 +342,7 @@ function dlnaPlayer (player) { type: 'video/mp4', title: config.APP_NAME + ' - ' + torrentSummary.name, seek: state.playing.currentTime > 10 ? state.playing.currentTime : 0 - }, function (err) { + }, err => { if (err) { state.playing.location = 'local' state.errors.push({ @@ -374,7 +377,7 @@ function dlnaPlayer (player) { } function volume (volume, callback) { - ret.device.volume(volume, function (err) { + ret.device.volume(volume, err => { // quick volume update state.playing.volume = volume callback(err) @@ -396,7 +399,7 @@ function handleStatus (err, status) { // Start polling cast device state, whenever we're connected function startStatusInterval () { - statusInterval = setInterval(function () { + statusInterval = setInterval(() => { const player = getPlayer() if (player) player.status() }, 1000) @@ -454,7 +457,7 @@ function selectDevice (index) { function stop () { const player = getPlayer() if (player) { - player.stop(function () { + player.stop(() => { player.device = null stoppedCasting() }) @@ -522,6 +525,6 @@ function setVolume (volume) { if (player) player.volume(volume, castCallback) } -function castCallback () { - console.log('%s callback: %o', state.playing.location, arguments) +function castCallback(...args) { + console.log('%s callback: %o', state.playing.location, args) } diff --git a/src/renderer/lib/dispatcher.js b/src/renderer/lib/dispatcher.js index 1b6cd23d..d2a84951 100644 --- a/src/renderer/lib/dispatcher.js +++ b/src/renderer/lib/dispatcher.js @@ -5,7 +5,7 @@ module.exports = { } const dispatchers = {} -let _dispatch = function () {} +let _dispatch = () => {} function setDispatch (dispatch) { _dispatch = dispatch @@ -23,7 +23,7 @@ function dispatcher (...args) { const str = JSON.stringify(args) let handler = dispatchers[str] if (!handler) { - handler = dispatchers[str] = function (e) { + handler = dispatchers[str] = e => { // Do not propagate click to elements below the button e.stopPropagation() diff --git a/src/renderer/lib/migrations.js b/src/renderer/lib/migrations.js index 21fe646f..fb760b07 100644 --- a/src/renderer/lib/migrations.js +++ b/src/renderer/lib/migrations.js @@ -52,7 +52,7 @@ function migrate_0_7_0 (saved) { const { copyFileSync } = require('fs') const path = require('path') - saved.torrents.forEach(function (ts) { + saved.torrents.forEach(ts => { const infoHash = ts.infoHash // Replace torrentPath with torrentFileName @@ -61,7 +61,9 @@ function migrate_0_7_0 (saved) { // * Then, relative paths for the default torrents, eg '../static/sintel.torrent' // * Then, paths computed at runtime for default torrents, eg 'sintel.torrent' // * Finally, now we're getting rid of torrentPath altogether - let src, dst + let src; + + let dst; if (ts.torrentPath) { if (path.isAbsolute(ts.torrentPath) || ts.torrentPath.startsWith('..')) { src = ts.torrentPath @@ -134,7 +136,7 @@ function migrate_0_12_0 (saved) { '02767050e0be2fd4db9a2ad6c12416ac806ed6ed.torrent', '3ba219a8634bf7bae3d848192b2da75ae995589d.torrent' ] - saved.torrents.forEach(function (torrentSummary) { + saved.torrents.forEach(torrentSummary => { if (!defaultTorrentFiles.includes(torrentSummary.torrentFileName)) return const fileOrFolder = TorrentSummary.getFileOrFolder(torrentSummary) if (!fileOrFolder) return @@ -148,16 +150,16 @@ function migrate_0_12_0 (saved) { } function migrate_0_14_0 (saved) { - saved.torrents.forEach(function (ts) { + saved.torrents.forEach(ts => { delete ts.defaultPlayFileIndex }) } function migrate_0_17_0 (saved) { // Fix a sad, sad bug that resulted in 100MB+ config.json files - saved.torrents.forEach(function (ts) { + saved.torrents.forEach(ts => { if (!ts.files) return - ts.files.forEach(function (file) { + ts.files.forEach(file => { if (!file.audioInfo || !file.audioInfo.picture) return // This contained a Buffer, which 30x'd in size when serialized to JSON delete file.audioInfo.picture @@ -179,9 +181,7 @@ function migrate_0_17_2 (saved) { const OLD_HASH = '3ba219a8634bf7bae3d848192b2da75ae995589d' const NEW_HASH = 'a88fda5954e89178c372716a6a78b8180ed4dad3' - const ts = saved.torrents.find((ts) => { - return ts.infoHash === OLD_HASH - }) + const ts = saved.torrents.find(ts => ts.infoHash === OLD_HASH) if (!ts) return // Wired CD torrent does not exist diff --git a/src/renderer/lib/state.js b/src/renderer/lib/state.js index e41f718a..f279cdc4 100644 --- a/src/renderer/lib/state.js +++ b/src/renderer/lib/state.js @@ -12,13 +12,13 @@ const State = module.exports = Object.assign(new EventEmitter(), { getDefaultPlayState, load, // state.save() calls are rate-limited. Use state.saveImmediate() to skip limit. - save: function () { + save(...args) { // Perf optimization: Lazy-require debounce (and it's dependencies) const debounce = require('debounce') // After first State.save() invokation, future calls go straight to the // debounced function State.save = debounce(saveImmediate, SAVE_DEBOUNCE_INTERVAL) - State.save(...arguments) + State.save(...args) }, saveImmediate }) @@ -242,7 +242,7 @@ async function saveImmediate (state, cb) { // reading the torrent file or file(s) to seed & don't have an infohash copy.torrents = copy.torrents .filter((x) => x.infoHash) - .map(function (x) { + .map(x => { const torrent = {} for (const key in x) { if (key === 'progress' || key === 'torrentKey') { diff --git a/src/renderer/lib/telemetry.js b/src/renderer/lib/telemetry.js index 5143ba52..6acdaef7 100644 --- a/src/renderer/lib/telemetry.js +++ b/src/renderer/lib/telemetry.js @@ -50,7 +50,7 @@ function send (state) { json: true } - get.post(opts, function (err, res) { + get.post(opts, (err, res) => { if (err) return console.error('Error sending telemetry', err) if (res.statusCode !== 200) { return console.error(`Error sending telemetry, status code: ${res.statusCode}`) @@ -106,15 +106,14 @@ function getTorrentStats (state) { } // First, count torrents & total file size - for (let i = 0; i < count; i++) { - const t = state.saved.torrents[i] - const stat = byStatus[t.status] - if (!t || !t.files || !stat) continue + for (const torrent of state.saved.torrents) { + const stat = byStatus[torrent.status] + if (!torrent || !torrent.files || !stat) continue stat.count++ - for (let j = 0; j < t.files.length; j++) { - const f = t.files[j] - if (!f || !f.length) continue - const fileSizeMB = f.length / (1 << 20) + + for (const file of torrent.files) { + if (!file || !file.length) continue + const fileSizeMB = file.length / (1 << 20) sizeMB += fileSizeMB stat.sizeMB += fileSizeMB } @@ -145,7 +144,7 @@ function roundPow2 (n) { if (n <= 0) return 0 // Otherwise, return 1, 2, 4, 8, etc by rounding in log space const log2 = Math.log(n) / Math.log(2) - return Math.pow(2, Math.round(log2)) + return 2 ** Math.round(log2) } // An uncaught error happened in the main process or in one of the windows diff --git a/src/renderer/lib/torrent-poster.js b/src/renderer/lib/torrent-poster.js index 3fcc2d57..eab77278 100644 --- a/src/renderer/lib/torrent-poster.js +++ b/src/renderer/lib/torrent-poster.js @@ -9,20 +9,15 @@ const msgNoSuitablePoster = 'Cannot generate a poster from any files in the torr function torrentPoster (torrent, cb) { // First, try to use a poster image if available - const posterFile = torrent.files.filter(function (file) { - return /^poster\.(jpg|png|gif)$/.test(file.name) - })[0] + const posterFile = torrent.files.filter(file => /^poster\.(jpg|png|gif)$/.test(file.name))[0] if (posterFile) return extractPoster(posterFile, cb) // 'score' each media type based on total size present in torrent - const bestScore = ['audio', 'video', 'image'].map(mediaType => { - return { - type: mediaType, - size: calculateDataLengthByExtension(torrent, mediaExtensions[mediaType]) - } - }).sort((a, b) => { // sort descending on size - return b.size - a.size - })[0] + const bestScore = ['audio', 'video', 'image'].map(mediaType => ({ + type: mediaType, + size: calculateDataLengthByExtension(torrent, mediaExtensions[mediaType]) + })).sort((a, b) => // sort descending on size + b.size - a.size)[0] if (bestScore.size === 0) { // Admit defeat, no video, audio or image had a significant presence @@ -51,9 +46,7 @@ function calculateDataLengthByExtension (torrent, extensions) { if (files.length === 0) return 0 return files .map(file => file.length) - .reduce((a, b) => { - return a + b - }) + .reduce((a, b) => a + b); } /** @@ -65,9 +58,7 @@ function calculateDataLengthByExtension (torrent, extensions) { function getLargestFileByExtension (torrent, extensions) { const files = filterOnExtension(torrent, extensions) if (files.length === 0) return undefined - return files.reduce((a, b) => { - return a.length > b.length ? a : b - }) + return files.reduce((a, b) => a.length > b.length ? a : b); } /** @@ -115,12 +106,10 @@ function torrentPosterFromAudio (torrent, cb) { if (imageFiles.length === 0) return cb(new Error(msgNoSuitablePoster)) - const bestCover = imageFiles.map(file => { - return { - file, - score: scoreAudioCoverFile(file) - } - }).reduce((a, b) => { + const bestCover = imageFiles.map(file => ({ + file, + score: scoreAudioCoverFile(file) + })).reduce((a, b) => { if (a.score > b.score) { return a } @@ -190,5 +179,5 @@ function torrentPosterFromImage (torrent, cb) { function extractPoster (file, cb) { const extname = path.extname(file.name) - file.getBuffer((err, buf) => { return cb(err, buf, extname) }) + file.getBuffer((err, buf) => cb(err, buf, extname)) } diff --git a/src/renderer/main.js b/src/renderer/main.js index 9d848c7f..945842ea 100644 --- a/src/renderer/main.js +++ b/src/renderer/main.js @@ -104,9 +104,7 @@ function onState (err, _state) { const TorrentController = require('./controllers/torrent-controller') return new TorrentController(state) }), - torrentList: createGetter(() => { - return new TorrentListController(state) - }), + torrentList: createGetter(() => new TorrentListController(state)), update: createGetter(() => { const UpdateController = require('./controllers/update-controller') return new UpdateController(state) @@ -155,11 +153,11 @@ function onState (err, _state) { // Add YouTube style hotkey shortcuts window.addEventListener('keydown', onKeydown) - const debouncedFullscreenToggle = debounce(function () { + const debouncedFullscreenToggle = debounce(() => { dispatch('toggleFullScreen') }, 1000, true) - document.addEventListener('wheel', function (event) { + document.addEventListener('wheel', event => { // ctrlKey detects pinch to zoom, http://crbug.com/289887 if (event.ctrlKey) { event.preventDefault() @@ -400,7 +398,7 @@ function setupIpc () { function backToList () { // Exit any modals and screens with a back button state.modal = null - state.location.backToFirst(function () { + state.location.backToFirst(() => { // If we were already on the torrent list, scroll to the top const contentTag = document.querySelector('.content') if (contentTag) contentTag.scrollTop = 0 @@ -590,7 +588,7 @@ function onWindowBoundsChanged (e, newBounds) { } function checkDownloadPath () { - fs.stat(state.saved.prefs.downloadPath, function (err, stat) { + fs.stat(state.saved.prefs.downloadPath, (err, stat) => { if (err) { state.downloadPathStatus = 'missing' return console.error(err) diff --git a/src/renderer/pages/app.js b/src/renderer/pages/app.js index 1709f127..d07bc3d1 100644 --- a/src/renderer/pages/app.js +++ b/src/renderer/pages/app.js @@ -86,9 +86,7 @@ class App extends React.Component { const recentErrors = state.errors.filter((x) => now - x.time < 5000) const hasErrors = recentErrors.length > 0 - const errorElems = recentErrors.map(function (error, i) { - return (
{error.message}
) - }) + const errorElems = recentErrors.map((error, i) =>
{error.message}
) return (
torrent name 'foo.jpg', path '/a/b' defaultName = files[0].name diff --git a/src/renderer/pages/player-page.js b/src/renderer/pages/player-page.js index 6b16cc8f..96568e6a 100644 --- a/src/renderer/pages/player-page.js +++ b/src/renderer/pages/player-page.js @@ -109,8 +109,7 @@ function renderMedia (state) { // Add subtitles to the