Split state into temp and saved

Also stop using IPC to calculate window width

Add default torrents--the Blender Foundation videos--not displayed yet
This commit is contained in:
DC
2016-03-05 15:44:57 -08:00
parent c2b5f7a7bb
commit 5b383d3ed0
9 changed files with 618 additions and 72 deletions

View File

@@ -31,9 +31,13 @@ global.WEBTORRENT_ANNOUNCE = createTorrent.announceList
}) })
var state = global.state = { var state = global.state = {
server: null, /* local WebTorrent-to-HTTP server */ /* Temporary state disappears once the program exits.
view: { * It can contain complex objects like open connections, etc.
*/
temp: {
url: '/', url: '/',
client: null, /* the WebTorrent client */
server: null, /* local WebTorrent-to-HTTP server */
dock: { dock: {
badge: 0, badge: 0,
progress: 0 progress: 0
@@ -42,19 +46,41 @@ var state = global.state = {
airplay: null, /* airplay client. finds and manages AppleTVs */ airplay: null, /* airplay client. finds and manages AppleTVs */
chromecast: null /* chromecast client. finds and manages Chromecasts */ chromecast: null /* chromecast client. finds and manages Chromecasts */
}, },
client: null, /* the WebTorrent client */
torrentPlaying: null, /* the torrent we're streaming. see client.torrents */ torrentPlaying: null, /* the torrent we're streaming. see client.torrents */
// history: [], /* track how we got to the current view. enables Back button */ // history: [], /* track how we got to the current view. enables Back button */
// historyIndex: 0, // historyIndex: 0,
isFocused: true, isFocused: true,
isFullScreen: false, isFullScreen: false,
mainWindowBounds: null, /* x y width height */ mainWindowBounds: null, /* x y width height */
title: 'WebTorrent' /* current window title */ title: 'WebTorrent', /* current window title */
video: {
isPaused: false,
currentTime: 0, /* seconds */
duration: 1 /* seconds */
}
}, },
video: { /* Saved state is read from and written to ~/.webtorrent/state.json
isPaused: false, * It should be simple and minimal and must be JSONifiable
currentTime: 0, /* seconds */ */
duration: 1 /* seconds */ saved: {
torrents: [
{
name: 'Elephants Dream',
torrentFile: 'resources/ElephantsDream_archive.torrent'
},
{
name: 'Big Buck Bunny',
torrentFile: 'resources/BigBuckBunny_archive.torrent'
},
{
name: 'Sintel',
torrentFile: 'resources/Sintel_archive.torrent'
},
{
name: 'Tears of Steel',
torrentFile: 'resources/TearsOfSteel_archive.torrent'
}
]
} }
} }
@@ -64,7 +90,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.view.client = client state.temp.client = client
vdomLoop = mainLoop(state, render, { vdomLoop = mainLoop(state, render, {
create: createElement, create: createElement,
@@ -78,12 +104,12 @@ function init () {
dragDrop('body', onFiles) dragDrop('body', onFiles)
chromecasts.on('update', function (player) { chromecasts.on('update', function (player) {
state.view.devices.chromecast = player state.temp.devices.chromecast = player
update() update()
}) })
airplay.createBrowser().on('deviceOn', function (player) { airplay.createBrowser().on('deviceOn', function (player) {
state.view.devices.airplay = player state.temp.devices.airplay = player
}).start() }).start()
document.addEventListener('paste', function () { document.addEventListener('paste', function () {
@@ -92,7 +118,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.view.isFullScreen) { if (state.temp.isFullScreen) {
dispatch('toggleFullScreen') dispatch('toggleFullScreen')
} else { } else {
dispatch('back') dispatch('back')
@@ -101,13 +127,13 @@ function init () {
}) })
window.addEventListener('focus', function () { window.addEventListener('focus', function () {
state.view.isFocused = true state.temp.isFocused = true
if (state.view.dock.badge > 0) electron.ipcRenderer.send('setBadge', '') if (state.temp.dock.badge > 0) electron.ipcRenderer.send('setBadge', '')
state.view.dock.badge = 0 state.temp.dock.badge = 0
}) })
window.addEventListener('blur', function () { window.addEventListener('blur', function () {
state.view.isFocused = false state.temp.isFocused = false
}) })
} }
init() init()
@@ -126,16 +152,16 @@ setInterval(function () {
}, 1000) }, 1000)
function updateDockIcon () { function updateDockIcon () {
var progress = state.view.client.progress var progress = state.temp.client.progress
var activeTorrentsExist = state.view.client.torrents.some(function (torrent) { var activeTorrentsExist = state.temp.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.view.dock.progress) { if (progress !== state.temp.dock.progress) {
state.view.dock.progress = progress state.temp.dock.progress = progress
electron.ipcRenderer.send('setProgress', progress) electron.ipcRenderer.send('setProgress', progress)
} }
} }
@@ -164,19 +190,19 @@ function dispatch (action, ...args) {
setDimensions(args[0] /* dimensions */) setDimensions(args[0] /* dimensions */)
} }
if (action === 'back') { if (action === 'back') {
if (state.view.url === '/player') { if (state.temp.url === '/player') {
restoreBounds() restoreBounds()
closeServer() closeServer()
} }
state.view.url = '/' state.temp.url = '/'
update() update()
} }
if (action === 'playPause') { if (action === 'playPause') {
state.video.isPaused = !state.video.isPaused state.temp.video.isPaused = !state.temp.video.isPaused
update() update()
} }
if (action === 'playbackJump') { if (action === 'playbackJump') {
state.video.jumpToTime = args[0] /* seconds */ state.temp.video.jumpToTime = args[0] /* seconds */
update() update()
} }
if (action === 'toggleFullScreen') { if (action === 'toggleFullScreen') {
@@ -193,14 +219,14 @@ electron.ipcRenderer.on('seed', function (e, files) {
}) })
electron.ipcRenderer.on('fullscreenChanged', function (e, isFullScreen) { electron.ipcRenderer.on('fullscreenChanged', function (e, isFullScreen) {
state.view.isFullScreen = isFullScreen state.temp.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.view.devices[device] = player state.temp.devices[device] = player
update() update()
}) })
@@ -237,9 +263,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.view.isFocused) { if (!state.temp.isFocused) {
state.view.dock.badge += 1 state.temp.dock.badge += 1
electron.ipcRenderer.send('setBadge', state.view.dock.badge) electron.ipcRenderer.send('setBadge', state.temp.dock.badge)
} }
update() update()
}) })
@@ -261,19 +287,19 @@ function torrentReady (torrent) {
} }
function startServer (torrent, cb) { function startServer (torrent, cb) {
if (state.server) return cb() if (state.temp.server) return cb()
// use largest file // use largest file
state.view.torrentPlaying = torrent.files.reduce(function (a, b) { state.temp.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.view.torrentPlaying) var index = torrent.files.indexOf(state.temp.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.server = { state.temp.server = {
server: server, server: server,
localURL: 'http://localhost' + urlSuffix, localURL: 'http://localhost' + urlSuffix,
networkURL: 'http://' + networkAddress() + urlSuffix networkURL: 'http://' + networkAddress() + urlSuffix
@@ -283,13 +309,13 @@ function startServer (torrent, cb) {
} }
function closeServer () { function closeServer () {
state.server.server.destroy() state.temp.server.server.destroy()
state.server = null state.temp.server = null
} }
function openPlayer (torrent) { function openPlayer (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.view.url = '/player' state.temp.url = '/player'
update() update()
}) })
} }
@@ -300,8 +326,10 @@ function deleteTorrent (torrent) {
function openChromecast (torrent) { function openChromecast (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.view.devices.chromecast.play(state.server.networkURL, { title: 'WebTorrent — ' + torrent.name }) state.temp.devices.chromecast.play(state.temp.server.networkURL, {
state.view.devices.chromecast.on('error', function (err) { title: 'WebTorrent — ' + torrent.name
})
state.temp.devices.chromecast.on('error', function (err) {
err.message = 'Chromecast: ' + err.message err.message = 'Chromecast: ' + err.message
onError(err) onError(err)
}) })
@@ -311,14 +339,15 @@ function openChromecast (torrent) {
function openAirplay (torrent) { function openAirplay (torrent) {
startServer(torrent, function () { startServer(torrent, function () {
state.view.devices.airplay.play(state.server.networkURL, 0, function () {}) state.temp.devices.airplay.play(state.temp.server.networkURL, 0, function () {
// TODO: handle airplay errors // TODO: handle airplay errors
})
update() update()
}) })
} }
function setDimensions (dimensions) { function setDimensions (dimensions) {
state.view.mainWindowBounds = electron.remote.getCurrentWindow().getBounds() state.temp.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
@@ -344,8 +373,8 @@ function setDimensions (dimensions) {
function restoreBounds () { function restoreBounds () {
electron.ipcRenderer.send('setAspectRatio', 0) electron.ipcRenderer.send('setAspectRatio', 0)
if (state.view.mainWindowBounds) { if (state.temp.mainWindowBounds) {
electron.ipcRenderer.send('setBounds', state.view.mainWindowBounds, true) electron.ipcRenderer.send('setBounds', state.temp.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.view.url === '/') { if (state.temp.url === '/') {
return TorrentList(state, dispatch) return TorrentList(state, dispatch)
} else if (state.view.url === '/player') { } else if (state.temp.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.view.url === '/player' var isVideo = state.temp.url === '/player'
var isFullScreen = state.view.isFullScreen var isFullScreen = state.temp.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.view.title}</div>` return hx`<div class="title">${state.temp.title}</div>`
} }
} }
function plusButton () { function plusButton () {
if (state.view.url !== '/player') { if (state.temp.url !== '/player') {
return hx`<i class="icon add" onclick=${onAddTorrent}>add</i>` return hx`<i class="icon add" onclick=${onAddTorrent}>add</i>`
} }
} }

View File

@@ -3,25 +3,24 @@ module.exports = Player
var h = require('virtual-dom/h') var h = require('virtual-dom/h')
var hyperx = require('hyperx') var hyperx = require('hyperx')
var hx = hyperx(h) var hx = hyperx(h)
var electron = require('electron')
function Player (state, dispatch) { function Player (state, dispatch) {
// Unfortunately, play/pause can't be done just by modifying HTML. // Unfortunately, play/pause can't be done just by modifying HTML.
// 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.video.isPaused && !videoElement.paused) { if (state.temp.video.isPaused && !videoElement.paused) {
videoElement.pause() videoElement.pause()
} else if (!state.video.isPaused && videoElement.paused) { } else if (!state.temp.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.video.jumpToTime) { if (state.temp.video.jumpToTime) {
videoElement.currentTime = state.video.jumpToTime videoElement.currentTime = state.temp.video.jumpToTime
state.video.jumpToTime = null state.temp.video.jumpToTime = null
} }
state.video.currentTime = videoElement.currentTime state.temp.video.currentTime = videoElement.currentTime
state.video.duration = videoElement.duration state.temp.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
@@ -29,7 +28,7 @@ function Player (state, dispatch) {
<div class="player"> <div class="player">
<div class="letterbox"> <div class="letterbox">
<video <video
src="${state.server.localURL}" src="${state.temp.server.localURL}"
onloadedmetadata=${onLoadedMetadata} onloadedmetadata=${onLoadedMetadata}
autoplay="autoplay"> autoplay="autoplay">
</video> </video>
@@ -53,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.video.currentTime / state.video.duration var positionPercent = 100 * state.temp.video.currentTime / state.temp.video.duration
var playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 8px)' } var playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 8px)' }
var torrent = state.view.torrentPlaying._torrent var torrent = state.temp.torrentPlaying._torrent
var elements = [ var elements = [
hx` hx`
@@ -76,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.view.devices.chromecast) { if (state.temp.devices.chromecast) {
elements.push(hx` elements.push(hx`
<i.icon.chromecast <i.icon.chromecast
onclick=${() => dispatch('openChromecast', torrent)}> onclick=${() => dispatch('openChromecast', torrent)}>
@@ -84,7 +83,7 @@ function renderPlayerControls (state, dispatch) {
</i> </i>
`) `)
} }
if (state.view.devices.airplay) { if (state.temp.devices.airplay) {
elements.push(hx` elements.push(hx`
<i.icon.airplay <i.icon.airplay
onclick=${() => dispatch('openAirplay', torrent)}> onclick=${() => dispatch('openAirplay', torrent)}>
@@ -104,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.video.isPaused ? 'play_arrow' : 'pause'} ${state.temp.video.isPaused ? 'play_arrow' : 'pause'}
</i> </i>
`) `)
@@ -112,11 +111,9 @@ function renderPlayerControls (state, dispatch) {
// Handles a click or drag to scrub (jump to another position in the video) // Handles a click or drag to scrub (jump to another position in the video)
function handleScrub (e) { function handleScrub (e) {
// TODO: don't use remote -- it does IPC with the main process which is overkill var windowWidth = document.querySelector('body').clientWidth
// just to get the width
var windowWidth = electron.remote.getCurrentWindow().getBounds().width
var fraction = e.clientX / windowWidth var fraction = e.clientX / windowWidth
var position = fraction * state.video.duration /* seconds */ var position = fraction * state.temp.video.duration /* seconds */
dispatch('playbackJump', position) dispatch('playbackJump', position)
} }
} }
@@ -124,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.view.torrentPlaying._torrent var torrent = state.temp.torrentPlaying._torrent
if (torrent === null) { if (torrent === null) {
return [] return []
} }

View File

@@ -6,18 +6,18 @@ 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.view.client var torrents = state.temp.client
? state.view.client.torrents ? state.temp.client.torrents
: [] : []
var list = torrents.map((torrent) => renderTorrent(state, dispatch, torrent)) var list = torrents.map((torrent) => renderTorrent(torrent, dispatch))
return hx`<div class="torrent-list">${list}</div>` return hx`<div class="torrent-list">${list}</div>`
} }
// Renders a torrent in the torrent list // Renders a torrent in the torrent list
// Includes name, download status, play button, background image // Includes name, download status, play button, background image
// May be expanded for additional info, including the list of files inside // May be expanded for additional info, including the list of files inside
function renderTorrent (state, dispatch, torrent) { function renderTorrent (torrent, dispatch) {
// Background image: show some nice visuals, like a frame from the movie, if possible // Background image: show some nice visuals, like a frame from the movie, if possible
var style = {} var style = {}
if (torrent.posterURL) { if (torrent.posterURL) {

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.