State: put temp state directly in state, saved in state.saved

This commit is contained in:
DC
2016-03-05 15:46:57 -08:00
parent 5b383d3ed0
commit 098827ec78
5 changed files with 80 additions and 81 deletions

View File

@@ -34,31 +34,30 @@ var state = global.state = {
/* Temporary state disappears once the program exits. /* Temporary state disappears once the program exits.
* It can contain complex objects like open connections, etc. * It can contain complex objects like open connections, etc.
*/ */
temp: { url: '/',
url: '/', client: null, /* the WebTorrent client */
client: null, /* the WebTorrent client */ server: null, /* local WebTorrent-to-HTTP server */
server: null, /* local WebTorrent-to-HTTP server */ dock: {
dock: { badge: 0,
badge: 0, progress: 0
progress: 0
},
devices: {
airplay: null, /* airplay client. finds and manages AppleTVs */
chromecast: null /* chromecast client. finds and manages Chromecasts */
},
torrentPlaying: null, /* the torrent we're streaming. see client.torrents */
// history: [], /* track how we got to the current view. enables Back button */
// historyIndex: 0,
isFocused: true,
isFullScreen: false,
mainWindowBounds: null, /* x y width height */
title: 'WebTorrent', /* current window title */
video: {
isPaused: false,
currentTime: 0, /* seconds */
duration: 1 /* seconds */
}
}, },
devices: {
airplay: null, /* airplay client. finds and manages AppleTVs */
chromecast: null /* chromecast client. finds and manages Chromecasts */
},
torrentPlaying: null, /* the torrent we're streaming. see client.torrents */
// history: [], /* track how we got to the current view. enables Back button */
// historyIndex: 0,
isFocused: true,
isFullScreen: false,
mainWindowBounds: null, /* x y width height */
title: 'WebTorrent', /* current window title */
video: {
isPaused: false,
currentTime: 0, /* seconds */
duration: 1 /* seconds */
},
/* Saved state is read from and written to ~/.webtorrent/state.json /* Saved state is read from and written to ~/.webtorrent/state.json
* It should be simple and minimal and must be JSONifiable * It should be simple and minimal and must be JSONifiable
*/ */
@@ -90,7 +89,7 @@ function init () {
client = global.client = new WebTorrent() client = global.client = new WebTorrent()
client.on('warning', onWarning) client.on('warning', onWarning)
client.on('error', onError) client.on('error', onError)
state.temp.client = client state.client = client
vdomLoop = mainLoop(state, render, { vdomLoop = mainLoop(state, render, {
create: createElement, create: createElement,
@@ -104,12 +103,12 @@ function init () {
dragDrop('body', onFiles) dragDrop('body', onFiles)
chromecasts.on('update', function (player) { chromecasts.on('update', function (player) {
state.temp.devices.chromecast = player state.devices.chromecast = player
update() update()
}) })
airplay.createBrowser().on('deviceOn', function (player) { airplay.createBrowser().on('deviceOn', function (player) {
state.temp.devices.airplay = player state.devices.airplay = player
}).start() }).start()
document.addEventListener('paste', function () { document.addEventListener('paste', function () {
@@ -118,7 +117,7 @@ function init () {
document.addEventListener('keydown', function (e) { document.addEventListener('keydown', function (e) {
if (e.which === 27) { /* ESC means either exit fullscreen or go back */ if (e.which === 27) { /* ESC means either exit fullscreen or go back */
if (state.temp.isFullScreen) { if (state.isFullScreen) {
dispatch('toggleFullScreen') dispatch('toggleFullScreen')
} else { } else {
dispatch('back') dispatch('back')
@@ -127,13 +126,13 @@ function init () {
}) })
window.addEventListener('focus', function () { window.addEventListener('focus', function () {
state.temp.isFocused = true state.isFocused = true
if (state.temp.dock.badge > 0) electron.ipcRenderer.send('setBadge', '') if (state.dock.badge > 0) electron.ipcRenderer.send('setBadge', '')
state.temp.dock.badge = 0 state.dock.badge = 0
}) })
window.addEventListener('blur', function () { window.addEventListener('blur', function () {
state.temp.isFocused = false state.isFocused = false
}) })
} }
init() init()
@@ -152,16 +151,16 @@ setInterval(function () {
}, 1000) }, 1000)
function updateDockIcon () { function updateDockIcon () {
var progress = state.temp.client.progress var progress = state.client.progress
var activeTorrentsExist = state.temp.client.torrents.some(function (torrent) { var activeTorrentsExist = state.client.torrents.some(function (torrent) {
return torrent.progress !== 1 return torrent.progress !== 1
}) })
// Hide progress bar when client has no torrents, or progress is 100% // Hide progress bar when client has no torrents, or progress is 100%
if (!activeTorrentsExist || progress === 1) { if (!activeTorrentsExist || progress === 1) {
progress = -1 progress = -1
} }
if (progress !== state.temp.dock.progress) { if (progress !== state.dock.progress) {
state.temp.dock.progress = progress state.dock.progress = progress
electron.ipcRenderer.send('setProgress', progress) electron.ipcRenderer.send('setProgress', progress)
} }
} }
@@ -190,19 +189,19 @@ function dispatch (action, ...args) {
setDimensions(args[0] /* dimensions */) setDimensions(args[0] /* dimensions */)
} }
if (action === 'back') { if (action === 'back') {
if (state.temp.url === '/player') { if (state.url === '/player') {
restoreBounds() restoreBounds()
closeServer() closeServer()
} }
state.temp.url = '/' state.url = '/'
update() update()
} }
if (action === 'playPause') { if (action === 'playPause') {
state.temp.video.isPaused = !state.temp.video.isPaused state.video.isPaused = !state.video.isPaused
update() update()
} }
if (action === 'playbackJump') { if (action === 'playbackJump') {
state.temp.video.jumpToTime = args[0] /* seconds */ state.video.jumpToTime = args[0] /* seconds */
update() update()
} }
if (action === 'toggleFullScreen') { if (action === 'toggleFullScreen') {
@@ -219,14 +218,14 @@ electron.ipcRenderer.on('seed', function (e, files) {
}) })
electron.ipcRenderer.on('fullscreenChanged', function (e, isFullScreen) { electron.ipcRenderer.on('fullscreenChanged', function (e, isFullScreen) {
state.temp.isFullScreen = isFullScreen state.isFullScreen = isFullScreen
update() update()
}) })
electron.ipcRenderer.on('addFakeDevice', function (e, device) { electron.ipcRenderer.on('addFakeDevice', function (e, device) {
var player = new EventEmitter() var player = new EventEmitter()
player.play = (networkURL) => console.log(networkURL) player.play = (networkURL) => console.log(networkURL)
state.temp.devices[device] = player state.devices[device] = player
update() update()
}) })
@@ -263,9 +262,9 @@ function seed (files) {
function addTorrentEvents (torrent) { function addTorrentEvents (torrent) {
torrent.on('infoHash', update) torrent.on('infoHash', update)
torrent.on('done', function () { torrent.on('done', function () {
if (!state.temp.isFocused) { if (!state.isFocused) {
state.temp.dock.badge += 1 state.dock.badge += 1
electron.ipcRenderer.send('setBadge', state.temp.dock.badge) electron.ipcRenderer.send('setBadge', state.dock.badge)
} }
update() update()
}) })
@@ -287,19 +286,19 @@ function torrentReady (torrent) {
} }
function startServer (torrent, cb) { function startServer (torrent, cb) {
if (state.temp.server) return cb() if (state.server) return cb()
// use largest file // use largest file
state.temp.torrentPlaying = torrent.files.reduce(function (a, b) { state.torrentPlaying = torrent.files.reduce(function (a, b) {
return a.length > b.length ? a : b return a.length > b.length ? a : b
}) })
var index = torrent.files.indexOf(state.temp.torrentPlaying) var index = torrent.files.indexOf(state.torrentPlaying)
var server = torrent.createServer() var server = torrent.createServer()
server.listen(0, function () { server.listen(0, function () {
var port = server.address().port var port = server.address().port
var urlSuffix = ':' + port + '/' + index var urlSuffix = ':' + port + '/' + index
state.temp.server = { state.server = {
server: server, server: server,
localURL: 'http://localhost' + urlSuffix, localURL: 'http://localhost' + urlSuffix,
networkURL: 'http://' + networkAddress() + urlSuffix networkURL: 'http://' + networkAddress() + urlSuffix
@@ -309,13 +308,13 @@ function startServer (torrent, cb) {
} }
function closeServer () { function closeServer () {
state.temp.server.server.destroy() state.server.server.destroy()
state.temp.server = null state.server = null
} }
function openPlayer (torrent) { function openPlayer (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.temp.url = '/player' state.url = '/player'
update() update()
}) })
} }
@@ -326,10 +325,10 @@ function deleteTorrent (torrent) {
function openChromecast (torrent) { function openChromecast (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.temp.devices.chromecast.play(state.temp.server.networkURL, { state.devices.chromecast.play(state.server.networkURL, {
title: 'WebTorrent — ' + torrent.name title: 'WebTorrent — ' + torrent.name
}) })
state.temp.devices.chromecast.on('error', function (err) { state.devices.chromecast.on('error', function (err) {
err.message = 'Chromecast: ' + err.message err.message = 'Chromecast: ' + err.message
onError(err) onError(err)
}) })
@@ -339,7 +338,7 @@ function openChromecast (torrent) {
function openAirplay (torrent) { function openAirplay (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.temp.devices.airplay.play(state.temp.server.networkURL, 0, function () { state.devices.airplay.play(state.server.networkURL, 0, function () {
// TODO: handle airplay errors // TODO: handle airplay errors
}) })
update() update()
@@ -347,7 +346,7 @@ function openAirplay (torrent) {
} }
function setDimensions (dimensions) { function setDimensions (dimensions) {
state.temp.mainWindowBounds = electron.remote.getCurrentWindow().getBounds() state.mainWindowBounds = electron.remote.getCurrentWindow().getBounds()
// Limit window size to screen size // Limit window size to screen size
var workAreaSize = electron.remote.screen.getPrimaryDisplay().workAreaSize var workAreaSize = electron.remote.screen.getPrimaryDisplay().workAreaSize
@@ -373,8 +372,8 @@ function setDimensions (dimensions) {
function restoreBounds () { function restoreBounds () {
electron.ipcRenderer.send('setAspectRatio', 0) electron.ipcRenderer.send('setAspectRatio', 0)
if (state.temp.mainWindowBounds) { if (state.mainWindowBounds) {
electron.ipcRenderer.send('setBounds', state.temp.mainWindowBounds, true) electron.ipcRenderer.send('setBounds', state.mainWindowBounds, true)
} }
} }

View File

@@ -10,9 +10,9 @@ var TorrentList = require('./torrent-list')
function App (state, dispatch) { function App (state, dispatch) {
function getView () { function getView () {
if (state.temp.url === '/') { if (state.url === '/') {
return TorrentList(state, dispatch) return TorrentList(state, dispatch)
} else if (state.temp.url === '/player') { } else if (state.url === '/player') {
return Player(state, dispatch) return Player(state, dispatch)
} }
} }
@@ -20,8 +20,8 @@ function App (state, dispatch) {
// Show the header only when we're outside of fullscreen // Show the header only when we're outside of fullscreen
// Also don't show it in the video player except in OSX // Also don't show it in the video player except in OSX
var isOSX = process.platform === 'darwin' var isOSX = process.platform === 'darwin'
var isVideo = state.temp.url === '/player' var isVideo = state.url === '/player'
var isFullScreen = state.temp.isFullScreen var isFullScreen = state.isFullScreen
var header = !isFullScreen && (!isVideo || isOSX) ? Header(state, dispatch) : null var header = !isFullScreen && (!isVideo || isOSX) ? Header(state, dispatch) : null
return hx` return hx`

View File

@@ -23,12 +23,12 @@ function Header (state, dispatch) {
function getTitle () { function getTitle () {
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
return hx`<div class="title">${state.temp.title}</div>` return hx`<div class="title">${state.title}</div>`
} }
} }
function plusButton () { function plusButton () {
if (state.temp.url !== '/player') { if (state.url !== '/player') {
return hx`<i class="icon add" onclick=${onAddTorrent}>add</i>` return hx`<i class="icon add" onclick=${onAddTorrent}>add</i>`
} }
} }

View File

@@ -9,18 +9,18 @@ function Player (state, dispatch) {
// Instead, grab the DOM node and play/pause it if necessary // Instead, grab the DOM node and play/pause it if necessary
var videoElement = document.querySelector('video') var videoElement = document.querySelector('video')
if (videoElement !== null) { if (videoElement !== null) {
if (state.temp.video.isPaused && !videoElement.paused) { if (state.video.isPaused && !videoElement.paused) {
videoElement.pause() videoElement.pause()
} else if (!state.temp.video.isPaused && videoElement.paused) { } else if (!state.video.isPaused && videoElement.paused) {
videoElement.play() videoElement.play()
} }
// When the user clicks or drags on the progress bar, jump to that position // When the user clicks or drags on the progress bar, jump to that position
if (state.temp.video.jumpToTime) { if (state.video.jumpToTime) {
videoElement.currentTime = state.temp.video.jumpToTime videoElement.currentTime = state.video.jumpToTime
state.temp.video.jumpToTime = null state.video.jumpToTime = null
} }
state.temp.video.currentTime = videoElement.currentTime state.video.currentTime = videoElement.currentTime
state.temp.video.duration = videoElement.duration state.video.duration = videoElement.duration
} }
// Show the video as large as will fit in the window, play immediately // Show the video as large as will fit in the window, play immediately
@@ -28,7 +28,7 @@ function Player (state, dispatch) {
<div class="player"> <div class="player">
<div class="letterbox"> <div class="letterbox">
<video <video
src="${state.temp.server.localURL}" src="${state.server.localURL}"
onloadedmetadata=${onLoadedMetadata} onloadedmetadata=${onLoadedMetadata}
autoplay="autoplay"> autoplay="autoplay">
</video> </video>
@@ -52,9 +52,9 @@ function Player (state, dispatch) {
// Renders all video controls: play/pause, scrub, loading bar // Renders all video controls: play/pause, scrub, loading bar
// TODO: cast buttons // TODO: cast buttons
function renderPlayerControls (state, dispatch) { function renderPlayerControls (state, dispatch) {
var positionPercent = 100 * state.temp.video.currentTime / state.temp.video.duration var positionPercent = 100 * state.video.currentTime / state.video.duration
var playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 8px)' } var playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 8px)' }
var torrent = state.temp.torrentPlaying._torrent var torrent = state.torrentPlaying._torrent
var elements = [ var elements = [
hx` hx`
@@ -75,7 +75,7 @@ function renderPlayerControls (state, dispatch) {
` `
] ]
// If we've detected a Chromecast or AppleTV, the user can play video there // If we've detected a Chromecast or AppleTV, the user can play video there
if (state.temp.devices.chromecast) { if (state.devices.chromecast) {
elements.push(hx` elements.push(hx`
<i.icon.chromecast <i.icon.chromecast
onclick=${() => dispatch('openChromecast', torrent)}> onclick=${() => dispatch('openChromecast', torrent)}>
@@ -83,7 +83,7 @@ function renderPlayerControls (state, dispatch) {
</i> </i>
`) `)
} }
if (state.temp.devices.airplay) { if (state.devices.airplay) {
elements.push(hx` elements.push(hx`
<i.icon.airplay <i.icon.airplay
onclick=${() => dispatch('openAirplay', torrent)}> onclick=${() => dispatch('openAirplay', torrent)}>
@@ -103,7 +103,7 @@ function renderPlayerControls (state, dispatch) {
} }
elements.push(hx` elements.push(hx`
<i class="icon play-pause" onclick=${() => dispatch('playPause')}> <i class="icon play-pause" onclick=${() => dispatch('playPause')}>
${state.temp.video.isPaused ? 'play_arrow' : 'pause'} ${state.video.isPaused ? 'play_arrow' : 'pause'}
</i> </i>
`) `)
@@ -113,7 +113,7 @@ function renderPlayerControls (state, dispatch) {
function handleScrub (e) { function handleScrub (e) {
var windowWidth = document.querySelector('body').clientWidth var windowWidth = document.querySelector('body').clientWidth
var fraction = e.clientX / windowWidth var fraction = e.clientX / windowWidth
var position = fraction * state.temp.video.duration /* seconds */ var position = fraction * state.video.duration /* seconds */
dispatch('playbackJump', position) dispatch('playbackJump', position)
} }
} }
@@ -121,7 +121,7 @@ function renderPlayerControls (state, dispatch) {
// Renders the loading bar. Shows which parts of the torrent are loaded, which // Renders the loading bar. Shows which parts of the torrent are loaded, which
// can be "spongey" / non-contiguous // can be "spongey" / non-contiguous
function renderLoadingBar (state) { function renderLoadingBar (state) {
var torrent = state.temp.torrentPlaying._torrent var torrent = state.torrentPlaying._torrent
if (torrent === null) { if (torrent === null) {
return [] return []
} }

View File

@@ -6,8 +6,8 @@ var hx = hyperx(h)
var prettyBytes = require('pretty-bytes') var prettyBytes = require('pretty-bytes')
function TorrentList (state, dispatch) { function TorrentList (state, dispatch) {
var torrents = state.temp.client var torrents = state.client
? state.temp.client.torrents ? state.client.torrents
: [] : []
var list = torrents.map((torrent) => renderTorrent(torrent, dispatch)) var list = torrents.map((torrent) => renderTorrent(torrent, dispatch))