code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function toggleDevTools () {
if (!main.win) return
log('toggleDevTools')
if (main.win.webContents.isDevToolsOpened()) {
main.win.webContents.closeDevTools()
} else {
main.win.webContents.openDevTools({ mode: 'detach' })
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | toggleDevTools | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function toggleFullScreen (flag) {
if (!main.win || !main.win.isVisible()) {
return
}
if (flag == null) flag = !main.win.isFullScreen()
log(`toggleFullScreen ${flag}`)
if (flag) {
// Fullscreen and aspect ratio do not play well together. (Mac)
main.win.setAspectRatio(0)
}
main.win.setFullScreen(flag)
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | toggleFullScreen | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onWindowBlur () {
menu.setWindowFocus(false)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(false)
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | onWindowBlur | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onWindowFocus () {
menu.setWindowFocus(true)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(true)
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | onWindowFocus | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function getIconPath () {
return process.platform === 'win32'
? config.APP_ICON + '.ico'
: config.APP_ICON + '.png'
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | getIconPath | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onState (err, _state) {
if (err) return onError(err)
// Make available for easier debugging
state = window.state = _state
window.dispatch = dispatch
telemetry.init(state)
sound.init(state)
// Log uncaught JS errors
window.addEventListener(
'error', (e) => telemetry.logUncaughtError('window', e), true /* capture */
)
// Create controllers
controllers = {
media: createGetter(() => {
const MediaController = require('./controllers/media-controller')
return new MediaController(state)
}),
playback: createGetter(() => {
const PlaybackController = require('./controllers/playback-controller')
return new PlaybackController(state, config, update)
}),
prefs: createGetter(() => {
const PrefsController = require('./controllers/prefs-controller')
return new PrefsController(state, config)
}),
subtitles: createGetter(() => {
const SubtitlesController = require('./controllers/subtitles-controller')
return new SubtitlesController(state)
}),
audioTracks: createGetter(() => {
const AudioTracksController = require('./controllers/audio-tracks-controller')
return new AudioTracksController(state)
}),
torrent: createGetter(() => {
const TorrentController = require('./controllers/torrent-controller')
return new TorrentController(state)
}),
torrentList: createGetter(() => new TorrentListController(state)),
update: createGetter(() => {
const UpdateController = require('./controllers/update-controller')
return new UpdateController(state)
}),
folderWatcher: createGetter(() => {
const FolderWatcherController = require('./controllers/folder-watcher-controller')
return new FolderWatcherController()
})
}
// Add first page to location history
state.location.go({
url: 'home',
setup: (cb) => {
state.window.title = config.APP_WINDOW_TITLE
cb(null)
}
})
// Give global trackers
setGlobalTrackers()
// Restart everything we were torrenting last time the app ran
resumeTorrents()
// Initialize ReactDOM
ReactDOM.render(
<App state={state} ref={elem => { app = elem }} />,
document.querySelector('#body')
)
// Calling update() updates the UI given the current state
// Do this at least once a second to give every file in every torrentSummary
// a progress bar and to keep the cursor in sync when playing a video
setInterval(update, 1000)
// Listen for messages from the main process
setupIpc()
// Drag and drop files/text to start torrenting or seeding
dragDrop('body', {
onDrop: onOpen,
onDropText: onOpen
})
// ...same thing if you paste a torrent
document.addEventListener('paste', onPaste)
// Add YouTube style hotkey shortcuts
window.addEventListener('keydown', onKeydown)
const debouncedFullscreenToggle = debounce(() => {
dispatch('toggleFullScreen')
}, 1000, true)
document.addEventListener('wheel', event => {
// ctrlKey detects pinch to zoom, http://crbug.com/289887
if (event.ctrlKey) {
event.preventDefault()
debouncedFullscreenToggle()
}
})
// ...focus and blur. Needed to show correct dock icon text ('badge') in OSX
window.addEventListener('focus', onFocus)
window.addEventListener('blur', onBlur)
if (electron.remote.getCurrentWindow().isVisible()) {
sound.play('STARTUP')
}
// To keep app startup fast, some code is delayed.
window.setTimeout(delayedInit, config.DELAYED_INIT)
// Done! Ideally we want to get here < 500ms after the user clicks the app
console.timeEnd('init')
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onState | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function delayedInit () {
telemetry.send(state)
// Send telemetry data every 12 hours, for users who keep the app running
// for extended periods of time
setInterval(() => telemetry.send(state), 12 * 3600 * 1000)
// Warn if the download dir is gone, eg b/c an external drive is unplugged
checkDownloadPath()
// ...window visibility state.
document.addEventListener('webkitvisibilitychange', onVisibilityChange)
onVisibilityChange()
lazyLoadCast()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | delayedInit | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function lazyLoadCast () {
if (!Cast) {
Cast = require('./lib/cast')
Cast.init(state, update) // Search the local network for Chromecast and Airplays
}
return Cast
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | lazyLoadCast | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function update () {
controllers.playback().showOrHidePlayerControls()
app.setState(state)
updateElectron()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | update | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function updateElectron () {
if (state.window.title !== state.prev.title) {
state.prev.title = state.window.title
ipcRenderer.send('setTitle', state.window.title)
}
if (state.dock.progress.toFixed(2) !== state.prev.progress.toFixed(2)) {
state.prev.progress = state.dock.progress
ipcRenderer.send('setProgress', state.dock.progress)
}
if (state.dock.badge !== state.prev.badge) {
state.prev.badge = state.dock.badge
ipcRenderer.send('setBadge', state.dock.badge || 0)
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | updateElectron | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function dispatch (action, ...args) {
// Log dispatch calls, for debugging, but don't spam
if (!['mediaMouseMoved', 'mediaTimeUpdate', 'update'].includes(action)) {
console.log('dispatch: %s %o', action, args)
}
const handler = dispatchHandlers[action]
if (handler) handler(...args)
else console.error('Missing dispatch handler: ' + action)
// Update the virtual DOM, unless it's just a mouse move event
if (action !== 'mediaMouseMoved' ||
controllers.playback().showOrHidePlayerControls()) {
update()
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | dispatch | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function setupIpc () {
ipcRenderer.on('log', (e, ...args) => console.log(...args))
ipcRenderer.on('error', (e, ...args) => console.error(...args))
ipcRenderer.on('dispatch', (e, ...args) => dispatch(...args))
ipcRenderer.on('fullscreenChanged', onFullscreenChanged)
ipcRenderer.on('windowBoundsChanged', onWindowBoundsChanged)
const tc = controllers.torrent()
ipcRenderer.on('wt-parsed', (e, ...args) => tc.torrentParsed(...args))
ipcRenderer.on('wt-metadata', (e, ...args) => tc.torrentMetadata(...args))
ipcRenderer.on('wt-done', (e, ...args) => tc.torrentDone(...args))
ipcRenderer.on('wt-done', () => controllers.torrentList().resumePausedTorrents())
ipcRenderer.on('wt-warning', (e, ...args) => tc.torrentWarning(...args))
ipcRenderer.on('wt-error', (e, ...args) => tc.torrentError(...args))
ipcRenderer.on('wt-progress', (e, ...args) => tc.torrentProgress(...args))
ipcRenderer.on('wt-file-modtimes', (e, ...args) => tc.torrentFileModtimes(...args))
ipcRenderer.on('wt-file-saved', (e, ...args) => tc.torrentFileSaved(...args))
ipcRenderer.on('wt-poster', (e, ...args) => tc.torrentPosterSaved(...args))
ipcRenderer.on('wt-audio-metadata', (e, ...args) => tc.torrentAudioMetadata(...args))
ipcRenderer.on('wt-server-running', (e, ...args) => tc.torrentServerRunning(...args))
ipcRenderer.on('wt-uncaught-error', (e, err) => telemetry.logUncaughtError('webtorrent', err))
ipcRenderer.send('ipcReady')
State.on('stateSaved', () => ipcRenderer.send('stateSaved'))
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | setupIpc | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function backToList () {
// Exit any modals and screens with a back button
state.modal = null
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
})
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | backToList | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function escapeBack () {
if (state.modal) {
dispatch('exitModal')
} else if (state.window.isFullScreen) {
dispatch('toggleFullScreen')
} else {
dispatch('back')
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | escapeBack | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function resumeTorrents () {
state.saved.torrents
.map((torrentSummary) => {
// Torrent keys are ephemeral, reassigned each time the app runs.
// On startup, give all torrents a key, even the ones that are paused.
torrentSummary.torrentKey = state.nextTorrentKey++
return torrentSummary
})
.filter((s) => s.status !== 'paused')
.forEach((s) => controllers.torrentList().startTorrentingSummary(s.torrentKey))
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | resumeTorrents | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function setDimensions (dimensions) {
// Don't modify the window size if it's already maximized
if (electron.remote.getCurrentWindow().isMaximized()) {
state.window.bounds = null
return
}
// Save the bounds of the window for later. See restoreBounds()
state.window.bounds = {
x: window.screenX,
y: window.screenY,
width: window.outerWidth,
height: window.outerHeight
}
state.window.wasMaximized = electron.remote.getCurrentWindow().isMaximized
// Limit window size to screen size
const screenWidth = window.screen.width
const screenHeight = window.screen.height
const aspectRatio = dimensions.width / dimensions.height
const scaleFactor = Math.min(
Math.min(screenWidth / dimensions.width, 1),
Math.min(screenHeight / dimensions.height, 1)
)
const width = Math.max(
Math.floor(dimensions.width * scaleFactor),
config.WINDOW_MIN_WIDTH
)
const height = Math.max(
Math.floor(dimensions.height * scaleFactor),
config.WINDOW_MIN_HEIGHT
)
ipcRenderer.send('setAspectRatio', aspectRatio)
ipcRenderer.send('setBounds', { contentBounds: true, x: null, y: null, width, height })
state.playing.aspectRatio = aspectRatio
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | setDimensions | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onOpen (files) {
if (!Array.isArray(files)) files = [files]
// File API seems to transform "magnet:?foo" in "magnet:///?foo"
// this is a sanitization
files = files.map(file => {
if (typeof file !== 'string') return file
return file.replace(/^magnet:\/+\?/i, 'magnet:?')
})
const url = state.location.url()
const allTorrents = files.every(TorrentPlayer.isTorrent)
const allSubtitles = files.every(controllers.subtitles().isSubtitle)
if (allTorrents) {
// Drop torrents onto the app: go to home screen, add torrents, no matter what
dispatch('backToList')
// All .torrent files? Add them.
files.forEach((file) => controllers.torrentList().addTorrent(file))
} else if (url === 'player' && allSubtitles) {
// Drop subtitles onto a playing video: add subtitles
controllers.subtitles().addSubtitles(files, true)
} else if (url === 'home') {
// Drop files onto home screen: show Create Torrent
state.modal = null
controllers.torrentList().showCreateTorrent(files)
} else {
// Drop files onto any other screen: show error
return onError('Please go back to the torrent list before creating a new torrent.')
}
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onOpen | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onError (err) {
console.error(err.stack || err)
sound.play('ERROR')
state.errors.push({
time: new Date().getTime(),
message: err.message || err
})
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onError | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onPaste (e) {
if (e && editableHtmlTags.has(e.target.tagName.toLowerCase())) return
controllers.torrentList().addTorrent(electron.clipboard.readText())
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onPaste | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onKeydown (e) {
// prevent event fire on user input elements
if (editableHtmlTags.has(e.target.tagName.toLowerCase())) return
const key = e.key
if (key === 'ArrowLeft') {
dispatch('skip', -5)
} else if (key === 'ArrowRight') {
dispatch('skip', 5)
} else if (key === 'ArrowUp') {
dispatch('changeVolume', 0.1)
} else if (key === 'ArrowDown') {
dispatch('changeVolume', -0.1)
} else if (key === 'j') {
dispatch('skip', -10)
} else if (key === 'l') {
dispatch('skip', 10)
} else if (key === 'k') {
dispatch('playPause')
} else if (key === '>') {
dispatch('changePlaybackRate', 1)
} else if (key === '<') {
dispatch('changePlaybackRate', -1)
} else if (key === 'f') {
dispatch('toggleFullScreen')
}
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onKeydown | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onFocus (e) {
state.window.isFocused = true
state.dock.badge = 0
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onFocus | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onBlur () {
state.window.isFocused = false
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onBlur | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onVisibilityChange () {
state.window.isVisible = !document.hidden
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onVisibilityChange | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onFullscreenChanged (e, isFullScreen) {
state.window.isFullScreen = isFullScreen
if (!isFullScreen) {
// Aspect ratio gets reset in fullscreen mode, so restore it (Mac)
ipcRenderer.send('setAspectRatio', state.playing.aspectRatio)
}
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onFullscreenChanged | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onWindowBoundsChanged (e, newBounds) {
if (state.location.url() !== 'player') {
state.saved.bounds = newBounds
dispatch('stateSave')
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onWindowBoundsChanged | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function checkDownloadPath () {
fs.stat(state.saved.prefs.downloadPath, (err, stat) => {
if (err) {
state.downloadPathStatus = 'missing'
return console.error(err)
}
if (stat.isDirectory()) state.downloadPathStatus = 'ok'
else state.downloadPathStatus = 'missing'
})
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | checkDownloadPath | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function init () {
listenToClientEvents()
ipcRenderer.on('wt-set-global-trackers', (e, globalTrackers) =>
setGlobalTrackers(globalTrackers))
ipcRenderer.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) =>
startTorrenting(torrentKey, torrentID, path, fileModtimes, selections))
ipcRenderer.on('wt-stop-torrenting', (e, infoHash) =>
stopTorrenting(infoHash))
ipcRenderer.on('wt-create-torrent', (e, torrentKey, options) =>
createTorrent(torrentKey, options))
ipcRenderer.on('wt-save-torrent-file', (e, torrentKey) =>
saveTorrentFile(torrentKey))
ipcRenderer.on('wt-generate-torrent-poster', (e, torrentKey) =>
generateTorrentPoster(torrentKey))
ipcRenderer.on('wt-get-audio-metadata', (e, infoHash, index) =>
getAudioMetadata(infoHash, index))
ipcRenderer.on('wt-start-server', (e, infoHash) =>
startServer(infoHash))
ipcRenderer.on('wt-stop-server', () =>
stopServer())
ipcRenderer.on('wt-select-files', (e, infoHash, selections) =>
selectFiles(infoHash, selections))
ipcRenderer.send('ipcReadyWebTorrent')
window.addEventListener('error', (e) =>
ipcRenderer.send('wt-uncaught-error', { message: e.error.message, stack: e.error.stack }),
true)
setInterval(updateTorrentProgress, 1000)
console.timeEnd('init')
} | Generate an ephemeral peer ID each time. | init | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function listenToClientEvents () {
client.on('warning', (err) => ipcRenderer.send('wt-warning', null, err.message))
client.on('error', (err) => ipcRenderer.send('wt-error', null, err.message))
} | Generate an ephemeral peer ID each time. | listenToClientEvents | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function setGlobalTrackers (globalTrackers) {
globalThis.WEBTORRENT_ANNOUNCE = globalTrackers
} | Generate an ephemeral peer ID each time. | setGlobalTrackers | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startTorrenting (torrentKey, torrentID, path, fileModtimes, selections) {
console.log('starting torrent %s: %s', torrentKey, torrentID)
const torrent = client.add(torrentID, {
path,
fileModtimes
})
torrent.key = torrentKey
// Listen for ready event, progress notifications, etc
addTorrentEvents(torrent)
// Only download the files the user wants, not necessarily all files
torrent.once('ready', () => selectFiles(torrent, selections))
} | Generate an ephemeral peer ID each time. | startTorrenting | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function stopTorrenting (infoHash) {
console.log('--- STOP TORRENTING: ', infoHash)
const torrent = client.get(infoHash)
if (torrent) torrent.destroy()
} | Generate an ephemeral peer ID each time. | stopTorrenting | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function createTorrent (torrentKey, options) {
console.log('creating torrent', torrentKey, options)
const paths = options.files.map((f) => f.path)
const torrent = client.seed(paths, options)
torrent.key = torrentKey
addTorrentEvents(torrent)
ipcRenderer.send('wt-new-torrent')
} | Generate an ephemeral peer ID each time. | createTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function addTorrentEvents (torrent) {
torrent.on('warning', (err) =>
ipcRenderer.send('wt-warning', torrent.key, err.message))
torrent.on('error', (err) =>
ipcRenderer.send('wt-error', torrent.key, err.message))
torrent.on('infoHash', () =>
ipcRenderer.send('wt-parsed', torrent.key, torrent.infoHash, torrent.magnetURI))
torrent.on('metadata', torrentMetadata)
torrent.on('ready', torrentReady)
torrent.on('done', torrentDone)
function torrentMetadata () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-metadata', torrent.key, info)
updateTorrentProgress()
}
function torrentReady () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-ready', torrent.key, info)
ipcRenderer.send('wt-ready-' + torrent.infoHash, torrent.key, info)
updateTorrentProgress()
}
function torrentDone () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-done', torrent.key, info)
updateTorrentProgress()
torrent.getFileModtimes((err, fileModtimes) => {
if (err) return onError(err)
ipcRenderer.send('wt-file-modtimes', torrent.key, fileModtimes)
})
}
} | Generate an ephemeral peer ID each time. | addTorrentEvents | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentMetadata () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-metadata', torrent.key, info)
updateTorrentProgress()
} | Generate an ephemeral peer ID each time. | torrentMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentReady () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-ready', torrent.key, info)
ipcRenderer.send('wt-ready-' + torrent.infoHash, torrent.key, info)
updateTorrentProgress()
} | Generate an ephemeral peer ID each time. | torrentReady | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentDone () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-done', torrent.key, info)
updateTorrentProgress()
torrent.getFileModtimes((err, fileModtimes) => {
if (err) return onError(err)
ipcRenderer.send('wt-file-modtimes', torrent.key, fileModtimes)
})
} | Generate an ephemeral peer ID each time. | torrentDone | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentInfo (torrent) {
return {
infoHash: torrent.infoHash,
magnetURI: torrent.magnetURI,
name: torrent.name,
path: torrent.path,
files: torrent.files.map(getTorrentFileInfo),
bytesReceived: torrent.received
}
} | Generate an ephemeral peer ID each time. | getTorrentInfo | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentFileInfo (file) {
return {
name: file.name,
length: file.length,
path: file.path
}
} | Generate an ephemeral peer ID each time. | getTorrentFileInfo | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function saveTorrentFile (torrentKey) {
const torrent = getTorrent(torrentKey)
const torrentPath = path.join(config.TORRENT_PATH, torrent.infoHash + '.torrent')
fs.access(torrentPath, fs.constants.R_OK, err => {
const fileName = torrent.infoHash + '.torrent'
if (!err) {
// We've already saved the file
return ipcRenderer.send('wt-file-saved', torrentKey, fileName)
}
// Otherwise, save the .torrent file, under the app config folder
fs.mkdir(config.TORRENT_PATH, { recursive: true }, _ => {
fs.writeFile(torrentPath, torrent.torrentFile, err => {
if (err) return console.log('error saving torrent file %s: %o', torrentPath, err)
console.log('saved torrent file %s', torrentPath)
return ipcRenderer.send('wt-file-saved', torrentKey, fileName)
})
})
})
} | Generate an ephemeral peer ID each time. | saveTorrentFile | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function generateTorrentPoster (torrentKey) {
const torrent = getTorrent(torrentKey)
torrentPoster(torrent, (err, buf, extension) => {
if (err) return console.log('error generating poster: %o', err)
// save it for next time
fs.mkdir(config.POSTER_PATH, { recursive: true }, err => {
if (err) return console.log('error creating poster dir: %o', err)
const posterFileName = torrent.infoHash + extension
const posterFilePath = path.join(config.POSTER_PATH, posterFileName)
fs.writeFile(posterFilePath, buf, err => {
if (err) return console.log('error saving poster: %o', err)
// show the poster
ipcRenderer.send('wt-poster', torrentKey, posterFileName)
})
})
})
} | Generate an ephemeral peer ID each time. | generateTorrentPoster | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function updateTorrentProgress () {
const progress = getTorrentProgress()
// TODO: diff torrent-by-torrent, not once for the whole update
if (prevProgress && util.isDeepStrictEqual(progress, prevProgress)) {
return /* don't send heavy object if it hasn't changed */
}
ipcRenderer.send('wt-progress', progress)
prevProgress = progress
} | Generate an ephemeral peer ID each time. | updateTorrentProgress | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentProgress () {
// First, track overall progress
const progress = client.progress
const hasActiveTorrents = client.torrents.some(torrent => torrent.progress !== 1)
// Track progress for every file in each torrent
// TODO: ideally this would be tracked by WebTorrent, which could do it
// more efficiently than looping over torrent.bitfield
const torrentProg = client.torrents.map(torrent => {
const fileProg = torrent.files && torrent.files.map(file => {
const numPieces = file._endPiece - file._startPiece + 1
let numPiecesPresent = 0
for (let piece = file._startPiece; piece <= file._endPiece; piece++) {
if (torrent.bitfield.get(piece)) numPiecesPresent++
}
return {
startPiece: file._startPiece,
endPiece: file._endPiece,
numPieces,
numPiecesPresent
}
})
return {
torrentKey: torrent.key,
ready: torrent.ready,
progress: torrent.progress,
downloaded: torrent.downloaded,
downloadSpeed: torrent.downloadSpeed,
uploadSpeed: torrent.uploadSpeed,
numPeers: torrent.numPeers,
length: torrent.length,
bitfield: torrent.bitfield,
files: fileProg
}
})
return {
torrents: torrentProg,
progress,
hasActiveTorrents
}
} | Generate an ephemeral peer ID each time. | getTorrentProgress | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startServer (infoHash) {
const torrent = client.get(infoHash)
if (torrent.ready) startServerFromReadyTorrent(torrent)
else torrent.once('ready', () => startServerFromReadyTorrent(torrent))
} | Generate an ephemeral peer ID each time. | startServer | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startServerFromReadyTorrent (torrent) {
if (server) return
// start the streaming torrent-to-http server
server = torrent.createServer()
server.listen(0, () => {
const port = server.address().port
const urlSuffix = ':' + port
const info = {
torrentKey: torrent.key,
localURL: 'http://localhost' + urlSuffix,
networkURL: 'http://' + networkAddress() + urlSuffix,
networkAddress: networkAddress()
}
ipcRenderer.send('wt-server-running', info)
ipcRenderer.send('wt-server-' + torrent.infoHash, info)
})
} | Generate an ephemeral peer ID each time. | startServerFromReadyTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function stopServer () {
if (!server) return
server.destroy()
server = null
} | Generate an ephemeral peer ID each time. | stopServer | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getAudioMetadata (infoHash, index) {
const torrent = client.get(infoHash)
const file = torrent.files[index]
// Set initial matadata to display the filename first.
const metadata = { title: file.name }
ipcRenderer.send('wt-audio-metadata', infoHash, index, metadata)
const options = {
native: false,
skipCovers: true,
fileSize: file.length,
observer: () => {
ipcRenderer.send('wt-audio-metadata', infoHash, index, {
common: metadata.common,
format: metadata.format
})
}
}
const onMetadata = file.done
// If completed; use direct file access
? mm.parseFile(path.join(torrent.path, file.path), options)
// otherwise stream
: mm.parseStream(file.createReadStream(), file.name, options)
onMetadata
.then(
metadata => {
ipcRenderer.send('wt-audio-metadata', infoHash, index, metadata)
console.log(`metadata for file='${file.name}' completed.`)
},
err => {
console.log(
`error getting audio metadata for ${infoHash}:${index}`,
err
)
}
)
} | Generate an ephemeral peer ID each time. | getAudioMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function selectFiles (torrentOrInfoHash, selections) {
// Get the torrent object
let torrent
if (typeof torrentOrInfoHash === 'string') {
torrent = client.get(torrentOrInfoHash)
} else {
torrent = torrentOrInfoHash
}
if (!torrent) {
throw new Error('selectFiles: missing torrent ' + torrentOrInfoHash)
}
// Selections not specified?
// Load all files. We still need to replace the default whole-torrent
// selection with individual selections for each file, so we can
// select/deselect files later on
if (!selections) {
selections = new Array(torrent.files.length).fill(true)
}
// Selections specified incorrectly?
if (selections.length !== torrent.files.length) {
throw new Error('got ' + selections.length + ' file selections, ' +
'but the torrent contains ' + torrent.files.length + ' files')
}
// Remove default selection (whole torrent)
torrent.deselect(0, torrent.pieces.length - 1, false)
// Add selections (individual files)
selections.forEach((selection, i) => {
const file = torrent.files[i]
if (selection) {
file.select()
} else {
console.log('deselecting file ' + i + ' of torrent ' + torrent.name)
file.deselect()
}
})
} | Generate an ephemeral peer ID each time. | selectFiles | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrent (torrentKey) {
const ret = client.torrents.find((x) => x.key === torrentKey)
if (!ret) throw new TorrentKeyNotFoundError(torrentKey)
return ret
} | Generate an ephemeral peer ID each time. | getTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function calculateDataLengthByExtension (torrent, extensions) {
const files = filterOnExtension(torrent, extensions)
if (files.length === 0) return 0
return files
.map(file => file.length)
.reduce((a, b) => a + b)
} | Calculate the total data size of file matching one of the provided extensions
@param torrent
@param extensions List of extension to match
@returns {number} total size, of matches found (>= 0) | calculateDataLengthByExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function getLargestFileByExtension (torrent, extensions) {
const files = filterOnExtension(torrent, extensions)
if (files.length === 0) return undefined
return files.reduce((a, b) => a.length > b.length ? a : b)
} | Get the largest file of a given torrent, filtered by provided extension
@param torrent Torrent to search in
@param extensions Extension whitelist filter
@returns Torrent file object | getLargestFileByExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function filterOnExtension (torrent, extensions) {
return torrent.files.filter(file => {
const extname = path.extname(file.name).toLowerCase()
return extensions.indexOf(extname) !== -1
})
} | Filter file on a list extension, can be used to find al image files
@param torrent Torrent to filter files from
@param extensions File extensions to filter on
@returns {Array} Array of torrent file objects matching one of the given extensions | filterOnExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function scoreAudioCoverFile (imgFile) {
const fileName = path.basename(imgFile.name, path.extname(imgFile.name)).toLowerCase()
const relevanceScore = {
cover: 80,
folder: 80,
album: 80,
front: 80,
back: 20,
spectrogram: -80
}
for (const keyword in relevanceScore) {
if (fileName === keyword) {
return relevanceScore[keyword]
}
if (fileName.indexOf(keyword) !== -1) {
return relevanceScore[keyword]
}
}
return 0
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | scoreAudioCoverFile | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromAudio (torrent, cb) {
const imageFiles = filterOnExtension(torrent, mediaExtensions.image)
if (imageFiles.length === 0) return cb(new Error(msgNoSuitablePoster))
const bestCover = imageFiles.map(file => ({
file,
score: scoreAudioCoverFile(file)
})).reduce((a, b) => {
if (a.score > b.score) {
return a
}
if (b.score > a.score) {
return b
}
// If score is equal, pick the largest file, aiming for highest resolution
if (a.file.length > b.file.length) {
return a
}
return b
})
const extname = path.extname(bestCover.file.name)
bestCover.file.getBuffer((err, buf) => cb(err, buf, extname))
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromAudio | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromVideo (torrent, cb) {
const file = getLargestFileByExtension(torrent, mediaExtensions.video)
const index = torrent.files.indexOf(file)
const server = torrent.createServer(0)
server.listen(0, onListening)
function onListening () {
const port = server.address().port
const url = 'http://localhost:' + port + '/' + index
const video = document.createElement('video')
video.addEventListener('canplay', onCanPlay)
video.volume = 0
video.src = url
video.play()
function onCanPlay () {
video.removeEventListener('canplay', onCanPlay)
video.addEventListener('seeked', onSeeked)
video.currentTime = Math.min((video.duration || 600) * 0.03, 60)
}
function onSeeked () {
video.removeEventListener('seeked', onSeeked)
const frame = captureFrame(video)
const buf = frame && frame.image
// unload video element
video.pause()
video.src = ''
video.load()
server.destroy()
if (buf.length === 0) return cb(new Error(msgNoSuitablePoster))
cb(null, buf, '.jpg')
}
}
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromVideo | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onListening () {
const port = server.address().port
const url = 'http://localhost:' + port + '/' + index
const video = document.createElement('video')
video.addEventListener('canplay', onCanPlay)
video.volume = 0
video.src = url
video.play()
function onCanPlay () {
video.removeEventListener('canplay', onCanPlay)
video.addEventListener('seeked', onSeeked)
video.currentTime = Math.min((video.duration || 600) * 0.03, 60)
}
function onSeeked () {
video.removeEventListener('seeked', onSeeked)
const frame = captureFrame(video)
const buf = frame && frame.image
// unload video element
video.pause()
video.src = ''
video.load()
server.destroy()
if (buf.length === 0) return cb(new Error(msgNoSuitablePoster))
cb(null, buf, '.jpg')
}
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onListening | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onCanPlay () {
video.removeEventListener('canplay', onCanPlay)
video.addEventListener('seeked', onSeeked)
video.currentTime = Math.min((video.duration || 600) * 0.03, 60)
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onCanPlay | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onSeeked () {
video.removeEventListener('seeked', onSeeked)
const frame = captureFrame(video)
const buf = frame && frame.image
// unload video element
video.pause()
video.src = ''
video.load()
server.destroy()
if (buf.length === 0) return cb(new Error(msgNoSuitablePoster))
cb(null, buf, '.jpg')
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onSeeked | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromImage (torrent, cb) {
const file = getLargestFileByExtension(torrent, mediaExtensions.image)
extractPoster(file, cb)
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromImage | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function extractPoster (file, cb) {
const extname = path.extname(file.name)
file.getBuffer((err, buf) => cb(err, buf, extname))
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | extractPoster | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function renderTrack (common, key) {
// Audio metadata: track-number
if (common[key] && common[key].no) {
let str = `${common[key].no}`
if (common[key].of) {
str += ` of ${common[key].of}`
}
const style = { textTransform: 'capitalize' }
return (
<div className={`audio-${key}`}>
<label style={style}>{key}</label> {str}
</div>
)
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderTrack | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderAudioMetadata (state) {
const fileSummary = state.getPlayingFileSummary()
if (!fileSummary.audioInfo) return
const common = fileSummary.audioInfo.common || {}
// Get audio track info
const title = common.title ? common.title : fileSummary.name
// Show a small info box in the middle of the screen with title/album/etc
const elems = []
// Audio metadata: artist(s)
const artist = common.artist || common.albumartist
if (artist) {
elems.push((
<div key='artist' className='audio-artist'>
<label>Artist</label>{artist}
</div>
))
}
// Audio metadata: disk & track-number
const count = ['track', 'disk']
count.forEach(key => {
const nrElem = renderTrack(common, key)
if (nrElem) {
elems.push(nrElem)
}
})
// Audio metadata: album
if (common.album) {
elems.push((
<div key='album' className='audio-album'>
<label>Album</label>{common.album}
</div>
))
}
// Audio metadata: year
if (common.year) {
elems.push((
<div key='year' className='audio-year'>
<label>Year</label>{common.year}
</div>
))
}
// Audio metadata: release information (label & catalog-number)
if (common.label || common.catalognumber) {
const releaseInfo = []
if (common.label && common.catalognumber &&
common.label.length === common.catalognumber.length) {
// Assume labels & catalog-numbers are pairs
for (let n = 0; n < common.label.length; ++n) {
releaseInfo.push(common.label[0] + ' / ' + common.catalognumber[n])
}
} else {
if (common.label) {
releaseInfo.push(...common.label)
}
if (common.catalognumber) {
releaseInfo.push(...common.catalognumber)
}
}
elems.push((
<div key='release' className='audio-release'>
<label>Release</label>{releaseInfo.join(', ')}
</div>
))
}
// Audio metadata: format
const format = []
fileSummary.audioInfo.format = fileSummary.audioInfo.format || ''
if (fileSummary.audioInfo.format.container) {
format.push(fileSummary.audioInfo.format.container)
}
if (fileSummary.audioInfo.format.codec &&
fileSummary.audioInfo.format.container !== fileSummary.audioInfo.format.codec) {
format.push(fileSummary.audioInfo.format.codec)
}
if (fileSummary.audioInfo.format.bitrate) {
format.push(Math.round(fileSummary.audioInfo.format.bitrate / 1000) + ' kbit/s') // 128 kbit/s
}
if (fileSummary.audioInfo.format.sampleRate) {
format.push(Math.round(fileSummary.audioInfo.format.sampleRate / 100) / 10 + ' kHz')
}
if (fileSummary.audioInfo.format.bitsPerSample) {
format.push(fileSummary.audioInfo.format.bitsPerSample + '-bit')
}
if (format.length > 0) {
elems.push((
<div key='format' className='audio-format'>
<label>Format</label>{format.join(', ')}
</div>
))
}
// Audio metadata: comments
if (common.comment) {
elems.push((
<div key='comments' className='audio-comments'>
<label>Comments</label>{common.comment.join(' / ')}
</div>
))
}
// Align the title with the other info, if available. Otherwise, center title
const emptyLabel = (<label />)
elems.unshift((
<div key='title' className='audio-title'>
{elems.length ? emptyLabel : undefined}{title}
</div>
))
return (<div key='audio-metadata' className='audio-metadata'>{elems}</div>)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderAudioMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderEta (total, downloaded) {
const missing = (total || 0) - (downloaded || 0)
const downloadSpeed = prog.downloadSpeed || 0
if (downloadSpeed === 0 || missing === 0) return
const etaStr = calculateEta(missing, downloadSpeed)
return (<span>{etaStr}</span>)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderEta | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderCastOptions (state) {
if (!state.devices.castMenu) return
const { location, devices } = state.devices.castMenu
const player = state.devices[location]
const items = devices.map((device, ix) => {
const isSelected = player.device === device
const name = device.name
return (
<li key={ix} onClick={dispatcher('selectCastDevice', ix)}>
<i className='icon'>{isSelected ? 'radio_button_checked' : 'radio_button_unchecked'}</i>
{' '}
{name}
</li>
)
})
return (
<ul key='cast-options' className='options-list'>
{items}
</ul>
)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderCastOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderSubtitleOptions (state) {
const subtitles = state.playing.subtitles
if (!subtitles.tracks.length || !subtitles.showMenu) return
const items = subtitles.tracks.map((track, ix) => {
const isSelected = state.playing.subtitles.selectedIndex === ix
return (
<li key={ix} onClick={dispatcher('selectSubtitle', ix)}>
<i className='icon'>{'radio_button_' + (isSelected ? 'checked' : 'unchecked')}</i>
{track.label}
</li>
)
})
const noneSelected = state.playing.subtitles.selectedIndex === -1
const noneClass = 'radio_button_' + (noneSelected ? 'checked' : 'unchecked')
return (
<ul key='subtitle-options' className='options-list'>
{items}
<li onClick={dispatcher('selectSubtitle', -1)}>
<i className='icon'>{noneClass}</i>
None
</li>
</ul>
)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderSubtitleOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderAudioTrackOptions (state) {
const audioTracks = state.playing.audioTracks
if (!audioTracks.tracks.length || !audioTracks.showMenu) return
const items = audioTracks.tracks.map((track, ix) => {
const isSelected = state.playing.audioTracks.selectedIndex === ix
return (
<li key={ix} onClick={dispatcher('selectAudioTrack', ix)}>
<i className='icon'>{'radio_button_' + (isSelected ? 'checked' : 'unchecked')}</i>
{track.label}
</li>
)
})
return (
<ul key='audio-track-options' className='options-list'>
{items}
</ul>
)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderAudioTrackOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderPlayerControls (state) {
const positionPercent = 100 * state.playing.currentTime / state.playing.duration
const playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 3px)' }
const captionsClass = state.playing.subtitles.tracks.length === 0
? 'disabled'
: state.playing.subtitles.selectedIndex >= 0
? 'active'
: ''
const multiAudioClass = state.playing.audioTracks.tracks.length > 1
? 'active'
: 'disabled'
const prevClass = Playlist.hasPrevious(state) ? '' : 'disabled'
const nextClass = Playlist.hasNext(state) ? '' : 'disabled'
const elements = [
renderPreview(state),
<div key='playback-bar' className='playback-bar'>
{renderLoadingBar(state)}
<div
key='cursor'
className='playback-cursor'
style={playbackCursorStyle}
/>
<div
key='scrub-bar'
className='scrub-bar'
draggable='true'
onMouseMove={handleScrubPreview}
onMouseOut={clearPreview}
onDragStart={handleDragStart}
onClick={handleScrub}
onDrag={handleScrub}
/>
</div>,
<i
key='skip-previous'
className={'icon skip-previous float-left ' + prevClass}
onClick={dispatcher('previousTrack')}
role='button'
aria-label='Previous track'
>
skip_previous
</i>,
<i
key='play'
className='icon play-pause float-left'
onClick={dispatcher('playPause')}
role='button'
aria-label={state.playing.isPaused ? 'Play' : 'Pause'}
>
{state.playing.isPaused ? 'play_arrow' : 'pause'}
</i>,
<i
key='skip-next'
className={'icon skip-next float-left ' + nextClass}
onClick={dispatcher('nextTrack')}
role='button'
aria-label='Next track'
>
skip_next
</i>,
<i
key='fullscreen'
className='icon fullscreen float-right'
onClick={dispatcher('toggleFullScreen')}
role='button'
aria-label={state.window.isFullScreen ? 'Exit full screen' : 'Enter full screen'}
>
{state.window.isFullScreen ? 'fullscreen_exit' : 'fullscreen'}
</i>
]
if (state.playing.type === 'video') {
// Show closed captions icon
elements.push((
<i
key='subtitles'
className={'icon closed-caption float-right ' + captionsClass}
onClick={handleSubtitles}
role='button'
aria-label='Closed captions'
>
closed_caption
</i>
), (
<i
key='audio-tracks'
className={'icon multi-audio float-right ' + multiAudioClass}
onClick={handleAudioTracks}
>
library_music
</i>
))
}
// If we've detected a Chromecast or AppleTV, the user can play video there
const castTypes = ['chromecast', 'airplay', 'dlna']
const isCastingAnywhere = castTypes.some(
(castType) => state.playing.location.startsWith(castType))
// Add the cast buttons. Icons for each cast type, connected/disconnected:
const buttonIcons = {
chromecast: { true: 'cast_connected', false: 'cast' },
airplay: { true: 'airplay', false: 'airplay' },
dlna: { true: 'tv', false: 'tv' }
}
castTypes.forEach(castType => {
// Do we show this button (eg. the Chromecast button) at all?
const isCasting = state.playing.location.startsWith(castType)
const player = state.devices[castType]
if ((!player || player.getDevices().length === 0) && !isCasting) return
// Show the button. Three options for eg the Chromecast button:
let buttonClass, buttonHandler
if (isCasting) {
// Option 1: we are currently connected to Chromecast. Button stops the cast.
buttonClass = 'active'
buttonHandler = dispatcher('stopCasting')
} else if (isCastingAnywhere) {
// Option 2: we are currently connected somewhere else. Button disabled.
buttonClass = 'disabled'
buttonHandler = undefined
} else {
// Option 3: we are not connected anywhere. Button opens Chromecast menu.
buttonClass = ''
buttonHandler = dispatcher('toggleCastMenu', castType)
}
const buttonIcon = buttonIcons[castType][isCasting]
elements.push((
<i
key={castType}
className={'icon device float-right ' + buttonClass}
onClick={buttonHandler}
>
{buttonIcon}
</i>
))
})
// Render volume slider
const volume = state.playing.volume
const volumeIcon = 'volume_' + (
volume === 0
? 'off'
: volume < 0.3
? 'mute'
: volume < 0.6
? 'down'
: 'up'
)
const volumeStyle = {
background: '-webkit-gradient(linear, left top, right top, ' +
'color-stop(' + (volume * 100) + '%, #eee), ' +
'color-stop(' + (volume * 100) + '%, #727272))'
}
elements.push((
<div key='volume' className='volume float-left'>
<i
className='icon volume-icon float-left'
onMouseDown={handleVolumeMute}
role='button'
aria-label='Mute'
>
{volumeIcon}
</i>
<input
className='volume-slider float-right'
type='range' min='0' max='1' step='0.05'
value={volume}
onChange={handleVolumeScrub}
style={volumeStyle}
/>
</div>
))
// Show video playback progress
const currentTimeStr = formatTime(state.playing.currentTime, state.playing.duration)
const durationStr = formatTime(state.playing.duration, state.playing.duration)
elements.push((
<span key='time' className='time float-left'>
{currentTimeStr} / {durationStr}
</span>
))
// Render playback rate
if (state.playing.playbackRate !== 1) {
elements.push((
<span key='rate' className='rate float-left'>
{state.playing.playbackRate}x
</span>
))
}
const emptyImage = new window.Image(0, 0)
emptyImage.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'
function handleDragStart (e) {
if (e.dataTransfer) {
const dt = e.dataTransfer
// Prevent the cursor from changing, eg to a green + icon on Mac
dt.effectAllowed = 'none'
// Prevent ghost image
dt.setDragImage(emptyImage, 0, 0)
}
}
// Handles a scrub hover (preview another position in the video)
function handleScrubPreview (e) {
// Only show for videos
if (!e.clientX || state.playing.type !== 'video') return
dispatch('mediaMouseMoved')
dispatch('preview', e.clientX)
}
function clearPreview () {
if (state.playing.type !== 'video') return
dispatch('clearPreview')
}
// Handles a click or drag to scrub (jump to another position in the video)
function handleScrub (e) {
if (!e.clientX) return
dispatch('mediaMouseMoved')
const windowWidth = document.querySelector('body').clientWidth
const fraction = e.clientX / windowWidth
const position = fraction * state.playing.duration /* seconds */
dispatch('skipTo', position)
}
// Handles volume muting and Unmuting
function handleVolumeMute () {
if (state.playing.volume === 0.0) {
dispatch('setVolume', 1.0)
} else {
dispatch('setVolume', 0.0)
}
}
// Handles volume slider scrub
function handleVolumeScrub (e) {
dispatch('setVolume', e.target.value)
}
function handleSubtitles (e) {
if (!state.playing.subtitles.tracks.length || e.ctrlKey || e.metaKey) {
// if no subtitles available select it
dispatch('openSubtitles')
} else {
dispatch('toggleSubtitlesMenu')
}
}
function handleAudioTracks () {
dispatch('toggleAudioTracksMenu')
}
return (
<div
key='controls' className='controls'
onMouseEnter={dispatcher('mediaControlsMouseEnter')}
onMouseLeave={dispatcher('mediaControlsMouseLeave')}
>
{elements}
{renderCastOptions(state)}
{renderSubtitleOptions(state)}
{renderAudioTrackOptions(state)}
</div>
)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderPlayerControls | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleDragStart (e) {
if (e.dataTransfer) {
const dt = e.dataTransfer
// Prevent the cursor from changing, eg to a green + icon on Mac
dt.effectAllowed = 'none'
// Prevent ghost image
dt.setDragImage(emptyImage, 0, 0)
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleDragStart | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleScrubPreview (e) {
// Only show for videos
if (!e.clientX || state.playing.type !== 'video') return
dispatch('mediaMouseMoved')
dispatch('preview', e.clientX)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleScrubPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function clearPreview () {
if (state.playing.type !== 'video') return
dispatch('clearPreview')
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | clearPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleScrub (e) {
if (!e.clientX) return
dispatch('mediaMouseMoved')
const windowWidth = document.querySelector('body').clientWidth
const fraction = e.clientX / windowWidth
const position = fraction * state.playing.duration /* seconds */
dispatch('skipTo', position)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleScrub | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleVolumeMute () {
if (state.playing.volume === 0.0) {
dispatch('setVolume', 1.0)
} else {
dispatch('setVolume', 0.0)
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleVolumeMute | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleVolumeScrub (e) {
dispatch('setVolume', e.target.value)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleVolumeScrub | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleSubtitles (e) {
if (!state.playing.subtitles.tracks.length || e.ctrlKey || e.metaKey) {
// if no subtitles available select it
dispatch('openSubtitles')
} else {
dispatch('toggleSubtitlesMenu')
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleSubtitles | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderPreview (state) {
const { previewXCoord = null } = state.playing
// Calculate time from x-coord as fraction of track width
const windowWidth = document.querySelector('body').clientWidth
const fraction = previewXCoord / windowWidth
const time = fraction * state.playing.duration /* seconds */
const height = 70
let width = 0
const previewEl = document.querySelector('video#preview')
if (previewEl !== null && previewXCoord !== null) {
previewEl.currentTime = time
// Auto adjust width to maintain video aspect ratio
width = Math.floor((previewEl.videoWidth / previewEl.videoHeight) * height)
}
// Center preview window on mouse cursor,
// while avoiding falling off the left or right edges
const xPos = Math.min(Math.max(previewXCoord - (width / 2), 5), windowWidth - width - 5)
return (
<div
key='preview' style={{
position: 'absolute',
bottom: 50,
left: xPos,
display: previewXCoord == null && 'none' // Hide preview when XCoord unset
}}
>
<div style={{ width, height, backgroundColor: 'black' }}>
<video
src={Playlist.getCurrentLocalURL(state)}
id='preview'
style={{ border: '1px solid lightgrey', borderRadius: 2 }}
/>
</div>
<p
style={{
textAlign: 'center', margin: 5, textShadow: '0 0 2px rgba(0,0,0,.5)', color: '#eee'
}}
>
{formatTime(time, state.playing.duration)}
</p>
</div>
)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderLoadingBar (state) {
if (config.IS_TEST) return // Don't integration test the loading bar. Screenshots won't match.
const torrentSummary = state.getPlayingTorrentSummary()
if (!torrentSummary.progress) {
return null
}
// Find all contiguous parts of the torrent which are loaded
const prog = torrentSummary.progress
const fileProg = prog.files[state.playing.fileIndex]
if (!fileProg) return null
const parts = []
let lastPiecePresent = false
for (let i = fileProg.startPiece; i <= fileProg.endPiece; i++) {
const partPresent = BitField.prototype.get.call(prog.bitfield, i)
if (partPresent && !lastPiecePresent) {
parts.push({ start: i - fileProg.startPiece, count: 1 })
} else if (partPresent) {
parts[parts.length - 1].count++
}
lastPiecePresent = partPresent
}
// Output some bars to show which parts of the file are loaded
const loadingBarElems = parts.map((part, i) => {
const style = {
left: (100 * part.start / fileProg.numPieces) + '%',
width: (100 * part.count / fileProg.numPieces) + '%'
}
return (<div key={i} className='loading-bar-part' style={style} />)
})
return (<div key='loading-bar' className='loading-bar'>{loadingBarElems}</div>)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderLoadingBar | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function cssBackgroundImagePoster (state) {
const torrentSummary = state.getPlayingTorrentSummary()
const posterPath = TorrentSummary.getPosterPath(torrentSummary)
if (!posterPath) return ''
return cssBackgroundImageDarkGradient() + `, url('${posterPath}')`
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | cssBackgroundImagePoster | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function cssBackgroundImageDarkGradient () {
return 'radial-gradient(circle at center, ' +
'rgba(0,0,0,0.4) 0%, rgba(0,0,0,1) 100%)'
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | cssBackgroundImageDarkGradient | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function formatTime (time, total) {
if (typeof time !== 'number' || Number.isNaN(time)) {
return '0:00'
}
const totalHours = Math.floor(total / 3600)
const totalMinutes = Math.floor(total / 60)
const hours = Math.floor(time / 3600)
let minutes = Math.floor(time % 3600 / 60)
if (totalMinutes > 9 && minutes < 10) {
minutes = '0' + minutes
}
const seconds = `0${Math.floor(time % 60)}`.slice(-2)
return (totalHours > 0 ? hours + ':' : '') + minutes + ':' + seconds
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | formatTime | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.required = true;
this._name = name.slice(1, -1);
break;
case '[': // e.g. [optional]
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && this._name.slice(-3) === '...') {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
} | Initialize a new command argument with the given name and description.
The default is that the argument is required, and you can explicitly
indicate this with <> around the name. Put [] around the name for an optional argument.
@param {string} name
@param {string} [description] | constructor | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
} | Set the default value, and optionally supply the description to be displayed in the help.
@param {*} value
@param {string} [description]
@return {Argument} | default | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
argParser(fn) {
this.parseArg = fn;
return this;
} | Set the custom handler for processing CLI command arguments into argument values.
@param {Function} [fn]
@return {Argument} | argParser | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
} | Only allow argument value to be one of choices.
@param {string[]} values
@return {Argument} | choices | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
} | Takes an argument and returns its human readable equivalent for help usage.
@param {Argument} arg
@return {string}
@private | humanReadableArgName | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
constructor(name) {
super();
/** @type {Command[]} */
this.commands = [];
/** @type {Option[]} */
this.options = [];
this.parent = null;
this._allowUnknownOption = false;
this._allowExcessArguments = false;
/** @type {Argument[]} */
this.registeredArguments = [];
this._args = this.registeredArguments; // deprecated old name
/** @type {string[]} */
this.args = []; // cli args with options removed
this.rawArgs = [];
this.processedArgs = []; // like .args but after custom processing and collecting variadic
this._scriptPath = null;
this._name = name || '';
this._optionValues = {};
this._optionValueSources = {}; // default, env, cli etc
this._storeOptionsAsProperties = false;
this._actionHandler = null;
this._executableHandler = false;
this._executableFile = null; // custom name for executable
this._executableDir = null; // custom search directory for subcommands
this._defaultCommandName = null;
this._exitCallback = null;
this._aliases = [];
this._combineFlagAndOptionalValue = true;
this._description = '';
this._summary = '';
this._argsDescription = undefined; // legacy
this._enablePositionalOptions = false;
this._passThroughOptions = false;
this._lifeCycleHooks = {}; // a hash of arrays
/** @type {(boolean | string)} */
this._showHelpAfterError = false;
this._showSuggestionAfterError = true;
this._savedState = null; // used in save/restoreStateBeforeParse
// see configureOutput() for docs
this._outputConfiguration = {
writeOut: (str) => process.stdout.write(str),
writeErr: (str) => process.stderr.write(str),
outputError: (str, write) => write(str),
getOutHelpWidth: () =>
process.stdout.isTTY ? process.stdout.columns : undefined,
getErrHelpWidth: () =>
process.stderr.isTTY ? process.stderr.columns : undefined,
getOutHasColors: () =>
useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
getErrHasColors: () =>
useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
stripColor: (str) => stripColor(str),
};
this._hidden = false;
/** @type {(Option | null | undefined)} */
this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
/** @type {Command} */
this._helpCommand = undefined; // lazy initialised, inherited
this._helpConfiguration = {};
/** @type {string | undefined} */
this._helpGroupHeading = undefined; // soft initialised when added to parent
/** @type {string | undefined} */
this._defaultCommandGroup = undefined;
/** @type {string | undefined} */
this._defaultOptionGroup = undefined;
} | Initialize a new `Command`.
@param {string} [name] | constructor | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
copyInheritedSettings(sourceCommand) {
this._outputConfiguration = sourceCommand._outputConfiguration;
this._helpOption = sourceCommand._helpOption;
this._helpCommand = sourceCommand._helpCommand;
this._helpConfiguration = sourceCommand._helpConfiguration;
this._exitCallback = sourceCommand._exitCallback;
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
this._combineFlagAndOptionalValue =
sourceCommand._combineFlagAndOptionalValue;
this._allowExcessArguments = sourceCommand._allowExcessArguments;
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
this._showHelpAfterError = sourceCommand._showHelpAfterError;
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
return this;
} | Copy settings that are useful to have in common across root command and subcommands.
(Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
@param {Command} sourceCommand
@return {Command} `this` command for chaining | copyInheritedSettings | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
let desc = actionOptsOrExecDesc;
let opts = execOpts;
if (typeof desc === 'object' && desc !== null) {
opts = desc;
desc = null;
}
opts = opts || {};
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
const cmd = this.createCommand(name);
if (desc) {
cmd.description(desc);
cmd._executableHandler = true;
}
if (opts.isDefault) this._defaultCommandName = cmd._name;
cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
if (args) cmd.arguments(args);
this._registerCommand(cmd);
cmd.parent = this;
cmd.copyInheritedSettings(this);
if (desc) return this;
return cmd;
} | Define a command.
There are two styles of command: pay attention to where to put the description.
@example
// Command implemented using action handler (description is supplied separately to `.command`)
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});
// Command implemented using separate executable file (description is second parameter to `.command`)
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');
@param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
@param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
@param {object} [execOpts] - configuration options (for executable)
@return {Command} returns new command for action handler, or `this` for executable command | command | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createCommand(name) {
return new Command(name);
} | Factory routine to create a new unattached command.
See .command() for creating an attached subcommand, which uses this routine to
create the command. You can override createCommand to customise subcommands.
@param {string} [name]
@return {Command} new command | createCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createHelp() {
return Object.assign(new Help(), this.configureHelp());
} | You can customise the help with a subclass of Help by overriding createHelp,
or by overriding Help properties using configureHelp().
@return {Help} | createHelp | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
configureHelp(configuration) {
if (configuration === undefined) return this._helpConfiguration;
this._helpConfiguration = configuration;
return this;
} | You can customise the help by overriding Help properties using configureHelp(),
or with a subclass of Help by overriding createHelp().
@param {object} [configuration] - configuration options
@return {(Command | object)} `this` command for chaining, or stored configuration | configureHelp | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
configureOutput(configuration) {
if (configuration === undefined) return this._outputConfiguration;
this._outputConfiguration = Object.assign(
{},
this._outputConfiguration,
configuration,
);
return this;
} | The default output goes to stdout and stderr. You can customise this for special
applications. You can also customise the display of errors by overriding outputError.
The configuration properties are all functions:
// change how output being written, defaults to stdout and stderr
writeOut(str)
writeErr(str)
// change how output being written for errors, defaults to writeErr
outputError(str, write) // used for displaying errors and not used for displaying help
// specify width for wrapping help
getOutHelpWidth()
getErrHelpWidth()
// color support, currently only used with Help
getOutHasColors()
getErrHasColors()
stripColor() // used to remove ANSI escape codes if output does not have colors
@param {object} [configuration] - configuration options
@return {(Command | object)} `this` command for chaining, or stored configuration | configureOutput | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
showHelpAfterError(displayHelp = true) {
if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
this._showHelpAfterError = displayHelp;
return this;
} | Display the help or a custom message after an error occurs.
@param {(boolean|string)} [displayHelp]
@return {Command} `this` command for chaining | showHelpAfterError | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
showSuggestionAfterError(displaySuggestion = true) {
this._showSuggestionAfterError = !!displaySuggestion;
return this;
} | Display suggestion of similar commands for unknown commands, or options for unknown options.
@param {boolean} [displaySuggestion]
@return {Command} `this` command for chaining | showSuggestionAfterError | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addCommand(cmd, opts) {
if (!cmd._name) {
throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
}
opts = opts || {};
if (opts.isDefault) this._defaultCommandName = cmd._name;
if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
this._registerCommand(cmd);
cmd.parent = this;
cmd._checkForBrokenPassThrough();
return this;
} | Add a prepared subcommand.
See .command() for creating an attached subcommand which inherits settings from its parent.
@param {Command} cmd - new subcommand
@param {object} [opts] - configuration options
@return {Command} `this` command for chaining | addCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createArgument(name, description) {
return new Argument(name, description);
} | Factory routine to create a new unattached argument.
See .argument() for creating an attached argument, which uses this routine to
create the argument. You can override createArgument to return a custom argument.
@param {string} name
@param {string} [description]
@return {Argument} new argument | createArgument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
argument(name, description, parseArg, defaultValue) {
const argument = this.createArgument(name, description);
if (typeof parseArg === 'function') {
argument.default(defaultValue).argParser(parseArg);
} else {
argument.default(parseArg);
}
this.addArgument(argument);
return this;
} | Define argument syntax for command.
The default is that the argument is required, and you can explicitly
indicate this with <> around the name. Put [] around the name for an optional argument.
@example
program.argument('<input-file>');
program.argument('[output-file]');
@param {string} name
@param {string} [description]
@param {(Function|*)} [parseArg] - custom argument processing function or default value
@param {*} [defaultValue]
@return {Command} `this` command for chaining | argument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
arguments(names) {
names
.trim()
.split(/ +/)
.forEach((detail) => {
this.argument(detail);
});
return this;
} | Define argument syntax for command, adding multiple at once (without descriptions).
See also .argument().
@example
program.arguments('<cmd> [env]');
@param {string} names
@return {Command} `this` command for chaining | arguments | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addArgument(argument) {
const previousArgument = this.registeredArguments.slice(-1)[0];
if (previousArgument && previousArgument.variadic) {
throw new Error(
`only the last argument can be variadic '${previousArgument.name()}'`,
);
}
if (
argument.required &&
argument.defaultValue !== undefined &&
argument.parseArg === undefined
) {
throw new Error(
`a default value for a required argument is never used: '${argument.name()}'`,
);
}
this.registeredArguments.push(argument);
return this;
} | Define argument syntax for command, adding a prepared argument.
@param {Argument} argument
@return {Command} `this` command for chaining | addArgument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
helpCommand(enableOrNameAndArgs, description) {
if (typeof enableOrNameAndArgs === 'boolean') {
this._addImplicitHelpCommand = enableOrNameAndArgs;
if (enableOrNameAndArgs && this._defaultCommandGroup) {
// make the command to store the group
this._initCommandGroup(this._getHelpCommand());
}
return this;
}
const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
const helpDescription = description ?? 'display help for command';
const helpCommand = this.createCommand(helpName);
helpCommand.helpOption(false);
if (helpArgs) helpCommand.arguments(helpArgs);
if (helpDescription) helpCommand.description(helpDescription);
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
// init group unless lazy create
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
return this;
} | Customise or override default help command. By default a help command is automatically added if your command has subcommands.
@example
program.helpCommand('help [cmd]');
program.helpCommand('help [cmd]', 'show help');
program.helpCommand(false); // suppress default help command
program.helpCommand(true); // add help command even if no subcommands
@param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
@param {string} [description] - custom description
@return {Command} `this` command for chaining | helpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addHelpCommand(helpCommand, deprecatedDescription) {
// If not passed an object, call through to helpCommand for backwards compatibility,
// as addHelpCommand was originally used like helpCommand is now.
if (typeof helpCommand !== 'object') {
this.helpCommand(helpCommand, deprecatedDescription);
return this;
}
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
this._initCommandGroup(helpCommand);
return this;
} | Add prepared custom help command.
@param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
@param {string} [deprecatedDescription] - deprecated custom description used with custom name only
@return {Command} `this` command for chaining | addHelpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
_getHelpCommand() {
const hasImplicitHelpCommand =
this._addImplicitHelpCommand ??
(this.commands.length &&
!this._actionHandler &&
!this._findCommand('help'));
if (hasImplicitHelpCommand) {
if (this._helpCommand === undefined) {
this.helpCommand(undefined, undefined); // use default name and description
}
return this._helpCommand;
}
return null;
} | Lazy create help command.
@return {(Command|null)}
@package | _getHelpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.