Compare commits

...

170 Commits

Author SHA1 Message Date
Feross Aboukhadijeh
4cbad1fccd 0.17.2 2016-10-10 22:44:08 -07:00
Feross Aboukhadijeh
f818564dd1 package.json: Add {"private": true}
To prevent accidental publishing to npm.
2016-10-10 22:41:17 -07:00
Feross Aboukhadijeh
8be690a26e v0.17.2 changelog 2016-10-10 22:37:24 -07:00
Feross Aboukhadijeh
8081d42477 Attempt to fix "TypeError: Cannot read property 'startPiece' of undefined"
It wasn't clear what was causing this error, and I couldn't reproduce
it.

This PR attempts to resolve the issue by just guarding against the
exception.
2016-10-10 22:31:33 -07:00
Feross Aboukhadijeh
b0b6069fe2 remove 'pug' from nodemon command (we don't use pug) 2016-10-06 00:37:11 -07:00
Feross Aboukhadijeh
994aed9af7 Fix "Cannot read property 'files' of null"
This PR fixes one of our number 2 top error (142 error reports today
alone):

Processes: webtorrent window, platforms: darwin linux win32, versions:
pre-0.12 0.14.0 0.17.0 0.17.1
TypeError: Cannot read property 'files' of null
    at getAudioMetadata (.../build/renderer/webtorrent.js:328:21)
    at EventEmitter.<anonymous> (.../build/renderer/webtorrent.js:84:74)
    at emitThree (events.js:116:13)
    at EventEmitter.emit (events.js:194:7)

This error is reproducible if you start webtorrent for the first time
and click the WIRED CD torrent. This causes the webtorrent process to
get a  'wt-get-audio-metadata' before 'wt-start-torrenting'.

You can reproduce it 100% of the time if you force the race condition
to show itself by slowing down the sending of the 'wt-start-torrenting'
event.

(This same error was showing for an unrelated reason in the past: #891)
2016-10-05 03:00:52 -07:00
Feross Aboukhadijeh
852fc86cbd Remove unecessary return statement 2016-10-05 03:00:52 -07:00
Feross Aboukhadijeh
8801a87a58 Throttle browser-window 'move' and 'resize' events
Fixes: https://github.com/feross/webtorrent-desktop/issues/1011
2016-10-05 03:00:42 -07:00
Feross Aboukhadijeh
1e10f0083c Windows: Fix impossible to delete Wired CS torrent 2016-10-05 03:00:24 -07:00
Feross Aboukhadijeh
bb40f0f11a Update Mac integration test for Sierra 10.12
The font changed slightly on the next version of Mac OS. Let's update
the screenshots to match, since I already updated. (@dcposch - you'll
need to update too if you want the integration tests to pass on your
machine)
2016-10-04 01:53:49 -07:00
Feross Aboukhadijeh
78d7243a08 package: Explicitly specify architectures to build for
Electron now offers a "armv7l" build on Linux. Because we were
specifying "all", we were generating an armv7l binary which was being
included in "WebTorrent-vX.X.X-linux.zip" along with the ia32 build,
which explains why it was 90MB+ in the last release.
2016-10-03 04:40:42 -07:00
Feross Aboukhadijeh
09724dddd9 0.17.1 2016-10-03 04:02:21 -07:00
Feross Aboukhadijeh
59286ff3cb style: prefix all test commands with "test-"
It's a style I follow in all my packages...

- test
- test-node
- test-browser
- ...
2016-10-03 02:59:50 -07:00
Feross Aboukhadijeh
3f79c90868 Make Electron a devDependency
I moved it from devDependencies to dependencies when we added the app
to npm. But now that that's gone, let's move it back.

Functionally, this causes no difference since electron-packager
automatically excludes `electron` and all devDependencies from the
packaged app.
2016-10-03 02:59:50 -07:00
Feross Aboukhadijeh
33c48d4dfb cp-file@4
Only change is dropped Node 0.10 and 0.12 support. Nice change because
it means we load 3 fewer dependencies.
2016-10-03 02:38:03 -07:00
Feross Aboukhadijeh
48fbcd7303 v0.17.1 changelog 2016-10-03 02:28:25 -07:00
Feross Aboukhadijeh
cdb7b6eb44 Style fixes to PR #995 based on feedback 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
90b72523b7 perf: Only require('./user-tasks') on windows 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
a1fd30f4f5 cache mui theme after it is generated 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
fcae064dbb perf: ~40ms improvement: Lazy load controllers and page components 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
5815d8efe7 Fix first run telemetry bug 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
0be8a73621 perf: 140ms improvement: Hook into require() to modify how certain modules load 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
76e1d7777c Prevent exception when quitting and delayedInit() gets called 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
e10a84b294 Refactor: telemetry sending
- Fix bug where approxNumTorrents and other stats were not refreshed
when getting sent on 12 hour interval
- Lazy require modules
- Move setInterval into renderer/main.js
- Remove low-level https usage, use simple-get
2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
5ff2d893b9 perf: 90ms improvement: Defer more code in renderer, load state earlier
By deferring more code in the renderer and loading state earlier, we
improve startup time by another 90ms!

Before: 507 unique requires (1270-1280ms)
After: 506 unique requires  (1180-1190ms)
2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
02f5dbb63f perf: 60ms improvement: Replace fs-extra with mkdirp/rimraf/cp-file
In Electron apps, the cost of large modules is very real.

fs-extra is very convenient, but removing it caused 50 fewer unique
files to be required(), resultin in 60ms faster startup!

Before: 557 unique requires (1330-1340ms)
After: 507 unique requires (1270-1280ms)
2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
d4cfc32c8d re-order scripts 2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
d5820063a1 Perf: lazy-load more require() calls in main process
Went from 36 unique require calls, to 31 calls after this commit.
2016-10-03 01:24:53 -07:00
Feross Aboukhadijeh
21de048738 Remove unneeded console.logs 2016-10-03 01:24:53 -07:00
Benjamin Tan
06cdac8121 Remove weird outline from “Create Torrent” button.
The outline was caused by the wrong class being applied to the button.

Closes #989.
2016-10-02 21:35:26 -07:00
Mathias Rasmussen
f1aa1bdd59 go back to list on path missing error 2016-10-02 19:00:28 -07:00
Feross Aboukhadijeh
44f621b4de external player: Only run special .app login on darwin 2016-10-02 19:00:00 -07:00
Feross Aboukhadijeh
fd1a1f0f7e On paste: Do not handle multiple newline separated torrent ids
If the user accidentally pastes something that's not a torrent id, then
they get one "Invalid torrent Id" error for each line of the text.

Sure, this removes a "feature", but it's a pretty surprising one. When
I added it, I was being too clever, IMO.

The trim code can be removed, because that's handled in
controllers.torrentList.addTorrent().
2016-10-02 18:58:44 -07:00
Feross Aboukhadijeh
a38b5220ac Trim extra spaces off pasted magnet links
Before this change, using the "Open Torrent Address" dialog to paste a
magnet link would fail with leading or trailing spaces.

Pasting on the torrent list page has always trimmed. So this PR just
makes it consistent.
2016-10-02 18:58:44 -07:00
Feross Aboukhadijeh
428a07101a style: fix inconsistent naming
We don't use "ID" anywhere else in the codebase.
2016-10-02 18:58:44 -07:00
Feross Aboukhadijeh
f1ef9daa8f Update Electron to 1.4.2
Changelog: https://github.com/electron/electron/releases/tag/v1.4.2
2016-10-02 18:58:03 -07:00
Feross Aboukhadijeh
46d5c9c9e9 sound: Reduce volume even further 2016-10-01 19:36:06 -07:00
Feross Aboukhadijeh
ecd877551e sound: remove preloading
Sound playing is basically instant -- I was over-engineering when I
added this.
2016-10-01 19:36:06 -07:00
Feross Aboukhadijeh
76e071e965 Style: Use let/const instead of var 2016-10-01 00:50:04 +02:00
Mathias Rasmussen
5623c1024e delay external player if server is not ready 2016-09-30 01:14:32 -07:00
Feross Aboukhadijeh
1a20155f66 Disable Windows delta updates
See inline comment for explanation.
2016-09-28 09:48:51 +02:00
Benjamin Tan
9a17313a0c Remove unnecessary files after removal of npm package. 2016-09-28 09:28:31 +02:00
Feross Aboukhadijeh
b3ec61ddd8 Make Portable App also a Silent App
Fixes two portable app bugs, to make the app fully "silent", not just
"portable". This means that not only are all data files stored in the
"Portable Settings" folder, but the app should leave no trace on the
host system.

- Disable Electron's single instance mode so no lock file is created in
"%APPDATA%\Roaming\WebTorrent".

- Put Electron crash files, and other electron files into the "Portable
Settings\Temp" folder instead of "%APPDATA%\Temp".
2016-09-28 09:26:26 +02:00
Benjamin Tan
7dcddf90e9 Remove .nodemonignore file.
Adding configuration files for every tool used will clutter up the
repository, especially for a configuration as simple as this.
2016-09-28 09:03:46 +02:00
Feross Aboukhadijeh
a94fdcae61 Fix "Download path missing" for Portable App first run
Create "Portable Settings/Downloads" folder to prevent "Download path
missing" warning.
2016-09-28 04:22:05 +02:00
Feross Aboukhadijeh
f9bb83815f Switch fs.statSync to fs.accessSync, which is faster 2016-09-27 22:59:00 +02:00
Feross Aboukhadijeh
dccaf16a02 Merge pull request #973 from feross/feross/style
Pixel values should use numbers, not strings
2016-09-27 20:58:53 +02:00
Feross Aboukhadijeh
f4ee831319 Pixel values should use numbers, not strings
React converts to string and adds 'px' automatically
2016-09-27 11:56:12 -07:00
Feross Aboukhadijeh
5bcf1c6379 Merge pull request #972 from feross/f/controlst
Don't show pointer cursor on torrent list checkbox
2016-09-27 20:54:53 +02:00
Feross Aboukhadijeh
d2eb87e821 Merge pull request #974 from feross/feross/portable
Fix Windows Portable App mode
2016-09-27 20:47:07 +02:00
Feross Aboukhadijeh
be08925eb4 Fix Windows Portable App mode
Fixes: #971

This is a perfect example of putting too many statements into a
try-catch block. My bad. I was trying to keep the code simple, but it
bit us here.

This happens because we were using IS_PRODUCTION, but the order of the
consts at the top are:

const IS_PORTABLE = isPortable()
const IS_PRODUCTION = isProduction()

So we're inside of isPortable() and referring to IS_PRODUCTION before
it's defined. This should have thrown an exception, since const does
not allow use-before-define, but we're transforming to ES5 with Babel.

Also, standard could have caught this, but we can't enable the
use-before-define rule until this bug is fixed:
https://github.com/feross/standard/issues/636

Basically, a perfect storm.
2016-09-26 22:54:59 -07:00
Feross Aboukhadijeh
5698c22e75 Don't show pointer cursor on torrent list checkbox
Native apps don't have the "hand" cursor
2016-09-26 17:28:45 -07:00
DC
2114532f62 Integration tests: fix on Windows 2016-09-25 19:58:11 -07:00
DC
815ba00a6b Integration tests: fix on Mac 2016-09-25 19:43:09 -07:00
DC
bcd9f046fb No more npm publish 2016-09-25 18:24:38 -07:00
DC
bf3b416662 changelog 2016-09-25 18:23:00 -07:00
DC
736832c4e3 authors 2016-09-25 18:23:00 -07:00
DC
f08c0995a2 0.17.0 2016-09-25 18:23:00 -07:00
DC
de8a4d1160 Design: smaller progress bar 2016-09-25 18:23:00 -07:00
DC
739c1f705e Design: torrent list expand and collapse handle 2016-09-25 18:22:53 -07:00
DC
a32889291f Design: don't show 'Paused' on new torrents 2016-09-25 17:57:15 -07:00
Noam Okman
1e7e4cafd4 Use the progress bar from Material UI (#967) 2016-09-25 15:42:07 -07:00
Feross Aboukhadijeh
d5bed6c50a Add more peer ID entropy (#960) 2016-09-23 12:14:50 -07:00
Dan Flettre
8f827c9aae avoid saving window bounds when on player (#964) 2016-09-23 12:09:06 -07:00
DC
24fe033e2f Design: bring back the old startup sound
Talked about it w @feross, the new one sounds kind of like an error or warning
2016-09-23 03:44:52 -07:00
DC
85d04f931b Design: update integration test screenshots 2016-09-23 03:42:13 -07:00
DC
41b111c8a8 Design: address PR comments 2016-09-23 03:33:16 -07:00
DC
72db60bb12 Player: handle case where torrent-to-HTTP server hasn't started yet 2016-09-23 02:59:57 -07:00
DC
076eb009b9 Fix bug where playback rate could go negative 2016-09-23 02:59:57 -07:00
DC
789bd0ce82 Don't hide header when moused over player controls 2016-09-23 02:59:52 -07:00
DC
5155fca0e4 Design: off white primary color 2016-09-23 02:59:48 -07:00
DC
3b6819f894 Unmount audio/video tag when exiting player 2016-09-23 02:59:48 -07:00
DC
0dd1683298 Remove play button spinner, go to player page immediately 2016-09-23 02:59:48 -07:00
DC
2788d7433b Design: torrent list 2016-09-23 02:59:48 -07:00
DC
504a2419f6 Design: remove extra CSS 2016-09-23 02:59:48 -07:00
DC
75e5316ba1 Design: no gradients, nicer default colors
Before, the gradient transparent black overlay made text hard to read in some cases. Torrents without a poster image showed up in blue-gray and didn't look good.
2016-09-23 02:59:47 -07:00
DC
3be018521a Torrent list redesign 2016-09-23 02:59:47 -07:00
Feross Aboukhadijeh
6d375d5b5b Wait for 'ready-to-show' event before showing window (#959)
This gets rid of the light gray to dark gray background color change on
the main window at startup. Makes the window show slightly later, but
it's gray for less time. Doesn't affect overall startup time. Feels
less jank IMO.

From the Electron docs:

> While loading the page, the 'ready-to-show' event will be emitted
when renderer process has done drawing for the first time, showing
window after this event will have no visual flash.
2016-09-23 02:59:22 -07:00
Feross Aboukhadijeh
5de39bd7e5 Merge pull request #957 from feross/f/perf
startup perf: Reduce require() calls
2016-09-23 04:38:12 +02:00
Feross Aboukhadijeh
a08d576851 startup perf: Reduce require() calls
Every require() that we do before the users sees UI reduces startup
time.

I used the following code (added to index.js) to log every require()
call in the main process:

```js
var Module = require('module')
var required = {}
Module.prototype.require = function (orig) {
  return function (id) {
    if (!required[id]) {
      required[id] = true
      console.log(`${id}   (from ${this.filename})`)
    }
    return orig.apply(this, arguments)
  }
}(Module.prototype.require)
```

From this I was able to learn that lots of modules were being required
that aren't actually used until later.

I also sent this related PR to eliminate another few require()s:
https://github.com/LinusU/node-application-config/pull/4

This increases startup time by 50ms.

We'll probably realize much bigger gains by following this same
procedure for the renderer process.
2016-09-22 16:33:26 -07:00
Feross Aboukhadijeh
b8bdf65514 Use subtler UI sounds (#945)
* Use subtler UI sounds

Fixes #858

* Second round of volume tweaks
2016-09-22 14:42:43 -07:00
Feross Aboukhadijeh
1c0c3d07ff Merge pull request #949 from feross/f/state
State cleanup, rename, & tweaks
2016-09-22 23:41:01 +02:00
Feross Aboukhadijeh
832980eb9a Update Electron to 1.4.1 (#955)
Changelog: https://github.com/electron/electron/releases/tag/v1.4.1

(Should fix the Spectron console issue that @dcposch reported.)
2016-09-22 14:39:32 -07:00
Feross Aboukhadijeh
7c158e9f2c Rename events to be consistent
- Make State.save() always throttle calls -- since that's the common
case.

- Immediate saves are now the exception, with State.saveImmediate().

- The function is called State.save(), so the dispatch event should be
'stateSave'.
2016-09-22 14:25:57 -07:00
Feross Aboukhadijeh
a98d22ed72 code style 2016-09-22 14:20:58 -07:00
Feross Aboukhadijeh
63b7d34e29 Merge pull request #954 from omrilitov/master
use arch to determine OS_SYSARCH
2016-09-22 23:07:20 +02:00
Omri Litov
67ae6061aa use arch to determine OS_SYSARCH 2016-09-22 23:29:02 +03:00
Feross Aboukhadijeh
a8a861260e main: Start loading state before app is ready (#952)
As mentioned in
https://github.com/feross/webtorrent-desktop/pull/827#discussion_r799219
59

We should load the state outside the app.on('ready') handler so there's
a chance it's ready by the time 'ready' fires.

This improves startup time by roughly 50ms on my Macbook 12".
2016-09-22 03:00:40 -07:00
Feross Aboukhadijeh
fc879d5801 Update electron-packager to v8 (#946)
* electron-packager@8

* package: updates for electron-packager 8
2016-09-22 02:42:43 -07:00
DC
2d2645e642 Integration test: announce list windows screenshot 2016-09-21 23:58:42 -07:00
DC
8e66f641ce Integration test: default announce list changed 2016-09-21 23:58:21 -07:00
DC
82c49b5fc5 Integration test: yet another round of fixes 2016-09-21 23:58:21 -07:00
DC
b57ee73035 Integration tests: extra wait in test-audio 2016-09-21 23:58:21 -07:00
Feross Aboukhadijeh
ed8f493b8b Merge pull request #950 from feross/f/config
Make config static, not dynamic
2016-09-21 22:46:30 +02:00
Feross Aboukhadijeh
9e853027da make config static, not dynamic
I don't think we should dynamically generate the config object -- it
makes it harder to figure out what's going on.
2016-09-21 13:08:32 -07:00
Feross Aboukhadijeh
1e05487acd state: Use dispatch instead of direct call 2016-09-21 11:48:23 -07:00
Feross Aboukhadijeh
167da9dfd5 Double wait time until quit
On my modern Macbook 12" I've run into "Saving state took too long.
Quitting.". We have users with spinning disk drives, so let's be a bit
more generous.
2016-09-21 11:46:41 -07:00
Feross Aboukhadijeh
46e138a376 state: Use debounce to throttle saves 2016-09-21 11:46:00 -07:00
DC
853db922f1 Integration test: windows screenshot fuzzy diff 2016-09-20 23:53:00 -07:00
DC
7bf51b11ee Integration test: screenshot timing 2016-09-20 23:51:38 -07:00
DC
3a286ae978 Integration test: wait for next song 2016-09-20 23:51:38 -07:00
DC
82245f0b5c Integration tests: README 2016-09-20 23:51:37 -07:00
DC
802a898394 Integration tests: offline by default 2016-09-20 23:51:37 -07:00
DC
2200fffa1e Fix integration tests on Windows 2016-09-20 23:51:37 -07:00
DC
f4b2e78e72 Fix Delete Data on Windows. Fixes #935 2016-09-20 23:51:37 -07:00
DC
ad1162c7de Integration tests on Windows 2016-09-20 23:51:33 -07:00
DC
ed4daeb560 Integration test reliability 2016-09-20 23:49:45 -07:00
Feross Aboukhadijeh
927ae16e4f Merge pull request #941 from feross/dc/perf
Fix a sad, sad bug that resulted in 100+MB config.json
2016-09-21 08:18:48 +02:00
Feross Aboukhadijeh
917c89542b Merge pull request #944 from feross/buble
Replace babel with bublé
2016-09-21 08:18:27 +02:00
Feross Aboukhadijeh
39570bd4d7 Replace babel with bublé
Pros of bubel over babel:

- No configuration (a la standard)
- Runs twice as fast, for quicker development
- Converts everything to ES5 (which is likely to be faster than ES6,
untested)
- Easy to swap Babel back in -- low commitment

Cons:
- Less battle-tested than Babel, but recommended by React core
developer so probably not too bad
- No babel plugin support, but we're not using that right now anyway.
Can switch back to babel if we need that later

BEFORE:

$ time npm run build

> webtorrent-desktop@0.16.0 build /Users/feross/code/webtorrent-desktop
> babel --quiet src --out-dir build

npm run build  3.07s user 0.27s system 115% cpu 2.902 total

AFTER:

$ time npm run build

> webtorrent-desktop@0.16.0 build /Users/feross/code/webtorrent-desktop
> buble src --output build

npm run build  1.38s user 0.16s system 114% cpu 1.343 total
2016-09-20 15:21:17 -07:00
DC
f368dfad81 Fix a sad, sad bug that resulted in 100+MB config.json 2016-09-19 22:31:26 -07:00
DC
205e17cc83 Merge pull request #937 from feross/dynamic-window-min-height
make WINDOW_MIN_HEIGHT use existing values
2016-09-19 19:30:05 -07:00
Dan Flettre
4e052c8059 make WINDOW_MIN_HEIGHT use existing values 2016-09-19 16:48:12 -05:00
Dan Flettre
0afecd6063 Merge pull request #827 from feross/window-position
remember window position
2016-09-19 16:04:46 -05:00
DC
41511c5615 Integration test: use /tmp 2016-09-18 19:17:07 -07:00
Feross Aboukhadijeh
b9d39e3c64 changelog 2016-09-18 03:03:45 -07:00
Feross Aboukhadijeh
c1f482a950 Fix app DMG image 2016-09-18 02:58:39 -07:00
Feross Aboukhadijeh
e424031ad9 Windows build path fix 2016-09-18 02:58:36 -07:00
Feross Aboukhadijeh
f43dc2fc98 Fix windows path rename 2016-09-18 02:11:23 -07:00
Feross Aboukhadijeh
9cdc73edce 0.16.0 2016-09-18 01:56:59 -07:00
Feross Aboukhadijeh
3d254fa075 changelog 2016-09-18 01:41:01 -07:00
Feross Aboukhadijeh
ed1e43015e Merge pull request #931 from feross/detect-arch
Add 64-bit Windows build
2016-09-18 10:37:05 +02:00
Feross Aboukhadijeh
e6cbbd73f0 Fix silly typo 2016-09-18 01:35:20 -07:00
Feross Aboukhadijeh
67dff7b38c Add sanity check 2016-09-18 01:33:51 -07:00
Feross Aboukhadijeh
ced67176a3 add changelog 2016-09-18 01:29:14 -07:00
Feross Aboukhadijeh
00ac8afe64 About window: Show 32-bit vs. 64-bit status 2016-09-18 01:22:16 -07:00
Feross Aboukhadijeh
a6964c4495 Change file name inside RELEASES-ia32 to match renamed file 2016-09-18 01:07:45 -07:00
Dan Flettre
aedbc3c32f remember window position 2016-09-18 00:29:37 -05:00
DC
6541291e0d Integration test: address PR comments 2016-09-17 20:35:54 -07:00
DC
711d274398 Integration test: mock cast, remove loading bar
This lets us use exact screenshots with no transparency.
2016-09-17 20:35:53 -07:00
DC
6c5861b9fc Test screenshots: Create Torrent raised button 2016-09-17 20:35:53 -07:00
DC
f7ab27f9fd Integration test: audio 2016-09-17 20:35:53 -07:00
DC
e4e789cc5b Integration test: screenshot compare ignoring transparency 2016-09-17 20:35:52 -07:00
DC
09b525fe58 Integration test: simplify offline mode 2016-09-17 20:35:52 -07:00
DC
9dabfc1367 Integration test: offline mode 2016-09-17 20:35:52 -07:00
DC
bdb733352a Integration test: video playback 2016-09-17 20:35:52 -07:00
DC
75a4655a0f Integration test: create torrents 2016-09-17 20:35:52 -07:00
DC
051c1516a0 Integration test: add existing torrent 2016-09-17 20:35:51 -07:00
DC
62c5b78358 Integration test: update README 2016-09-17 20:35:51 -07:00
DC
290913d07a Integration test: delete torrent + data 2016-09-17 20:35:51 -07:00
Feross Aboukhadijeh
77534d650a Add 64-bit Windows build
Right now all Windows users are running a 32-bit app, even if their OS
is 64-bit.

Here's the plan to improve things:

1. We release a 64-bit installer, in addition to the 32-bit installer.

2. We auto-detect in the browser when a visitor is on a 32-bit vs.
64-bit OS and try to offer them the right installer. When in doubt, we
give them the 32-bit installer since that's safest.

3. The auto-updater will return the right binaries for the architecture
the user is on. This means that all our existing users who have 64-bit
OSs but are running the 32-bit app will get updated to the 64-bit app
on the next update. Also, 64-bit users who accidentally download the
32-bit installer will also get the 64-bit app on the next update.

---

Other notes:

- We don't generate 32-bit delta files. See reasoning inline.
- The package script now deletes extraneous Squirrel files (i.e.
*.nupkg delta files for older versions of the app) which should make
uploading the right files to GitHub easier. :)

The binary file naming works like this:

- Most users are on 64-bit systems, so they get nice clean file names
that don't specify an architecture (WebTorrentSetup-v1.0.0.exe). The
32-bit build files have the same naming but contain the string "-ia32"
at the end. In a few years, we will be able to just stop producing the
32-bit build files entirely.

- This means that the "WebTorrent-v0.15.0-linux-x64.zip" linux build
file is changing to "WebTorrent-v0.15.0-linux.zip" to match the Windows
naming convention. The .deb installer files must contain to
architecture in order to install correctly, so those do not change.

- Mac is 100% 64-bit, so it does not change.
2016-09-17 19:37:50 -07:00
Feross Aboukhadijeh
a4c715e3f6 Merge pull request #928 from feross/detect-arch
Detect system architecture; send in update/telemetry
2016-09-17 16:21:46 -07:00
Feross Aboukhadijeh
7415d3cee5 Detect system architecture; send in update/telemetry
Detect the actual operating system CPU architecture. This is different
than `process.arch` which returns the architecture the binary was
compiled for.

This is just good info to have in the telemetry, but we're also sending
it in the update check so that eventually we can upgrade Windows 32-bit
apps to 64-bit, like Slack does.

Context:
https://github.com/feross/webtorrent-desktop/issues/873#issuecomment-247
722023
2016-09-16 19:24:21 -07:00
Feross Aboukhadijeh
e1ba9c89fe Merge pull request #922 from feross/raised
Use raised button for inline button
2016-09-16 15:45:20 -07:00
Feross Aboukhadijeh
0fcbe7369a Merge pull request #925 from feross/capture-frame
Use capture-frame package
2016-09-16 15:43:20 -07:00
Feross Aboukhadijeh
c8087b5b63 Merge pull request #926 from feross/electron-1.4.0
Electron 1.4.0
2016-09-16 15:42:44 -07:00
Feross Aboukhadijeh
065faca8eb Electron 1.4.0 2016-09-16 10:25:03 -07:00
Feross Aboukhadijeh
bcd6a38a05 Use capture-frame package
See: https://github.com/feross/capture-frame
Capture video screenshot from a `<video>` tag (at the current time)

Changes from our version:

- Added tests in Chrome/Firefox browsers.
- Use built-in TypeError (which is meant for bad arguments) instead of
custom IllegalArgumentError.
2016-09-16 10:14:39 -07:00
DC
fa67f9b82b changelog 2016-09-16 01:11:12 -07:00
DC
39acd0bd47 authors 2016-09-16 01:02:16 -07:00
DC
c549fcfc27 0.15.0 2016-09-16 01:01:32 -07:00
DC
45e838d4c3 Telemetry: add torrent stats 2016-09-16 00:54:07 -07:00
DC
64f49e4d4f Auto launch: start minimized on MacOS 2016-09-13 19:49:47 -07:00
DC
61caa90901 Auto launch: don't open a terminal on MacOS 2016-09-13 19:49:47 -07:00
Noam Okman
3e85289318 Pref: start automatically on login 2016-09-13 19:49:47 -07:00
Feross Aboukhadijeh
a629f287f0 Use raised button for inline button 2016-09-13 08:16:38 -07:00
Mathias Rasmussen
3a4906079b External player clean up (#914)
* minor `addSubtitles` clean up

* external player clean up
2016-09-12 17:46:48 -07:00
Kai Curtis
3edf21f457 Update mouse moved time on header hover (#919)
Previously, moving the mouse into the player window from the sides or
bottom would bring up the HUD, but moving the mouse in from the top
would not. With this commit, moving the mouse in from the top of the
window will also bring up the HUD.

Fixes feross/webtorrent-desktop#241
2016-09-12 17:46:23 -07:00
DC
785c44cd2a Integration test: torrent list 2016-09-08 23:55:37 -07:00
DC
1ad8a5313b Integration test: save failed screenshot comparisons 2016-09-08 19:13:14 -07:00
DC
967e161288 Integration test: screenshots 2016-09-08 19:10:28 -07:00
DC
fe8c3b190c Integration test: tape + spectron hello world 2016-09-08 19:10:28 -07:00
Benjamin Tan
993e7d77ad Fix notification click not working. (#912)
This was changed incorrectly in 2a1e987.
2016-09-08 16:16:43 -07:00
DC
e0be052df4 Fix Open Torrent Address modal
Fixes a bug introduced in 0.14.0: cicking OK works, but hitting Enter doesn't do anything
2016-09-07 13:28:49 -07:00
Adam Gotlib
d331bae548 Move error definitions to errors.js (#898) 2016-09-07 13:21:59 -07:00
Adam Gotlib
d88229694a Disable playback controls while in external player (#909) 2016-09-07 13:13:50 -07:00
Adam Gotlib
8da5b955d6 Make git ignore npm-debug.log (#896) 2016-09-05 20:04:21 -07:00
DC
54882679c1 Dedupe cast.js status handlers, fix #889 2016-09-04 15:10:39 -07:00
DC
f2007be1b0 Fix selectFiles error, fixes #891 2016-09-04 14:56:17 -07:00
DC
7a757f9e05 More info in torrentFileModtimes, fix #892 2016-09-04 14:27:22 -07:00
136 changed files with 2126 additions and 936 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,4 @@
node_modules/ node_modules/
build/ build/
dist/ dist/
npm-debug.log.* npm-debug.log*

View File

@@ -1,2 +0,0 @@
build/
dist/

View File

@@ -32,5 +32,7 @@
- Vamsi Krishna Avula (vamsi_ism@outlook.com) - Vamsi Krishna Avula (vamsi_ism@outlook.com)
- Noam Okman (noamokman@gmail.com) - Noam Okman (noamokman@gmail.com)
- PurgingPanda (t3ch0wn3r@gmail.com) - PurgingPanda (t3ch0wn3r@gmail.com)
- Kai Curtis (morecode@kcurtis.com)
- Omri Litov (omrilitov@gmail.com)
#### Generated by bin/update-authors.sh. #### Generated by bin/update-authors.sh.

View File

@@ -1,5 +1,74 @@
# WebTorrent Desktop Version History # WebTorrent Desktop Version History
## v0.17.2 - 2016-10-10
### Fixed
- Windows: Fix impossible-to-delete "Wired CD" default torrent
- Throttle browser-window 'move' and 'resize' events
- Fix crash ("Cannot read property 'files' of null" error)
- Fix crash ("TypeError: Cannot read property 'startPiece' of undefined")
## v0.17.1 - 2016-10-03
### Changed
- Faster startup (improved by ~25%)
- Update Electron to 1.4.2
- Remove support for pasting multiple newline-separated magnet links
- Reduce UX sound volume
### Fixed
- Fix external player (VLC, etc.) opening before HTTP server was ready
- Windows (Portable App): Fix "Portable App" mode
- Write application support files to the "Portable Settings" folder
- Stop writing Electron "single instance" lock file to "%APPDATA%\Roaming\WebTorrent"
- Some temp data is still written to "%APPDATA%\Temp" (will be fixed in future version)
- Don't show pointer cursor on torrent list checkbox
- Trim extra whitespace from magnet links pasted into "Open Torrent Address" dialog
- Fix weird outline on 'Create Torrent' button
## v0.17.0 - 2016-09-23
### Added
- Remember window size and position
### Changed
- Torrent list redesign
- Quieter, more subtle sounds
- Got rid of the play button spinner, now goes to the player immediately
- Faster startup
### Fixed
- Fix bug where playback rate could go negative
- Don't hide header when moused over player controls
- Fix Delete Data File on Windows
- Fix a sad, sad bug that resulted in 100+ MB config files
- Fix app DMG background image
## v0.16.0 - 2016-09-18
### Added
- **Windows 64-bit support!** ([#931](https://github.com/feross/webtorrent-desktop/pull/931))
- Existing 32-bit users will update to 64-bit automatically in next release
- 64-bit reduces likelihood of out-of-memory errors by increasing the address space
### Fixed
- Mac: Fix background image on .DMG
## v0.15.0 - 2016-09-16
### Added
- Option to start automatically on login
- Add integration tests
- Add more detailed telemetry to diagnose "buffer allocation failed"
### Changed
- Disable playback controls while in external player (#909)
### Fixed
- Fix several uncaught errors (#889, #891, #892)
- Update to the latest webtorrent.js, fixing some more uncaught errors
- Clicking on the "torrent finished" notification works again (#912)
## v0.14.0 - 2016-09-03 ## v0.14.0 - 2016-09-03
### Added ### Added

View File

@@ -56,6 +56,32 @@ Restart the app automatically every time code changes. Useful during development
$ npm run watch $ npm run watch
``` ```
### Run linters
```
$ npm test
```
### Run integration tests
```
$ npm run test-integration
```
The integration tests use Spectron and Tape. They click through the app, taking screenshots and comparing each one to a reference. Why screenshots?
* Ad-hoc checking makes the tests a lot more work to write
* Even diffing the whole HTML is not as thorough as screenshot diffing. For example, it wouldn't catch an bug where hitting ESC from a video doesn't correctly restore window size.
* Chrome's own integration tests use screenshot diffing iirc
* Small UI changes will break a few tests, but the fix is as easy as deleting the offending screenshots and running the tests, which will recreate them with the new look.
* The resulting Github PR will then show, pixel by pixel, the exact UI changes that were made! Ses https://github.com/blog/817-behold-image-view-modes
For MacOS, you'll need a Retina screen for the integration tests to pass. Your screen should have the same resolution as a 2016 12" Macbook.
For Windows, you'll need Windows 10 with a 1366x768 screen.
When running integration tests, keep the mouse on the edge of the screen and don't touch the mouse or keyboard while the tests are running.
### Package the app ### Package the app
Builds app binaries for Mac, Linux, and Windows. Builds app binaries for Mac, Linux, and Windows.

View File

@@ -5,13 +5,13 @@
* Useful for developers. * Useful for developers.
*/ */
var fs = require('fs') const fs = require('fs')
var os = require('os') const os = require('os')
var path = require('path') const path = require('path')
var rimraf = require('rimraf') const rimraf = require('rimraf')
var config = require('../src/config') const config = require('../src/config')
var handlers = require('../src/main/handlers') const handlers = require('../src/main/handlers')
// First, remove generated files // First, remove generated files
rimraf.sync('build/') rimraf.sync('build/')
@@ -21,7 +21,7 @@ rimraf.sync('dist/')
rimraf.sync(config.CONFIG_PATH) rimraf.sync(config.CONFIG_PATH)
// Remove any temporary files // Remove any temporary files
var tmpPath let tmpPath
try { try {
tmpPath = path.join(fs.statSync('/tmp') && '/tmp', 'webtorrent') tmpPath = path.join(fs.statSync('/tmp') && '/tmp', 'webtorrent')
} catch (err) { } catch (err) {

View File

@@ -1,10 +0,0 @@
#!/usr/bin/env node
var electron = require('electron')
var cp = require('child_process')
var path = require('path')
var child = cp.spawn(electron, [path.join(__dirname, '..')], {stdio: 'inherit'})
child.on('close', function (code) {
process.exitCode = code
})

View File

@@ -7,16 +7,16 @@ const path = require('path')
let hasErrors = false let hasErrors = false
// Find all Javascript source files // Find all Javascript source files
var files = walkSync('src', {globs: ['**/*.js']}) const files = walkSync('src', {globs: ['**/*.js']})
console.log('Running extra-lint on ' + files.length + ' files...') console.log('Running extra-lint on ' + files.length + ' files...')
// Read each file, line by line // Read each file, line by line
files.forEach(function (file) { files.forEach(function (file) {
var filepath = path.join('src', file) const filepath = path.join('src', file)
var lines = fs.readFileSync(filepath, 'utf8').split('\n') const lines = fs.readFileSync(filepath, 'utf8').split('\n')
lines.forEach(function (line, i) { lines.forEach(function (line, i) {
var error let error
// Consistent JSX tag closing // Consistent JSX tag closing
if (line.match(/' {2}\/> *$/) || if (line.match(/' {2}\/> *$/) ||

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
var config = require('../src/config') const config = require('../src/config')
var open = require('open') const open = require('open')
open(config.CONFIG_PATH) open(config.CONFIG_PATH)

View File

@@ -1,28 +1,28 @@
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Builds app binaries for Mac, Linux, and Windows. * Builds app binaries for Mac, Windows, and Linux.
*/ */
var cp = require('child_process') const cp = require('child_process')
var electronPackager = require('electron-packager') const electronPackager = require('electron-packager')
var fs = require('fs') const fs = require('fs')
var minimist = require('minimist') const minimist = require('minimist')
var mkdirp = require('mkdirp') const mkdirp = require('mkdirp')
var os = require('os') const os = require('os')
var path = require('path') const path = require('path')
var rimraf = require('rimraf') const rimraf = require('rimraf')
var series = require('run-series') const series = require('run-series')
var zip = require('cross-zip') const zip = require('cross-zip')
var config = require('../src/config') const config = require('../src/config')
var pkg = require('../package.json') const pkg = require('../package.json')
var BUILD_NAME = config.APP_NAME + '-v' + config.APP_VERSION const BUILD_NAME = config.APP_NAME + '-v' + config.APP_VERSION
var BUILD_PATH = path.join(config.ROOT_PATH, 'build') const BUILD_PATH = path.join(config.ROOT_PATH, 'build')
var DIST_PATH = path.join(config.ROOT_PATH, 'dist') const DIST_PATH = path.join(config.ROOT_PATH, 'dist')
var argv = minimist(process.argv.slice(2), { const argv = minimist(process.argv.slice(2), {
boolean: [ boolean: [
'sign' 'sign'
], ],
@@ -39,11 +39,11 @@ function build () {
rimraf.sync(DIST_PATH) rimraf.sync(DIST_PATH)
rimraf.sync(BUILD_PATH) rimraf.sync(BUILD_PATH)
console.log('Babel: Building JSX...') console.log('Build: Transpiling to ES5...')
cp.execSync('npm run build', { NODE_ENV: 'production', stdio: 'inherit' }) cp.execSync('npm run build', { NODE_ENV: 'production', stdio: 'inherit' })
console.log('Babel: Built JSX.') console.log('Build: Transpiled to ES5.')
var platform = argv._[0] const platform = argv._[0]
if (platform === 'darwin') { if (platform === 'darwin') {
buildDarwin(printDone) buildDarwin(printDone)
} else if (platform === 'win32') { } else if (platform === 'win32') {
@@ -61,7 +61,7 @@ function build () {
} }
} }
var all = { const all = {
// The human-readable copyright line for the app. Maps to the `LegalCopyright` metadata // The human-readable copyright line for the app. Maps to the `LegalCopyright` metadata
// property on Windows, and `NSHumanReadableCopyright` on Mac. // property on Windows, and `NSHumanReadableCopyright` on Mac.
'app-copyright': config.APP_COPYRIGHT, 'app-copyright': config.APP_COPYRIGHT,
@@ -73,11 +73,11 @@ var all = {
// Package the application's source code into an archive, using Electron's archive // Package the application's source code into an archive, using Electron's archive
// format. Mitigates issues around long path names on Windows and slightly speeds up // format. Mitigates issues around long path names on Windows and slightly speeds up
// require(). // require().
asar: true, asar: {
// A glob expression, that unpacks the files with matching names to the
// A glob expression, that unpacks the files with matching names to the // "app.asar.unpacked" directory.
// "app.asar.unpacked" directory. unpack: 'WebTorrent*'
'asar-unpack': 'WebTorrent*', },
// The build version of the application. Maps to the FileVersion metadata property on // The build version of the application. Maps to the FileVersion metadata property on
// Windows, and CFBundleVersion on Mac. Note: Windows requires the build version to // Windows, and CFBundleVersion on Mac. Note: Windows requires the build version to
@@ -108,11 +108,11 @@ var all = {
version: require('electron/package.json').version version: require('electron/package.json').version
} }
var darwin = { const darwin = {
// Build for Mac // Build for Mac
platform: 'darwin', platform: 'darwin',
// Build 64 bit binaries only. // Build x64 binaries only.
arch: 'x64', arch: 'x64',
// The bundle identifier to use in the application's plist (Mac only). // The bundle identifier to use in the application's plist (Mac only).
@@ -129,15 +129,15 @@ var darwin = {
icon: config.APP_ICON + '.icns' icon: config.APP_ICON + '.icns'
} }
var win32 = { const win32 = {
// Build for Windows. // Build for Windows.
platform: 'win32', platform: 'win32',
// Build 32 bit binaries only. // Build ia32 and x64 binaries.
arch: 'ia32', arch: ['ia32', 'x64'],
// Object hash of application metadata to embed into the executable (Windows only) // Object hash of application metadata to embed into the executable (Windows only)
'version-string': { win32metadata: {
// Company that produced the file. // Company that produced the file.
CompanyName: config.APP_NAME, CompanyName: config.APP_NAME,
@@ -163,12 +163,12 @@ var win32 = {
icon: config.APP_ICON + '.ico' icon: config.APP_ICON + '.ico'
} }
var linux = { const linux = {
// Build for Linux. // Build for Linux.
platform: 'linux', platform: 'linux',
// Build 32 and 64 bit binaries. // Build ia32 and x64 binaries.
arch: 'all' arch: ['ia32', 'x64']
// Note: Application icon for Linux is specified via the BrowserWindow `icon` option. // Note: Application icon for Linux is specified via the BrowserWindow `icon` option.
} }
@@ -176,18 +176,18 @@ var linux = {
build() build()
function buildDarwin (cb) { function buildDarwin (cb) {
var plist = require('plist') const plist = require('plist')
console.log('Mac: Packaging electron...') console.log('Mac: Packaging electron...')
electronPackager(Object.assign({}, all, darwin), function (err, buildPath) { electronPackager(Object.assign({}, all, darwin), function (err, buildPath) {
if (err) return cb(err) if (err) return cb(err)
console.log('Mac: Packaged electron. ' + buildPath) console.log('Mac: Packaged electron. ' + buildPath)
var appPath = path.join(buildPath[0], config.APP_NAME + '.app') const appPath = path.join(buildPath[0], config.APP_NAME + '.app')
var contentsPath = path.join(appPath, 'Contents') const contentsPath = path.join(appPath, 'Contents')
var resourcesPath = path.join(contentsPath, 'Resources') const resourcesPath = path.join(contentsPath, 'Resources')
var infoPlistPath = path.join(contentsPath, 'Info.plist') const infoPlistPath = path.join(contentsPath, 'Info.plist')
var infoPlist = plist.parse(fs.readFileSync(infoPlistPath, 'utf8')) const infoPlist = plist.parse(fs.readFileSync(infoPlistPath, 'utf8'))
infoPlist.CFBundleDocumentTypes = [ infoPlist.CFBundleDocumentTypes = [
{ {
@@ -261,7 +261,7 @@ function buildDarwin (cb) {
} }
function signApp (cb) { function signApp (cb) {
var sign = require('electron-osx-sign') const sign = require('electron-osx-sign')
/* /*
* Sign the app with Apple Developer ID certificates. We sign the app for 2 reasons: * Sign the app with Apple Developer ID certificates. We sign the app for 2 reasons:
@@ -276,7 +276,7 @@ function buildDarwin (cb) {
* - Xcode Command Line Tools (xcode-select --install) * - Xcode Command Line Tools (xcode-select --install)
* - Membership in the Apple Developer Program * - Membership in the Apple Developer Program
*/ */
var signOpts = { const signOpts = {
app: appPath, app: appPath,
platform: 'darwin', platform: 'darwin',
verbose: true verbose: true
@@ -302,8 +302,8 @@ function buildDarwin (cb) {
// Create .zip file (used by the auto-updater) // Create .zip file (used by the auto-updater)
console.log('Mac: Creating zip...') console.log('Mac: Creating zip...')
var inPath = path.join(buildPath[0], config.APP_NAME + '.app') const inPath = path.join(buildPath[0], config.APP_NAME + '.app')
var outPath = path.join(DIST_PATH, BUILD_NAME + '-darwin.zip') const outPath = path.join(DIST_PATH, BUILD_NAME + '-darwin.zip')
zip.zipSync(inPath, outPath) zip.zipSync(inPath, outPath)
console.log('Mac: Created zip.') console.log('Mac: Created zip.')
@@ -312,13 +312,13 @@ function buildDarwin (cb) {
function packageDmg (cb) { function packageDmg (cb) {
console.log('Mac: Creating dmg...') console.log('Mac: Creating dmg...')
var appDmg = require('appdmg') const appDmg = require('appdmg')
var targetPath = path.join(DIST_PATH, BUILD_NAME + '.dmg') const targetPath = path.join(DIST_PATH, BUILD_NAME + '.dmg')
rimraf.sync(targetPath) rimraf.sync(targetPath)
// Create a .dmg (Mac disk image) file, for easy user installation. // Create a .dmg (Mac disk image) file, for easy user installation.
var dmgOpts = { const dmgOpts = {
basepath: config.ROOT_PATH, basepath: config.ROOT_PATH,
target: targetPath, target: targetPath,
specification: { specification: {
@@ -339,7 +339,7 @@ function buildDarwin (cb) {
} }
} }
var dmg = appDmg(dmgOpts) const dmg = appDmg(dmgOpts)
dmg.once('error', cb) dmg.once('error', cb)
dmg.on('progress', function (info) { dmg.on('progress', function (info) {
if (info.type === 'step-begin') console.log(info.title + '...') if (info.type === 'step-begin') console.log(info.title + '...')
@@ -353,7 +353,7 @@ function buildDarwin (cb) {
} }
function buildWin32 (cb) { function buildWin32 (cb) {
var installer = require('electron-winstaller') const installer = require('electron-winstaller')
console.log('Windows: Packaging electron...') console.log('Windows: Packaging electron...')
/* /*
@@ -361,7 +361,7 @@ function buildWin32 (cb) {
* - Windows Authenticode private key and cert (authenticode.p12) * - Windows Authenticode private key and cert (authenticode.p12)
* - Windows Authenticode password file (authenticode.txt) * - Windows Authenticode password file (authenticode.txt)
*/ */
var CERT_PATH let CERT_PATH
try { try {
fs.accessSync('D:') fs.accessSync('D:')
CERT_PATH = 'D:' CERT_PATH = 'D:'
@@ -373,12 +373,12 @@ function buildWin32 (cb) {
if (err) return cb(err) if (err) return cb(err)
console.log('Windows: Packaged electron. ' + buildPath) console.log('Windows: Packaged electron. ' + buildPath)
var signWithParams let signWithParams
if (process.platform === 'win32') { if (process.platform === 'win32') {
if (argv.sign) { if (argv.sign) {
var certificateFile = path.join(CERT_PATH, 'authenticode.p12') const certificateFile = path.join(CERT_PATH, 'authenticode.p12')
var certificatePassword = fs.readFileSync(path.join(CERT_PATH, 'authenticode.txt'), 'utf8') const certificatePassword = fs.readFileSync(path.join(CERT_PATH, 'authenticode.txt'), 'utf8')
var timestampServer = 'http://timestamp.comodoca.com' const timestampServer = 'http://timestamp.comodoca.com'
signWithParams = `/a /f "${certificateFile}" /p "${certificatePassword}" /tr "${timestampServer}" /td sha256` signWithParams = `/a /f "${certificateFile}" /p "${certificatePassword}" /tr "${timestampServer}" /td sha256`
} else { } else {
printWarning() printWarning()
@@ -387,20 +387,26 @@ function buildWin32 (cb) {
printWarning() printWarning()
} }
var tasks = [] const tasks = []
if (argv.package === 'exe' || argv.package === 'all') { buildPath.forEach(function (filesPath) {
tasks.push((cb) => packageInstaller(cb)) const destArch = filesPath.split('-').pop()
}
if (argv.package === 'portable' || argv.package === 'all') { if (argv.package === 'exe' || argv.package === 'all') {
tasks.push((cb) => packagePortable(cb)) tasks.push((cb) => packageInstaller(filesPath, destArch, cb))
} }
if (argv.package === 'portable' || argv.package === 'all') {
tasks.push((cb) => packagePortable(filesPath, destArch, cb))
}
})
series(tasks, cb) series(tasks, cb)
function packageInstaller (cb) { function packageInstaller (filesPath, destArch, cb) {
console.log('Windows: Creating installer...') console.log(`Windows: Creating ${destArch} installer...`)
const archStr = destArch === 'ia32' ? '-ia32' : ''
installer.createWindowsInstaller({ installer.createWindowsInstaller({
appDirectory: buildPath[0], appDirectory: filesPath,
authors: config.APP_TEAM, authors: config.APP_TEAM,
description: config.APP_NAME, description: config.APP_NAME,
exe: config.APP_NAME + '.exe', exe: config.APP_NAME + '.exe',
@@ -410,8 +416,26 @@ function buildWin32 (cb) {
noMsi: true, noMsi: true,
outputDirectory: DIST_PATH, outputDirectory: DIST_PATH,
productName: config.APP_NAME, productName: config.APP_NAME,
remoteReleases: config.GITHUB_URL, /**
setupExe: config.APP_NAME + 'Setup-v' + config.APP_VERSION + '.exe', * Only create delta updates for the Windows x64 build because 90% of our
* users have Windows x64 and the delta files take a *very* long time to
* generate. Also, the ia32 files on GitHub have non-standard Squirrel
* names (i.e. RELEASES-ia32 instead of RELEASES) and so Squirrel won't
* find them unless we proxy the requests.
*/
// TODO: Re-enable Windows 64-bit delta updates when we confirm that they
// work correctly in the presence of the "ia32" .nupkg files. I
// (feross) noticed them listed in the 64-bit RELEASES file and
// manually edited them out for the v0.17 release. Shipping only
// full updates for now will work fine, with no ill-effects.
// remoteReleases: destArch === 'x64'
// ? config.GITHUB_URL
// : undefined,
/**
* If you hit a "GitHub API rate limit exceeded" error, set this token!
*/
// remoteToken: process.env.WEBTORRENT_GITHUB_API_TOKEN,
setupExe: config.APP_NAME + 'Setup-v' + config.APP_VERSION + archStr + '.exe',
setupIcon: config.APP_ICON + '.ico', setupIcon: config.APP_ICON + '.ico',
signWithParams: signWithParams, signWithParams: signWithParams,
title: config.APP_NAME, title: config.APP_NAME,
@@ -419,23 +443,71 @@ function buildWin32 (cb) {
version: pkg.version version: pkg.version
}) })
.then(function () { .then(function () {
console.log('Windows: Created installer.') console.log(`Windows: Created ${destArch} installer.`)
/**
* Delete extraneous Squirrel files (i.e. *.nupkg delta files for older
* versions of the app)
*/
fs.readdirSync(DIST_PATH)
.filter((name) => name.endsWith('.nupkg') && !name.includes(pkg.version))
.forEach((filename) => {
fs.unlinkSync(path.join(DIST_PATH, filename))
})
if (destArch === 'ia32') {
console.log('Windows: Renaming ia32 installer files...')
// RELEASES -> RELEASES-ia32
const relPath = path.join(DIST_PATH, 'RELEASES-ia32')
fs.renameSync(
path.join(DIST_PATH, 'RELEASES'),
relPath
)
// WebTorrent-vX.X.X-full.nupkg -> WebTorrent-vX.X.X-ia32-full.nupkg
fs.renameSync(
path.join(DIST_PATH, `${config.APP_NAME}-${config.APP_VERSION}-full.nupkg`),
path.join(DIST_PATH, `${config.APP_NAME}-${config.APP_VERSION}-ia32-full.nupkg`)
)
// Change file name inside RELEASES-ia32 to match renamed file
const relContent = fs.readFileSync(relPath, 'utf8')
const relContent32 = relContent.replace('full.nupkg', 'ia32-full.nupkg')
fs.writeFileSync(relPath, relContent32)
if (relContent === relContent32) {
// Sanity check
throw new Error('Fixing RELEASES-ia32 failed. Replacement did not modify the file.')
}
console.log('Windows: Renamed ia32 installer files.')
}
cb(null) cb(null)
}) })
.catch(cb) .catch(cb)
} }
function packagePortable (cb) { function packagePortable (filesPath, destArch, cb) {
console.log('Windows: Creating portable app...') console.log(`Windows: Creating ${destArch} portable app...`)
var portablePath = path.join(buildPath[0], 'Portable Settings') const portablePath = path.join(filesPath, 'Portable Settings')
mkdirp.sync(portablePath) mkdirp.sync(portablePath)
var inPath = path.join(DIST_PATH, path.basename(buildPath[0])) const downloadsPath = path.join(portablePath, 'Downloads')
var outPath = path.join(DIST_PATH, BUILD_NAME + '-win.zip') mkdirp.sync(downloadsPath)
const tempPath = path.join(portablePath, 'Temp')
mkdirp.sync(tempPath)
const archStr = destArch === 'ia32' ? '-ia32' : ''
const inPath = path.join(DIST_PATH, path.basename(filesPath))
const outPath = path.join(DIST_PATH, BUILD_NAME + '-win' + archStr + '.zip')
zip.zipSync(inPath, outPath) zip.zipSync(inPath, outPath)
console.log('Windows: Created portable app.') console.log(`Windows: Created ${destArch} portable app.`)
cb(null) cb(null)
} }
}) })
@@ -447,9 +519,9 @@ function buildLinux (cb) {
if (err) return cb(err) if (err) return cb(err)
console.log('Linux: Packaged electron. ' + buildPath) console.log('Linux: Packaged electron. ' + buildPath)
var tasks = [] const tasks = []
buildPath.forEach(function (filesPath) { buildPath.forEach(function (filesPath) {
var destArch = filesPath.split('-').pop() const destArch = filesPath.split('-').pop()
if (argv.package === 'deb' || argv.package === 'all') { if (argv.package === 'deb' || argv.package === 'all') {
tasks.push((cb) => packageDeb(filesPath, destArch, cb)) tasks.push((cb) => packageDeb(filesPath, destArch, cb))
@@ -465,8 +537,8 @@ function buildLinux (cb) {
// Create .deb file for Debian-based platforms // Create .deb file for Debian-based platforms
console.log(`Linux: Creating ${destArch} deb...`) console.log(`Linux: Creating ${destArch} deb...`)
var deb = require('nobin-debian-installer')() const deb = require('nobin-debian-installer')()
var destPath = path.join('/opt', pkg.name) const destPath = path.join('/opt', pkg.name)
deb.pack({ deb.pack({
package: pkg, package: pkg,
@@ -500,8 +572,10 @@ function buildLinux (cb) {
// Create .zip file for Linux // Create .zip file for Linux
console.log(`Linux: Creating ${destArch} zip...`) console.log(`Linux: Creating ${destArch} zip...`)
var inPath = path.join(DIST_PATH, path.basename(filesPath)) const archStr = destArch === 'ia32' ? '-ia32' : ''
var outPath = path.join(DIST_PATH, BUILD_NAME + '-linux-' + destArch + '.zip')
const inPath = path.join(DIST_PATH, path.basename(filesPath))
const outPath = path.join(DIST_PATH, BUILD_NAME + '-linux' + archStr + '.zip')
zip.zipSync(inPath, outPath) zip.zipSync(inPath, outPath)
console.log(`Linux: Created ${destArch} zip.`) console.log(`Linux: Created ${destArch} zip.`)

View File

@@ -6,5 +6,4 @@ git diff --exit-code
npm run package -- --sign npm run package -- --sign
git push git push
git push --tags git push --tags
npm publish
npm run gh-release npm run gh-release

View File

@@ -1,33 +1,37 @@
{ {
"name": "webtorrent-desktop", "name": "webtorrent-desktop",
"description": "WebTorrent, the streaming torrent client. For Mac, Windows, and Linux.", "description": "WebTorrent, the streaming torrent client. For Mac, Windows, and Linux.",
"version": "0.14.0", "version": "0.17.2",
"author": { "author": {
"name": "WebTorrent, LLC", "name": "WebTorrent, LLC",
"email": "feross@webtorrent.io", "email": "feross@webtorrent.io",
"url": "https://webtorrent.io" "url": "https://webtorrent.io"
}, },
"bin": {
"webtorrent-desktop": "./bin/cmd.js"
},
"bugs": { "bugs": {
"url": "https://github.com/feross/webtorrent-desktop/issues" "url": "https://github.com/feross/webtorrent-desktop/issues"
}, },
"dependencies": { "dependencies": {
"airplayer": "^2.0.0", "airplayer": "^2.0.0",
"application-config": "^1.0.0", "application-config": "^1.0.0",
"arch": "^2.0.0",
"auto-launch": "^4.0.1",
"bitfield": "^1.0.2", "bitfield": "^1.0.2",
"capture-frame": "^1.0.0",
"chromecasts": "^1.8.0", "chromecasts": "^1.8.0",
"cp-file": "^4.0.1",
"create-torrent": "^3.24.5", "create-torrent": "^3.24.5",
"debounce": "^1.0.0",
"deep-equal": "^1.0.1", "deep-equal": "^1.0.1",
"dlnacasts": "^0.1.0", "dlnacasts": "^0.1.0",
"drag-drop": "^2.12.1", "drag-drop": "^2.12.1",
"electron": "1.3.3", "es6-error": "^3.0.1",
"fs-extra": "^0.30.0", "fn-getter": "^1.0.0",
"iso-639-1": "^1.2.1", "iso-639-1": "^1.2.1",
"languagedetect": "^1.1.1", "languagedetect": "^1.1.1",
"location-history": "^1.0.0", "location-history": "^1.0.0",
"lodash.merge": "^4.6.0",
"material-ui": "^0.15.4", "material-ui": "^0.15.4",
"mkdirp": "^0.5.1",
"musicmetadata": "^2.0.2", "musicmetadata": "^2.0.2",
"network-address": "^1.1.0", "network-address": "^1.1.0",
"parse-torrent": "^5.7.3", "parse-torrent": "^5.7.3",
@@ -35,6 +39,7 @@
"react": "^15.2.1", "react": "^15.2.1",
"react-dom": "^15.2.1", "react-dom": "^15.2.1",
"react-tap-event-plugin": "^1.0.0", "react-tap-event-plugin": "^1.0.0",
"rimraf": "^2.5.2",
"run-parallel": "^1.1.6", "run-parallel": "^1.1.6",
"semver": "^5.1.0", "semver": "^5.1.0",
"simple-concat": "^1.0.0", "simple-concat": "^1.0.0",
@@ -46,26 +51,24 @@
"zero-fill": "^2.2.3" "zero-fill": "^2.2.3"
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.11.4", "buble": "^0.14.0",
"babel-plugin-syntax-jsx": "^6.13.0",
"babel-plugin-transform-es2015-destructuring": "^6.9.0",
"babel-plugin-transform-object-rest-spread": "^6.8.0",
"babel-plugin-transform-react-jsx": "^6.8.0",
"cross-zip": "^2.0.1", "cross-zip": "^2.0.1",
"depcheck": "^0.6.4", "depcheck": "^0.6.4",
"electron": "1.4.2",
"electron-osx-sign": "^0.3.0", "electron-osx-sign": "^0.3.0",
"electron-packager": "^7.0.0", "electron-packager": "^8.0.0",
"electron-winstaller": "^2.3.0", "electron-winstaller": "^2.3.0",
"gh-release": "^2.0.3", "gh-release": "^2.0.3",
"minimist": "^1.2.0", "minimist": "^1.2.0",
"mkdirp": "^0.5.1",
"nobin-debian-installer": "^0.0.10", "nobin-debian-installer": "^0.0.10",
"nodemon": "^1.10.2", "nodemon": "^1.10.2",
"open": "0.0.5", "open": "0.0.5",
"plist": "^2.0.1", "plist": "^2.0.1",
"rimraf": "^2.5.2", "pngjs": "^3.0.0",
"run-series": "^1.1.4", "run-series": "^1.1.4",
"spectron": "^3.3.0",
"standard": "*", "standard": "*",
"tape": "^4.6.0",
"walk-sync": "^0.3.1" "walk-sync": "^0.3.1"
}, },
"engines": { "engines": {
@@ -87,21 +90,23 @@
"optionalDependencies": { "optionalDependencies": {
"appdmg": "^0.4.3" "appdmg": "^0.4.3"
}, },
"private": true,
"productName": "WebTorrent", "productName": "WebTorrent",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/feross/webtorrent-desktop.git" "url": "git://github.com/feross/webtorrent-desktop.git"
}, },
"scripts": { "scripts": {
"build": "babel --quiet src --out-dir build", "build": "buble src --output build",
"clean": "node ./bin/clean.js", "clean": "node ./bin/clean.js",
"gh-release": "gh-release",
"open-config": "node ./bin/open-config.js", "open-config": "node ./bin/open-config.js",
"package": "node ./bin/package.js", "package": "node ./bin/package.js",
"prepublish": "npm run build", "prepublish": "npm run build",
"start": "npm run build && electron .", "start": "npm run build && electron .",
"test": "standard && depcheck --ignores=babel-cli,nodemon,gh-release --ignore-dirs=build,dist && node ./bin/extra-lint.js", "test": "standard && depcheck --ignores=buble,lodash.merge,nodemon,gh-release --ignore-dirs=build,dist && node ./bin/extra-lint.js",
"gh-release": "gh-release", "test-integration": "npm run build && node ./test",
"update-authors": "./bin/update-authors.sh", "update-authors": "./bin/update-authors.sh",
"watch": "nodemon --exec \"npm run start\" --ext js,pug,css" "watch": "nodemon --exec \"npm run start\" --ext js,css --ignore build/ --ignore dist/"
} }
} }

View File

@@ -1,8 +0,0 @@
{
"plugins": [
"syntax-jsx",
"transform-es2015-destructuring",
"transform-object-rest-spread",
"transform-react-jsx"
]
}

View File

@@ -1,12 +1,21 @@
const appConfig = require('application-config')('WebTorrent') const appConfig = require('application-config')('WebTorrent')
const fs = require('fs')
const path = require('path') const path = require('path')
const electron = require('electron')
const arch = require('arch')
const APP_NAME = 'WebTorrent' const APP_NAME = 'WebTorrent'
const APP_TEAM = 'WebTorrent, LLC' const APP_TEAM = 'WebTorrent, LLC'
const APP_VERSION = require('../package.json').version const APP_VERSION = require('../package.json').version
const PORTABLE_PATH = path.join(path.dirname(process.execPath), 'Portable Settings') const IS_TEST = isTest()
const PORTABLE_PATH = IS_TEST
? path.join(process.platform === 'win32' ? 'C:\\Windows\\Temp' : '/tmp', 'WebTorrentTest')
: path.join(path.dirname(process.execPath), 'Portable Settings')
const IS_PRODUCTION = isProduction()
const IS_PORTABLE = isPortable()
const UI_HEADER_HEIGHT = 38
const UI_TORRENT_HEIGHT = 100
module.exports = { module.exports = {
ANNOUNCEMENT_URL: 'https://webtorrent.io/desktop/announcement', ANNOUNCEMENT_URL: 'https://webtorrent.io/desktop/announcement',
@@ -26,27 +35,32 @@ module.exports = {
DEFAULT_TORRENTS: [ DEFAULT_TORRENTS: [
{ {
testID: 'bbb',
name: 'Big Buck Bunny', name: 'Big Buck Bunny',
posterFileName: 'bigBuckBunny.jpg', posterFileName: 'bigBuckBunny.jpg',
torrentFileName: 'bigBuckBunny.torrent' torrentFileName: 'bigBuckBunny.torrent'
}, },
{ {
testID: 'cosmos',
name: 'Cosmos Laundromat (Preview)', name: 'Cosmos Laundromat (Preview)',
posterFileName: 'cosmosLaundromat.jpg', posterFileName: 'cosmosLaundromat.jpg',
torrentFileName: 'cosmosLaundromat.torrent' torrentFileName: 'cosmosLaundromat.torrent'
}, },
{ {
testID: 'sintel',
name: 'Sintel', name: 'Sintel',
posterFileName: 'sintel.jpg', posterFileName: 'sintel.jpg',
torrentFileName: 'sintel.torrent' torrentFileName: 'sintel.torrent'
}, },
{ {
testID: 'tears',
name: 'Tears of Steel', name: 'Tears of Steel',
posterFileName: 'tearsOfSteel.jpg', posterFileName: 'tearsOfSteel.jpg',
torrentFileName: 'tearsOfSteel.torrent' torrentFileName: 'tearsOfSteel.torrent'
}, },
{ {
name: 'The WIRED CD - Rip. Sample. Mash. Share.', testID: 'wired',
name: 'The WIRED CD - Rip. Sample. Mash. Share',
posterFileName: 'wiredCd.jpg', posterFileName: 'wiredCd.jpg',
torrentFileName: 'wiredCd.torrent' torrentFileName: 'wiredCd.torrent'
} }
@@ -62,8 +76,11 @@ module.exports = {
HOME_PAGE_URL: 'https://webtorrent.io', HOME_PAGE_URL: 'https://webtorrent.io',
IS_PORTABLE: isPortable(), IS_PORTABLE: IS_PORTABLE,
IS_PRODUCTION: isProduction(), IS_PRODUCTION: IS_PRODUCTION,
IS_TEST: IS_TEST,
OS_SYSARCH: arch() === 'x64' ? 'x64' : 'ia32',
POSTER_PATH: path.join(getConfigPath(), 'Posters'), POSTER_PATH: path.join(getConfigPath(), 'Posters'),
ROOT_PATH: path.join(__dirname, '..'), ROOT_PATH: path.join(__dirname, '..'),
@@ -74,12 +91,19 @@ module.exports = {
WINDOW_MAIN: 'file://' + path.join(__dirname, '..', 'static', 'main.html'), WINDOW_MAIN: 'file://' + path.join(__dirname, '..', 'static', 'main.html'),
WINDOW_WEBTORRENT: 'file://' + path.join(__dirname, '..', 'static', 'webtorrent.html'), WINDOW_WEBTORRENT: 'file://' + path.join(__dirname, '..', 'static', 'webtorrent.html'),
WINDOW_MIN_HEIGHT: 38 + (120 * 2), // header height + 2 torrents WINDOW_INITIAL_BOUNDS: {
WINDOW_MIN_WIDTH: 425 width: 500,
height: UI_HEADER_HEIGHT + (UI_TORRENT_HEIGHT * 6) // header + 6 torrents
},
WINDOW_MIN_HEIGHT: UI_HEADER_HEIGHT + (UI_TORRENT_HEIGHT * 2), // header + 2 torrents
WINDOW_MIN_WIDTH: 425,
UI_HEADER_HEIGHT: UI_HEADER_HEIGHT,
UI_TORRENT_HEIGHT: UI_TORRENT_HEIGHT
} }
function getConfigPath () { function getConfigPath () {
if (isPortable()) { if (IS_PORTABLE) {
return PORTABLE_PATH return PORTABLE_PATH
} else { } else {
return path.dirname(appConfig.filePath) return path.dirname(appConfig.filePath)
@@ -87,24 +111,47 @@ function getConfigPath () {
} }
function getDefaultDownloadPath () { function getDefaultDownloadPath () {
if (!process || !process.type) { if (IS_PORTABLE) {
return ''
}
if (isPortable()) {
return path.join(getConfigPath(), 'Downloads') return path.join(getConfigPath(), 'Downloads')
} else {
return getPath('downloads')
} }
}
const electron = require('electron') function getPath (key) {
if (!process.versions.electron) {
// Node.js process
return ''
} else if (process.type === 'renderer') {
// Electron renderer process
return electron.remote.app.getPath(key)
} else {
// Electron main process
return electron.app.getPath(key)
}
}
return process.type === 'renderer' function isTest () {
? electron.remote.app.getPath('downloads') return process.env.NODE_ENV === 'test'
: electron.app.getPath('downloads')
} }
function isPortable () { function isPortable () {
if (IS_TEST) {
return true
}
if (process.platform !== 'win32' || !IS_PRODUCTION) {
// Fast path: Non-Windows platforms should not check for path on disk
return false
}
const fs = require('fs')
try { try {
return process.platform === 'win32' && isProduction() && !!fs.statSync(PORTABLE_PATH) // This line throws if the "Portable Settings" folder does not exist, and does
// nothing otherwise.
fs.accessSync(PORTABLE_PATH, fs.constants.R_OK | fs.constants.W_OK)
return true
} catch (err) { } catch (err) {
return false return false
} }
@@ -112,6 +159,7 @@ function isPortable () {
function isProduction () { function isProduction () {
if (!process.versions.electron) { if (!process.versions.electron) {
// Node.js process
return false return false
} }
if (process.platform === 'darwin') { if (process.platform === 'darwin') {

View File

@@ -2,10 +2,10 @@ module.exports = {
init init
} }
const config = require('./config')
const electron = require('electron')
function init () { function init () {
const config = require('./config')
const electron = require('electron')
electron.crashReporter.start({ electron.crashReporter.start({
companyName: config.APP_NAME, companyName: config.APP_NAME,
productName: config.APP_NAME, productName: config.APP_NAME,

View File

@@ -21,12 +21,7 @@ function openSeedFile () {
title: 'Select a file for the torrent.', title: 'Select a file for the torrent.',
properties: [ 'openFile' ] properties: [ 'openFile' ]
} }
setTitle(opts.title) showOpenSeed(opts)
electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
resetTitle()
if (!Array.isArray(selectedPaths)) return
windows.main.dispatch('showCreateTorrent', selectedPaths)
})
} }
/* /*
@@ -46,12 +41,7 @@ function openSeedDirectory () {
title: 'Select a folder for the torrent.', title: 'Select a folder for the torrent.',
properties: [ 'openDirectory' ] properties: [ 'openDirectory' ]
} }
setTitle(opts.title) showOpenSeed(opts)
electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
resetTitle()
if (!Array.isArray(selectedPaths)) return
windows.main.dispatch('showCreateTorrent', selectedPaths)
})
} }
/* /*
@@ -119,3 +109,16 @@ function setTitle (title) {
function resetTitle () { function resetTitle () {
windows.main.dispatch('resetTitle') windows.main.dispatch('resetTitle')
} }
/**
* Pops up an Open File dialog with the given options.
* After the user selects files / folders, shows the Create Torrent page.
*/
function showOpenSeed (opts) {
setTitle(opts.title)
electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
resetTitle()
if (!Array.isArray(selectedPaths)) return
windows.main.dispatch('showCreateTorrent', selectedPaths)
})
}

View File

@@ -5,6 +5,7 @@ module.exports = {
} }
const cp = require('child_process') const cp = require('child_process')
const path = require('path')
const vlcCommand = require('vlc-command') const vlcCommand = require('vlc-command')
const log = require('./log') const log = require('./log')
@@ -13,15 +14,15 @@ const windows = require('./windows')
// holds a ChildProcess while we're playing a video in an external player, null otherwise // holds a ChildProcess while we're playing a video in an external player, null otherwise
let proc = null let proc = null
function checkInstall (path, cb) { function checkInstall (playerPath, cb) {
// check for VLC if external player has not been specified by the user // check for VLC if external player has not been specified by the user
// otherwise assume the player is installed // otherwise assume the player is installed
if (path == null) return vlcCommand((err) => cb(!err)) if (playerPath == null) return vlcCommand((err) => cb(!err))
process.nextTick(() => cb(true)) process.nextTick(() => cb(true))
} }
function spawn (path, url, title) { function spawn (playerPath, url, title) {
if (path != null) return spawnExternal(path, [url]) if (playerPath != null) return spawnExternal(playerPath, [url])
// Try to find and use VLC if external player is not specified // Try to find and use VLC if external player is not specified
vlcCommand(function (err, vlcPath) { vlcCommand(function (err, vlcPath) {
@@ -44,10 +45,15 @@ function kill () {
proc = null proc = null
} }
function spawnExternal (path, args) { function spawnExternal (playerPath, args) {
log('Running external media player:', path + ' ' + args.join(' ')) log('Running external media player:', playerPath + ' ' + args.join(' '))
proc = cp.spawn(path, args, {stdio: 'ignore'}) if (process.platform === 'darwin' && path.extname(playerPath) === '.app') {
// Mac: Use executable in packaged .app bundle
playerPath += '/Contents/MacOS/' + path.basename(playerPath, '.app')
}
proc = cp.spawn(playerPath, args, {stdio: 'ignore'})
// If it works, close the modal after a second // If it works, close the modal after a second
const closeModalTimeout = setTimeout(() => const closeModalTimeout = setTimeout(() =>

View File

@@ -273,7 +273,7 @@ function commandToArgs (command) {
} }
function installLinux () { function installLinux () {
const fs = require('fs-extra') const fs = require('fs')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
@@ -326,6 +326,8 @@ function installLinux () {
function writeIconFile (err, iconFile) { function writeIconFile (err, iconFile) {
if (err) return log.error(err.message) if (err) return log.error(err.message)
const mkdirp = require('mkdirp')
const iconFilePath = path.join( const iconFilePath = path.join(
os.homedir(), os.homedir(),
'.local', '.local',
@@ -333,9 +335,11 @@ function installLinux () {
'icons', 'icons',
'webtorrent-desktop.png' 'webtorrent-desktop.png'
) )
fs.mkdirp(path.dirname(iconFilePath)) mkdirp(path.dirname(iconFilePath), (err) => {
fs.writeFile(iconFilePath, iconFile, function (err) {
if (err) return log.error(err.message) if (err) return log.error(err.message)
fs.writeFile(iconFilePath, iconFile, (err) => {
if (err) log.error(err.message)
})
}) })
} }
} }
@@ -343,7 +347,7 @@ function installLinux () {
function uninstallLinux () { function uninstallLinux () {
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const fs = require('fs-extra') const rimraf = require('rimraf')
const desktopFilePath = path.join( const desktopFilePath = path.join(
os.homedir(), os.homedir(),
@@ -352,7 +356,7 @@ function uninstallLinux () {
'applications', 'applications',
'webtorrent-desktop.desktop' 'webtorrent-desktop.desktop'
) )
fs.removeSync(desktopFilePath) rimraf(desktopFilePath)
const iconFilePath = path.join( const iconFilePath = path.join(
os.homedir(), os.homedir(),
@@ -361,5 +365,5 @@ function uninstallLinux () {
'icons', 'icons',
'webtorrent-desktop.png' 'webtorrent-desktop.png'
) )
fs.removeSync(iconFilePath) rimraf(iconFilePath)
} }

View File

@@ -1,27 +1,26 @@
console.time('init') console.time('init')
const electron = require('electron') const electron = require('electron')
const app = electron.app const app = electron.app
const ipcMain = electron.ipcMain
const announcement = require('./announcement') const parallel = require('run-parallel')
const config = require('../config') const config = require('../config')
const crashReporter = require('../crash-reporter') const crashReporter = require('../crash-reporter')
const dialog = require('./dialog')
const dock = require('./dock')
const ipc = require('./ipc') const ipc = require('./ipc')
const log = require('./log') const log = require('./log')
const menu = require('./menu') const menu = require('./menu')
const squirrelWin32 = require('./squirrel-win32') const State = require('../renderer/lib/state')
const tray = require('./tray')
const updater = require('./updater')
const userTasks = require('./user-tasks')
const windows = require('./windows') const windows = require('./windows')
let shouldQuit = false let shouldQuit = false
let argv = sliceArgv(process.argv) let argv = sliceArgv(process.argv)
// Start the app without showing the main window when auto launching on login
// (On Windows and Linux, we get a flag. On MacOS, we get special API.)
const hidden = argv.includes('--hidden') ||
(process.platform === 'darwin' && app.getLoginItemSettings().wasOpenedAsHidden)
if (config.IS_PRODUCTION) { if (config.IS_PRODUCTION) {
// When Electron is running in production mode (packaged app), then run React // When Electron is running in production mode (packaged app), then run React
// in production mode too. // in production mode too.
@@ -29,13 +28,16 @@ if (config.IS_PRODUCTION) {
} }
if (process.platform === 'win32') { if (process.platform === 'win32') {
const squirrelWin32 = require('./squirrel-win32')
shouldQuit = squirrelWin32.handleEvent(argv[0]) shouldQuit = squirrelWin32.handleEvent(argv[0])
argv = argv.filter((arg) => !arg.includes('--squirrel')) argv = argv.filter((arg) => !arg.includes('--squirrel'))
} }
if (!shouldQuit) { if (!shouldQuit && !config.IS_PORTABLE) {
// Prevent multiple instances of app from running at same time. New instances // Prevent multiple instances of app from running at same time. New instances
// signal this instance and quit. // signal this instance and quit. Note: This feature creates a lock file in
// %APPDATA%\Roaming\WebTorrent so we do not do it for the Portable App since
// we want to be "silent" as well as "portable".
shouldQuit = app.makeSingleInstance(onAppOpen) shouldQuit = app.makeSingleInstance(onAppOpen)
if (shouldQuit) { if (shouldQuit) {
app.quit() app.quit()
@@ -48,27 +50,30 @@ if (!shouldQuit) {
function init () { function init () {
if (config.IS_PORTABLE) { if (config.IS_PORTABLE) {
const path = require('path')
// Put all user data into the "Portable Settings" folder
app.setPath('userData', config.CONFIG_PATH) app.setPath('userData', config.CONFIG_PATH)
// Put Electron crash files, etc. into the "Portable Settings\Temp" folder
app.setPath('temp', path.join(config.CONFIG_PATH, 'Temp'))
} }
const ipcMain = electron.ipcMain
let isReady = false // app ready, windows can be created let isReady = false // app ready, windows can be created
app.ipcReady = false // main window has finished loading and IPC is ready app.ipcReady = false // main window has finished loading and IPC is ready
app.isQuitting = false app.isQuitting = false
// Open handlers must be added as early as possible parallel({
app.on('open-file', onOpen) appReady: (cb) => app.on('ready', () => cb(null)),
app.on('open-url', onOpen) state: (cb) => State.load(cb)
}, onReady)
ipc.init() function onReady (err, results) {
if (err) throw err
app.once('will-finish-launching', function () {
crashReporter.init()
})
app.on('ready', function () {
isReady = true isReady = true
windows.main.init() windows.main.init(results.state, {hidden: hidden})
windows.webtorrent.init() windows.webtorrent.init()
menu.init() menu.init()
@@ -81,6 +86,15 @@ function init () {
const error = {message: err.message, stack: err.stack} const error = {message: err.message, stack: err.stack}
windows.main.dispatch('uncaughtError', 'main', error) windows.main.dispatch('uncaughtError', 'main', error)
}) })
}
app.on('open-file', onOpen)
app.on('open-url', onOpen)
ipc.init()
app.once('will-finish-launching', function () {
crashReporter.init()
}) })
app.once('ipcReady', function () { app.once('ipcReady', function () {
@@ -94,12 +108,12 @@ function init () {
app.isQuitting = true app.isQuitting = true
e.preventDefault() e.preventDefault()
windows.main.dispatch('saveState') // try to save state on exit windows.main.dispatch('stateSaveImmediate') // try to save state on exit
ipcMain.once('savedState', () => app.quit()) ipcMain.once('stateSaved', () => app.quit())
setTimeout(() => { setTimeout(() => {
console.error('Saving state took too long. Quitting.') console.error('Saving state took too long. Quitting.')
app.quit() app.quit()
}, 2000) // quit after 2 secs, at most }, 4000) // quit after 4 secs, at most
}) })
app.on('activate', function () { app.on('activate', function () {
@@ -108,11 +122,25 @@ function init () {
} }
function delayedInit () { function delayedInit () {
if (app.isQuitting) return
const announcement = require('./announcement')
const dock = require('./dock')
const updater = require('./updater')
announcement.init() announcement.init()
dock.init() dock.init()
tray.init()
updater.init() updater.init()
userTasks.init()
if (process.platform === 'win32') {
const userTasks = require('./user-tasks')
userTasks.init()
}
if (process.platform !== 'darwin') {
const tray = require('./tray')
tray.init()
}
} }
function onOpen (e, torrentId) { function onOpen (e, torrentId) {
@@ -143,22 +171,38 @@ function onAppOpen (newArgv) {
} }
} }
// Remove leading args.
// Production: 1 arg, eg: /Applications/WebTorrent.app/Contents/MacOS/WebTorrent
// Development: 2 args, eg: electron .
// Test: 4 args, eg: electron -r .../mocks.js .
function sliceArgv (argv) { function sliceArgv (argv) {
return argv.slice(config.IS_PRODUCTION ? 1 : 2) return argv.slice(config.IS_PRODUCTION ? 1
: config.IS_TEST ? 4
: 2)
} }
function processArgv (argv) { function processArgv (argv) {
let torrentIds = [] let torrentIds = []
argv.forEach(function (arg) { argv.forEach(function (arg) {
if (arg === '-n') { if (arg === '-n' || arg === '-o' || arg === '-u') {
dialog.openSeedDirectory() // Critical path: Only load the 'dialog' package if it is needed
} else if (arg === '-o') { const dialog = require('./dialog')
dialog.openTorrentFile() if (arg === '-n') {
} else if (arg === '-u') { dialog.openSeedDirectory()
dialog.openTorrentAddress() } else if (arg === '-o') {
dialog.openTorrentFile()
} else if (arg === '-u') {
dialog.openTorrentAddress()
}
} else if (arg === '--hidden') {
// Ignore hidden argument, already being handled
} else if (arg.startsWith('-psn')) { } else if (arg.startsWith('-psn')) {
// Ignore Mac launchd "process serial number" argument // Ignore Mac launchd "process serial number" argument
// Issue: https://github.com/feross/webtorrent-desktop/issues/214 // Issue: https://github.com/feross/webtorrent-desktop/issues/214
} else if (arg.startsWith('--')) {
// Ignore Spectron flags
} else if (arg === 'data:,') {
// Ignore weird Spectron argument
} else if (arg !== '.') { } else if (arg !== '.') {
// Ignore '.' argument, which gets misinterpreted as a torrent id, when a // Ignore '.' argument, which gets misinterpreted as a torrent id, when a
// development copy of WebTorrent is started while a production version is // development copy of WebTorrent is started while a production version is

View File

@@ -6,17 +6,9 @@ const electron = require('electron')
const app = electron.app const app = electron.app
const dialog = require('./dialog')
const dock = require('./dock')
const handlers = require('./handlers')
const log = require('./log') const log = require('./log')
const menu = require('./menu') const menu = require('./menu')
const powerSaveBlocker = require('./power-save-blocker')
const shell = require('./shell')
const shortcuts = require('./shortcuts')
const externalPlayer = require('./external-player')
const windows = require('./windows') const windows = require('./windows')
const thumbar = require('./thumbar')
// Messages from the main process, to be sent once the WebTorrent process starts // Messages from the main process, to be sent once the WebTorrent process starts
const messageQueueMainToWebTorrent = [] const messageQueueMainToWebTorrent = []
@@ -43,45 +35,73 @@ function init () {
* Dialog * Dialog
*/ */
ipc.on('openTorrentFile', () => dialog.openTorrentFile()) ipc.on('openTorrentFile', () => {
ipc.on('openFiles', () => dialog.openFiles()) const dialog = require('./dialog')
dialog.openTorrentFile()
})
ipc.on('openFiles', () => {
const dialog = require('./dialog')
dialog.openFiles()
})
/** /**
* Dock * Dock
*/ */
ipc.on('setBadge', (e, ...args) => dock.setBadge(...args)) ipc.on('setBadge', (e, ...args) => {
ipc.on('downloadFinished', (e, ...args) => dock.downloadFinished(...args)) const dock = require('./dock')
dock.setBadge(...args)
})
ipc.on('downloadFinished', (e, ...args) => {
const dock = require('./dock')
dock.downloadFinished(...args)
})
/** /**
* Events * Events
*/ */
ipc.on('onPlayerOpen', function () { ipc.on('onPlayerOpen', function () {
menu.setPlayerOpen(true) const powerSaveBlocker = require('./power-save-blocker')
const shortcuts = require('./shortcuts')
const thumbar = require('./thumbar')
menu.togglePlaybackControls(true)
powerSaveBlocker.enable() powerSaveBlocker.enable()
shortcuts.enable() shortcuts.enable()
thumbar.enable() thumbar.enable()
}) })
ipc.on('onPlayerUpdate', function (e, ...args) { ipc.on('onPlayerUpdate', function (e, ...args) {
const thumbar = require('./thumbar')
menu.onPlayerUpdate(...args) menu.onPlayerUpdate(...args)
thumbar.onPlayerUpdate(...args) thumbar.onPlayerUpdate(...args)
}) })
ipc.on('onPlayerClose', function () { ipc.on('onPlayerClose', function () {
menu.setPlayerOpen(false) const powerSaveBlocker = require('./power-save-blocker')
const shortcuts = require('./shortcuts')
const thumbar = require('./thumbar')
menu.togglePlaybackControls(false)
powerSaveBlocker.disable() powerSaveBlocker.disable()
shortcuts.disable() shortcuts.disable()
thumbar.disable() thumbar.disable()
}) })
ipc.on('onPlayerPlay', function () { ipc.on('onPlayerPlay', function () {
const powerSaveBlocker = require('./power-save-blocker')
const thumbar = require('./thumbar')
powerSaveBlocker.enable() powerSaveBlocker.enable()
thumbar.onPlayerPlay() thumbar.onPlayerPlay()
}) })
ipc.on('onPlayerPause', function () { ipc.on('onPlayerPause', function () {
const powerSaveBlocker = require('./power-save-blocker')
const thumbar = require('./thumbar')
powerSaveBlocker.disable() powerSaveBlocker.disable()
thumbar.onPlayerPause() thumbar.onPlayerPause()
}) })
@@ -90,18 +110,41 @@ function init () {
* Shell * Shell
*/ */
ipc.on('openItem', (e, ...args) => shell.openItem(...args)) ipc.on('openItem', (e, ...args) => {
ipc.on('showItemInFolder', (e, ...args) => shell.showItemInFolder(...args)) const shell = require('./shell')
ipc.on('moveItemToTrash', (e, ...args) => shell.moveItemToTrash(...args)) shell.openItem(...args)
})
ipc.on('showItemInFolder', (e, ...args) => {
const shell = require('./shell')
shell.showItemInFolder(...args)
})
ipc.on('moveItemToTrash', (e, ...args) => {
const shell = require('./shell')
shell.moveItemToTrash(...args)
})
/** /**
* File handlers * File handlers
*/ */
ipc.on('setDefaultFileHandler', (e, flag) => { ipc.on('setDefaultFileHandler', (e, flag) => {
const handlers = require('./handlers')
if (flag) handlers.install() if (flag) handlers.install()
else handlers.uninstall() else handlers.uninstall()
}) })
/**
* Auto start on login
*/
ipc.on('setStartup', (e, flag) => {
const startup = require('./startup')
if (flag) startup.install()
else startup.uninstall()
})
/** /**
* Windows: Main * Windows: Main
*/ */
@@ -121,15 +164,31 @@ function init () {
*/ */
ipc.on('checkForExternalPlayer', function (e, path) { ipc.on('checkForExternalPlayer', function (e, path) {
const externalPlayer = require('./external-player')
externalPlayer.checkInstall(path, function (isInstalled) { externalPlayer.checkInstall(path, function (isInstalled) {
windows.main.send('checkForExternalPlayer', isInstalled) windows.main.send('checkForExternalPlayer', isInstalled)
}) })
}) })
ipc.on('openExternalPlayer', (e, ...args) => externalPlayer.spawn(...args)) ipc.on('openExternalPlayer', (e, ...args) => {
ipc.on('quitExternalPlayer', () => externalPlayer.kill()) const externalPlayer = require('./external-player')
const thumbar = require('./thumbar')
menu.togglePlaybackControls(false)
thumbar.disable()
externalPlayer.spawn(...args)
})
ipc.on('quitExternalPlayer', () => {
const externalPlayer = require('./external-player')
externalPlayer.kill()
})
/**
* Message passing
*/
// Capture all events
const oldEmit = ipc.emit const oldEmit = ipc.emit
ipc.emit = function (name, e, ...args) { ipc.emit = function (name, e, ...args) {
// Relay messages between the main window and the WebTorrent hidden window // Relay messages between the main window and the WebTorrent hidden window

View File

@@ -1,6 +1,6 @@
module.exports = { module.exports = {
init, init,
setPlayerOpen, togglePlaybackControls,
setWindowFocus, setWindowFocus,
setAllowNav, setAllowNav,
onPlayerUpdate, onPlayerUpdate,
@@ -13,8 +13,6 @@ const electron = require('electron')
const app = electron.app const app = electron.app
const config = require('../config') const config = require('../config')
const dialog = require('./dialog')
const shell = require('./shell')
const windows = require('./windows') const windows = require('./windows')
let menu = null let menu = null
@@ -24,7 +22,7 @@ function init () {
electron.Menu.setApplicationMenu(menu) electron.Menu.setApplicationMenu(menu)
} }
function setPlayerOpen (flag) { function togglePlaybackControls (flag) {
getMenuItem('Play/Pause').enabled = flag getMenuItem('Play/Pause').enabled = flag
getMenuItem('Skip Next').enabled = flag getMenuItem('Skip Next').enabled = flag
getMenuItem('Skip Previous').enabled = flag getMenuItem('Skip Previous').enabled = flag
@@ -90,17 +88,26 @@ function getMenuTemplate () {
? 'Create New Torrent...' ? 'Create New Torrent...'
: 'Create New Torrent from Folder...', : 'Create New Torrent from Folder...',
accelerator: 'CmdOrCtrl+N', accelerator: 'CmdOrCtrl+N',
click: () => dialog.openSeedDirectory() click: () => {
const dialog = require('./dialog')
dialog.openSeedDirectory()
}
}, },
{ {
label: 'Open Torrent File...', label: 'Open Torrent File...',
accelerator: 'CmdOrCtrl+O', accelerator: 'CmdOrCtrl+O',
click: () => dialog.openTorrentFile() click: () => {
const dialog = require('./dialog')
dialog.openTorrentFile()
}
}, },
{ {
label: 'Open Torrent Address...', label: 'Open Torrent Address...',
accelerator: 'CmdOrCtrl+U', accelerator: 'CmdOrCtrl+U',
click: () => dialog.openTorrentAddress() click: () => {
const dialog = require('./dialog')
dialog.openTorrentAddress()
}
}, },
{ {
type: 'separator' type: 'separator'
@@ -277,18 +284,27 @@ function getMenuTemplate () {
submenu: [ submenu: [
{ {
label: 'Learn more about ' + config.APP_NAME, label: 'Learn more about ' + config.APP_NAME,
click: () => shell.openExternal(config.HOME_PAGE_URL) click: () => {
const shell = require('./shell')
shell.openExternal(config.HOME_PAGE_URL)
}
}, },
{ {
label: 'Contribute on GitHub', label: 'Contribute on GitHub',
click: () => shell.openExternal(config.GITHUB_URL) click: () => {
const shell = require('./shell')
shell.openExternal(config.GITHUB_URL)
}
}, },
{ {
type: 'separator' type: 'separator'
}, },
{ {
label: 'Report an Issue...', label: 'Report an Issue...',
click: () => shell.openExternal(config.GITHUB_URL_ISSUES) click: () => {
const shell = require('./shell')
shell.openExternal(config.GITHUB_URL_ISSUES)
}
} }
] ]
} }
@@ -361,7 +377,10 @@ function getMenuTemplate () {
// File menu (Windows, Linux) // File menu (Windows, Linux)
template[0].submenu.unshift({ template[0].submenu.unshift({
label: 'Create New Torrent from File...', label: 'Create New Torrent from File...',
click: () => dialog.openSeedFile() click: () => {
const dialog = require('./dialog')
dialog.openSeedFile()
}
}) })
// Edit menu (Windows, Linux) // Edit menu (Windows, Linux)

36
src/main/startup.js Normal file
View File

@@ -0,0 +1,36 @@
module.exports = {
install,
uninstall
}
const config = require('../config')
const AutoLaunch = require('auto-launch')
const { app } = require('electron')
// On Mac, work around a bug in auto-launch where it opens a Terminal window
// See https://github.com/Teamwork/node-auto-launch/issues/28#issuecomment-222194437
const appPath = process.platform === 'darwin'
? app.getPath('exe').replace(/\.app\/Content.*/, '.app')
: undefined // Use the default
const appLauncher = new AutoLaunch({
name: config.APP_NAME,
path: appPath,
isHidden: true
})
function install () {
return appLauncher
.isEnabled()
.then(enabled => {
if (!enabled) return appLauncher.enable()
})
}
function uninstall () {
return appLauncher
.isEnabled()
.then(enabled => {
if (enabled) return appLauncher.disable()
})
}

View File

@@ -11,7 +11,8 @@ const windows = require('./windows')
const AUTO_UPDATE_URL = config.AUTO_UPDATE_URL + const AUTO_UPDATE_URL = config.AUTO_UPDATE_URL +
'?version=' + config.APP_VERSION + '?version=' + config.APP_VERSION +
'&platform=' + process.platform '&platform=' + process.platform +
'&sysarch=' + config.OS_SYSARCH
function init () { function init () {
if (process.platform === 'linux') { if (process.platform === 'linux') {

View File

@@ -32,7 +32,7 @@ function init () {
// No menu on the About window // No menu on the About window
win.setMenu(null) win.setMenu(null)
win.webContents.once('did-finish-load', function () { win.once('ready-to-show', function () {
win.show() win.show()
}) })

View File

@@ -15,21 +15,21 @@ const main = module.exports = {
} }
const electron = require('electron') const electron = require('electron')
const debounce = require('debounce')
const app = electron.app const app = electron.app
const config = require('../../config') const config = require('../../config')
const log = require('../log') const log = require('../log')
const menu = require('../menu') const menu = require('../menu')
const tray = require('../tray')
const HEADER_HEIGHT = 38 function init (state, options) {
const TORRENT_HEIGHT = 100
function init () {
if (main.win) { if (main.win) {
return main.win.show() return main.win.show()
} }
const initialBounds = Object.assign(config.WINDOW_INITIAL_BOUNDS, state.saved.bounds)
const win = main.win = new electron.BrowserWindow({ const win = main.win = new electron.BrowserWindow({
backgroundColor: '#282828', backgroundColor: '#282828',
darkTheme: true, // Forces dark theme (GTK+3) darkTheme: true, // Forces dark theme (GTK+3)
@@ -39,18 +39,33 @@ function init () {
title: config.APP_WINDOW_TITLE, title: config.APP_WINDOW_TITLE,
titleBarStyle: 'hidden-inset', // Hide title bar (Mac) titleBarStyle: 'hidden-inset', // Hide title bar (Mac)
useContentSize: true, // Specify web page size without OS chrome useContentSize: true, // Specify web page size without OS chrome
width: 500, show: false,
height: HEADER_HEIGHT + (TORRENT_HEIGHT * 6) // header height + 5 torrents width: initialBounds.width,
height: initialBounds.height,
x: initialBounds.x,
y: initialBounds.y
}) })
win.loadURL(config.WINDOW_MAIN) win.loadURL(config.WINDOW_MAIN)
if (win.setSheetOffset) win.setSheetOffset(HEADER_HEIGHT) win.once('ready-to-show', () => {
if (!options.hidden) win.show()
})
if (win.setSheetOffset) {
win.setSheetOffset(config.UI_HEADER_HEIGHT)
}
win.webContents.on('dom-ready', function () { win.webContents.on('dom-ready', function () {
menu.onToggleFullScreen(main.win.isFullScreen()) menu.onToggleFullScreen(main.win.isFullScreen())
}) })
win.webContents.on('will-navigate', (e, url) => {
// Prevent drag-and-drop from navigating the Electron window, which can happen
// before our drag-and-drop handlers have been initialized.
e.preventDefault()
})
win.on('blur', onWindowBlur) win.on('blur', onWindowBlur)
win.on('focus', onWindowFocus) win.on('focus', onWindowFocus)
@@ -69,10 +84,23 @@ function init () {
win.setMenuBarVisibility(true) win.setMenuBarVisibility(true)
}) })
win.on('move', debounce(function (e) {
send('windowBoundsChanged', e.sender.getBounds())
}, 1000))
win.on('resize', debounce(function (e) {
send('windowBoundsChanged', e.sender.getBounds())
}, 1000))
win.on('close', function (e) { win.on('close', function (e) {
if (process.platform !== 'darwin' && !tray.hasTray()) { if (process.platform !== 'darwin') {
app.quit() const tray = require('../tray')
} else if (!app.isQuitting) { if (!tray.hasTray()) {
app.quit()
return
}
}
if (!app.isQuitting) {
e.preventDefault() e.preventDefault()
hide() hide()
} }
@@ -85,7 +113,7 @@ function dispatch (...args) {
function hide () { function hide () {
if (!main.win) return if (!main.win) return
main.win.send('dispatch', 'backToList') dispatch('backToList')
main.win.hide() main.win.hide()
} }
@@ -211,12 +239,20 @@ function toggleFullScreen (flag) {
function onWindowBlur () { function onWindowBlur () {
menu.setWindowFocus(false) menu.setWindowFocus(false)
tray.setWindowFocus(false)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(false)
}
} }
function onWindowFocus () { function onWindowFocus () {
menu.setWindowFocus(true) menu.setWindowFocus(true)
tray.setWindowFocus(true)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(true)
}
} }
function getIconPath () { function getIconPath () {

View File

@@ -9,7 +9,6 @@ const webtorrent = module.exports = {
const electron = require('electron') const electron = require('electron')
const config = require('../../config') const config = require('../../config')
const log = require('../log')
function init () { function init () {
const win = webtorrent.win = new electron.BrowserWindow({ const win = webtorrent.win = new electron.BrowserWindow({
@@ -52,7 +51,6 @@ function send (...args) {
function toggleDevTools () { function toggleDevTools () {
if (!webtorrent.win) return if (!webtorrent.win) return
log('toggleDevTools')
if (webtorrent.win.webContents.isDevToolsOpened()) { if (webtorrent.win.webContents.isDevToolsOpened()) {
webtorrent.win.webContents.closeDevTools() webtorrent.win.webContents.closeDevTools()
webtorrent.win.hide() webtorrent.win.hide()

View File

@@ -6,7 +6,10 @@ class Header extends React.Component {
render () { render () {
const loc = this.props.state.location const loc = this.props.state.location
return ( return (
<div className='header'> <div className='header'
onMouseMove={dispatcher('mediaMouseMoved')}
onMouseEnter={dispatcher('mediaControlsMouseEnter')}
onMouseLeave={dispatcher('mediaControlsMouseLeave')}>
{this.getTitle()} {this.getTitle()}
<div className='nav left float-left'> <div className='nav left float-left'>
<i <i

View File

@@ -9,12 +9,12 @@ module.exports = class ModalOKCancel extends React.Component {
return ( return (
<div className='float-right'> <div className='float-right'>
<FlatButton <FlatButton
className='control' className='control cancel'
style={cancelStyle} style={cancelStyle}
label={cancelText} label={cancelText}
onClick={onCancel} /> onClick={onCancel} />
<RaisedButton <RaisedButton
className='control' className='control ok'
primary primary
label={okText} label={okText}
onClick={onOK} /> onClick={onOK} />

View File

@@ -11,6 +11,7 @@ module.exports = class OpenTorrentAddressModal extends React.Component {
<p><label>Enter torrent address or magnet link</label></p> <p><label>Enter torrent address or magnet link</label></p>
<div> <div>
<TextField <TextField
id='torrent-address-field'
className='control' className='control'
ref={(c) => { this.torrentURL = c }} ref={(c) => { this.torrentURL = c }}
fullWidth fullWidth
@@ -31,7 +32,7 @@ module.exports = class OpenTorrentAddressModal extends React.Component {
} }
function handleKeyDown (e) { function handleKeyDown (e) {
if (e.which === 13) this.handleOK() /* hit Enter to submit */ if (e.which === 13) handleOK.call(this) /* hit Enter to submit */
} }
function handleOK () { function handleOK () {

View File

@@ -1,6 +1,6 @@
const React = require('react') const React = require('react')
const FlatButton = require('material-ui/FlatButton').default const RaisedButton = require('material-ui/RaisedButton').default
class ShowMore extends React.Component { class ShowMore extends React.Component {
static get propTypes () { static get propTypes () {
@@ -39,9 +39,10 @@ class ShowMore extends React.Component {
? this.props.hideLabel ? this.props.hideLabel
: this.props.showLabel : this.props.showLabel
return ( return (
<div style={this.props.style}> <div className='show-more' style={this.props.style}>
{this.state.expanded ? this.props.children : null} {this.state.expanded ? this.props.children : null}
<FlatButton <RaisedButton
className='control'
onClick={this.handleClick} onClick={this.handleClick}
label={label} /> label={label} />
</div> </div>

View File

@@ -1,6 +1,5 @@
const React = require('react') const React = require('react')
const electron = require('electron') const electron = require('electron')
const path = require('path')
const ModalOKCancel = require('./modal-ok-cancel') const ModalOKCancel = require('./modal-ok-cancel')
const {dispatcher} = require('../lib/dispatcher') const {dispatcher} = require('../lib/dispatcher')
@@ -12,15 +11,11 @@ module.exports = class UnsupportedMediaModal extends React.Component {
const message = (err && err.getMessage) const message = (err && err.getMessage)
? err.getMessage() ? err.getMessage()
: err : err
const playerPath = state.saved.prefs.externalPlayerPath
const playerName = playerPath
? path.basename(playerPath).split('.')[0]
: 'VLC'
const onAction = state.modal.externalPlayerInstalled const onAction = state.modal.externalPlayerInstalled
? dispatcher('openExternalPlayer') ? dispatcher('openExternalPlayer')
: () => this.onInstall() : () => this.onInstall()
const actionText = state.modal.externalPlayerInstalled const actionText = state.modal.externalPlayerInstalled
? 'PLAY IN ' + playerName.toUpperCase() ? 'PLAY IN ' + state.getExternalPlayerName().toUpperCase()
: 'INSTALL VLC' : 'INSTALL VLC'
const errorMessage = state.modal.externalPlayerNotFound const errorMessage = state.modal.externalPlayerNotFound
? 'Couldn\'t run external player. Please make sure it\'s installed.' ? 'Couldn\'t run external player. Please make sure it\'s installed.'

View File

@@ -44,14 +44,30 @@ module.exports = class MediaController {
this.state.playing.mouseStationarySince = new Date().getTime() this.state.playing.mouseStationarySince = new Date().getTime()
} }
controlsMouseEnter () {
this.state.playing.mouseInControls = true
this.state.playing.mouseStationarySince = new Date().getTime()
}
controlsMouseLeave () {
this.state.playing.mouseInControls = false
this.state.playing.mouseStationarySince = new Date().getTime()
}
openExternalPlayer () { openExternalPlayer () {
const state = this.state const state = this.state
const mediaURL = Playlist.getCurrentLocalURL(this.state)
ipcRenderer.send('openExternalPlayer',
state.saved.prefs.externalPlayerPath,
mediaURL,
state.window.title)
state.playing.location = 'external' state.playing.location = 'external'
let open = function () {
const mediaURL = Playlist.getCurrentLocalURL(state)
ipcRenderer.send('openExternalPlayer',
state.saved.prefs.externalPlayerPath,
mediaURL,
state.window.title)
}
if (state.server != null) open()
else ipcRenderer.once('wt-server-running', open)
} }
externalPlayerNotFound () { externalPlayerNotFound () {

View File

@@ -4,7 +4,7 @@ const path = require('path')
const Cast = require('../lib/cast') const Cast = require('../lib/cast')
const {dispatch} = require('../lib/dispatcher') const {dispatch} = require('../lib/dispatcher')
const telemetry = require('../lib/telemetry') const telemetry = require('../lib/telemetry')
const errors = require('../lib/errors') const {UnplayableFileError, UnplayableTorrentError} = require('../lib/errors')
const sound = require('../lib/sound') const sound = require('../lib/sound')
const TorrentPlayer = require('../lib/torrent-player') const TorrentPlayer = require('../lib/torrent-player')
const TorrentSummary = require('../lib/torrent-summary') const TorrentSummary = require('../lib/torrent-summary')
@@ -42,7 +42,7 @@ module.exports = class PlaybackController {
if (index === undefined || initialized) index = torrentSummary.mostRecentFileIndex if (index === undefined || initialized) index = torrentSummary.mostRecentFileIndex
if (index === undefined) index = torrentSummary.files.findIndex(TorrentPlayer.isPlayable) if (index === undefined) index = torrentSummary.files.findIndex(TorrentPlayer.isPlayable)
if (index === undefined) return cb(new errors.UnplayableError()) if (index === undefined) return cb(new UnplayableTorrentError())
initialized = true initialized = true
@@ -87,7 +87,7 @@ module.exports = class PlaybackController {
// Play next file in list (if any) // Play next file in list (if any)
nextTrack () { nextTrack () {
const state = this.state const state = this.state
if (Playlist.hasNext(state)) { if (Playlist.hasNext(state) && state.playing.location !== 'external') {
this.updatePlayer( this.updatePlayer(
state.playing.infoHash, Playlist.getNextIndex(state), false, (err) => { state.playing.infoHash, Playlist.getNextIndex(state), false, (err) => {
if (err) dispatch('error', err) if (err) dispatch('error', err)
@@ -99,7 +99,7 @@ module.exports = class PlaybackController {
// Play previous track in list (if any) // Play previous track in list (if any)
previousTrack () { previousTrack () {
const state = this.state const state = this.state
if (Playlist.hasPrevious(state)) { if (Playlist.hasPrevious(state) && state.playing.location !== 'external') {
this.updatePlayer( this.updatePlayer(
state.playing.infoHash, Playlist.getPreviousIndex(state), false, (err) => { state.playing.infoHash, Playlist.getPreviousIndex(state), false, (err) => {
if (err) dispatch('error', err) if (err) dispatch('error', err)
@@ -152,26 +152,21 @@ module.exports = class PlaybackController {
changePlaybackRate (direction) { changePlaybackRate (direction) {
const state = this.state const state = this.state
let rate = state.playing.playbackRate let rate = state.playing.playbackRate
if (direction > 0 && rate >= 0.25 && rate < 2) { if (direction > 0 && rate < 2) {
rate += 0.25 rate += 0.25
} else if (direction < 0 && rate > 0.25 && rate <= 2) { } else if (direction < 0 && rate > 0.25 && rate <= 2) {
rate -= 0.25 rate -= 0.25
} else if (direction < 0 && rate === 0.25) { } else if (direction > 0 && rate >= 1 && rate < 16) {
// When we set playback rate at 0 in html 5, playback hangs ;(
rate = -1
} else if (direction > 0 && rate === -1) {
rate = 0.25
} else if ((direction > 0 && rate >= 1 && rate < 16) ||
(direction < 0 && rate > -16 && rate <= -1)) {
rate *= 2 rate *= 2
} else if ((direction < 0 && rate > 1 && rate <= 16) || } else if (direction < 0 && rate > 1 && rate <= 16) {
(direction > 0 && rate >= -16 && rate < -1)) {
rate /= 2 rate /= 2
} }
state.playing.playbackRate = rate state.playing.playbackRate = rate
if (isCasting(state) && !Cast.setRate(rate)) { if (isCasting(state) && !Cast.setRate(rate)) {
state.playing.playbackRate = 1 state.playing.playbackRate = 1
} }
// Wait a bit before we hide the controls and header again
state.playing.mouseStationarySince = new Date().getTime()
} }
// Change the volume, in range [0, 1], by some amount // Change the volume, in range [0, 1], by some amount
@@ -201,11 +196,7 @@ module.exports = class PlaybackController {
// * The video is playing remotely on Chromecast or Airplay // * The video is playing remotely on Chromecast or Airplay
showOrHidePlayerControls () { showOrHidePlayerControls () {
const state = this.state const state = this.state
const hideControls = state.location.url() === 'player' && const hideControls = state.shouldHidePlayerControls()
state.playing.mouseStationarySince !== 0 &&
new Date().getTime() - state.playing.mouseStationarySince > 2000 &&
!state.playing.isPaused &&
state.playing.location === 'local'
if (hideControls !== state.playing.hideControls) { if (hideControls !== state.playing.hideControls) {
state.playing.hideControls = hideControls state.playing.hideControls = hideControls
@@ -222,38 +213,15 @@ module.exports = class PlaybackController {
state.playing.infoHash = torrentSummary.infoHash state.playing.infoHash = torrentSummary.infoHash
// update UI to show pending playback // update UI to show pending playback
if (torrentSummary.progress !== 1) sound.play('PLAY') sound.play('PLAY')
// TODO: remove torrentSummary.playStatus
torrentSummary.playStatus = 'requested'
this.update()
const timeout = setTimeout(() => { this.startServer(torrentSummary)
telemetry.logPlayAttempt('timeout') ipcRenderer.send('onPlayerOpen')
// TODO: remove torrentSummary.playStatus this.updatePlayer(infoHash, index, true, cb)
torrentSummary.playStatus = 'timeout' /* no seeders available? */
sound.play('ERROR')
cb(new Error('Playback timed out. Try again.'))
this.update()
}, 10000) /* give it a few seconds */
this.startServer(torrentSummary, () => {
clearTimeout(timeout)
// if we timed out (user clicked play a long time ago), don't autoplay
const timedOut = torrentSummary.playStatus === 'timeout'
delete torrentSummary.playStatus
if (timedOut) {
ipcRenderer.send('wt-stop-server')
return this.update()
}
ipcRenderer.send('onPlayerOpen')
this.updatePlayer(infoHash, index, true, cb)
})
} }
// Starts WebTorrent server for media streaming // Starts WebTorrent server for media streaming
startServer (torrentSummary, cb) { startServer (torrentSummary) {
if (torrentSummary.status === 'paused') { if (torrentSummary.status === 'paused') {
dispatch('startTorrentingSummary', torrentSummary.torrentKey) dispatch('startTorrentingSummary', torrentSummary.torrentKey)
ipcRenderer.once('wt-ready-' + torrentSummary.infoHash, ipcRenderer.once('wt-ready-' + torrentSummary.infoHash,
@@ -264,7 +232,6 @@ module.exports = class PlaybackController {
function onTorrentReady () { function onTorrentReady () {
ipcRenderer.send('wt-start-server', torrentSummary.infoHash) ipcRenderer.send('wt-start-server', torrentSummary.infoHash)
ipcRenderer.once('wt-server-' + torrentSummary.infoHash, () => cb())
} }
} }
@@ -277,7 +244,7 @@ module.exports = class PlaybackController {
if (!TorrentPlayer.isPlayable(fileSummary)) { if (!TorrentPlayer.isPlayable(fileSummary)) {
torrentSummary.mostRecentFileIndex = undefined torrentSummary.mostRecentFileIndex = undefined
return cb(new Error('Can\'t play that file')) return cb(new UnplayableFileError())
} }
torrentSummary.mostRecentFileIndex = index torrentSummary.mostRecentFileIndex = index
@@ -301,8 +268,16 @@ module.exports = class PlaybackController {
state.playing.jumpToTime = jumpToTime state.playing.jumpToTime = jumpToTime
// if it's audio, parse out the metadata (artist, title, etc) // if it's audio, parse out the metadata (artist, title, etc)
if (state.playing.type === 'audio' && !fileSummary.audioInfo) { if (torrentSummary.status === 'paused') {
ipcRenderer.send('wt-get-audio-metadata', torrentSummary.infoHash, index) ipcRenderer.once('wt-ready-' + torrentSummary.infoHash, getAudioMetadata)
} else {
getAudioMetadata()
}
function getAudioMetadata () {
if (state.playing.type === 'audio' && !fileSummary.audioInfo) {
ipcRenderer.send('wt-get-audio-metadata', torrentSummary.infoHash, index)
}
} }
// if it's video, check for subtitles files that are done downloading // if it's video, check for subtitles files that are done downloading

View File

@@ -1,4 +1,3 @@
const State = require('../lib/state')
const {dispatch} = require('../lib/dispatcher') const {dispatch} = require('../lib/dispatcher')
const ipcRenderer = require('electron').ipcRenderer const ipcRenderer = require('electron').ipcRenderer
@@ -17,7 +16,9 @@ module.exports = class PrefsController {
setup: function (cb) { setup: function (cb) {
// initialize preferences // initialize preferences
state.window.title = 'Preferences' state.window.title = 'Preferences'
state.unsaved = Object.assign(state.unsaved || {}, {prefs: state.saved.prefs || {}}) state.unsaved = Object.assign(state.unsaved || {}, {
prefs: Object.assign({}, state.saved.prefs)
})
ipcRenderer.send('setAllowNav', false) ipcRenderer.send('setAllowNav', false)
cb() cb()
}, },
@@ -50,8 +51,11 @@ module.exports = class PrefsController {
if (state.unsaved.prefs.isFileHandler !== state.saved.prefs.isFileHandler) { if (state.unsaved.prefs.isFileHandler !== state.saved.prefs.isFileHandler) {
ipcRenderer.send('setDefaultFileHandler', state.unsaved.prefs.isFileHandler) ipcRenderer.send('setDefaultFileHandler', state.unsaved.prefs.isFileHandler)
} }
if (state.unsaved.prefs.startup !== state.saved.prefs.startup) {
ipcRenderer.send('setStartup', state.unsaved.prefs.startup)
}
state.saved.prefs = Object.assign(state.saved.prefs || {}, state.unsaved.prefs) state.saved.prefs = Object.assign(state.saved.prefs || {}, state.unsaved.prefs)
State.save(state) dispatch('stateSaveImmediate')
dispatch('checkDownloadPath') dispatch('checkDownloadPath')
} }
} }

View File

@@ -1,5 +1,5 @@
const electron = require('electron') const electron = require('electron')
const fs = require('fs-extra') const fs = require('fs')
const path = require('path') const path = require('path')
const parallel = require('run-parallel') const parallel = require('run-parallel')
@@ -33,11 +33,10 @@ module.exports = class SubtitlesController {
} }
addSubtitles (files, autoSelect) { addSubtitles (files, autoSelect) {
const state = this.state
// Subtitles are only supported when playing video files // Subtitles are only supported when playing video files
if (state.playing.type !== 'video') return if (this.state.playing.type !== 'video') return
if (files.length === 0) return if (files.length === 0) return
const subtitles = state.playing.subtitles const subtitles = this.state.playing.subtitles
// Read the files concurrently, then add all resulting subtitle tracks // Read the files concurrently, then add all resulting subtitle tracks
const tasks = files.map((file) => (cb) => loadSubtitle(file, cb)) const tasks = files.map((file) => (cb) => loadSubtitle(file, cb))
@@ -47,17 +46,17 @@ module.exports = class SubtitlesController {
for (let i = 0; i < tracks.length; i++) { for (let i = 0; i < tracks.length; i++) {
// No dupes allowed // No dupes allowed
const track = tracks[i] const track = tracks[i]
let trackIndex = state.playing.subtitles.tracks let trackIndex = subtitles.tracks.findIndex((t) =>
.findIndex((t) => track.filePath === t.filePath) track.filePath === t.filePath)
// Add the track // Add the track
if (trackIndex === -1) { if (trackIndex === -1) {
trackIndex = state.playing.subtitles.tracks.push(track) - 1 trackIndex = subtitles.tracks.push(track) - 1
} }
// If we're auto-selecting a track, try to find one in the user's language // If we're auto-selecting a track, try to find one in the user's language
if (autoSelect && (i === 0 || isSystemLanguage(track.language))) { if (autoSelect && (i === 0 || isSystemLanguage(track.language))) {
state.playing.subtitles.selectedIndex = trackIndex subtitles.selectedIndex = trackIndex
} }
} }

View File

@@ -127,21 +127,22 @@ module.exports = class TorrentController {
torrentFileModtimes (torrentKey, fileModtimes) { torrentFileModtimes (torrentKey, fileModtimes) {
const torrentSummary = this.getTorrentSummary(torrentKey) const torrentSummary = this.getTorrentSummary(torrentKey)
if (!torrentSummary) throw new Error('Not saving modtimes for deleted torrent ' + torrentKey)
torrentSummary.fileModtimes = fileModtimes torrentSummary.fileModtimes = fileModtimes
dispatch('saveStateThrottled') dispatch('stateSave')
} }
torrentFileSaved (torrentKey, torrentFileName) { torrentFileSaved (torrentKey, torrentFileName) {
console.log('torrent file saved %s: %s', torrentKey, torrentFileName) console.log('torrent file saved %s: %s', torrentKey, torrentFileName)
const torrentSummary = this.getTorrentSummary(torrentKey) const torrentSummary = this.getTorrentSummary(torrentKey)
torrentSummary.torrentFileName = torrentFileName torrentSummary.torrentFileName = torrentFileName
dispatch('saveStateThrottled') dispatch('stateSave')
} }
torrentPosterSaved (torrentKey, posterFileName) { torrentPosterSaved (torrentKey, posterFileName) {
const torrentSummary = this.getTorrentSummary(torrentKey) const torrentSummary = this.getTorrentSummary(torrentKey)
torrentSummary.posterFileName = posterFileName torrentSummary.posterFileName = posterFileName
dispatch('saveStateThrottled') dispatch('stateSave')
} }
torrentAudioMetadata (infoHash, index, info) { torrentAudioMetadata (infoHash, index, info) {
@@ -176,7 +177,7 @@ function showDoneNotification (torrent) {
silent: true silent: true
}) })
notif.onClick = function () { notif.onclick = function () {
ipcRenderer.send('show') ipcRenderer.send('show')
} }

View File

@@ -3,7 +3,7 @@ const path = require('path')
const electron = require('electron') const electron = require('electron')
const {dispatch} = require('../lib/dispatcher') const {dispatch} = require('../lib/dispatcher')
const State = require('../lib/state') const {TorrentKeyNotFoundError} = require('../lib/errors')
const sound = require('../lib/sound') const sound = require('../lib/sound')
const TorrentSummary = require('../lib/torrent-summary') const TorrentSummary = require('../lib/torrent-summary')
@@ -25,6 +25,11 @@ module.exports = class TorrentListController {
torrentId = torrentId.path torrentId = torrentId.path
} }
// Trim extra spaces off pasted magnet links
if (typeof torrentId === 'string') {
torrentId = torrentId.trim()
}
// Allow a instant.io link to be pasted // Allow a instant.io link to be pasted
if (typeof torrentId === 'string' && instantIoRegex.test(torrentId)) { if (typeof torrentId === 'string' && instantIoRegex.test(torrentId)) {
torrentId = torrentId.slice(torrentId.indexOf('#') + 1) torrentId = torrentId.slice(torrentId.indexOf('#') + 1)
@@ -75,7 +80,7 @@ module.exports = class TorrentListController {
// Starts downloading and/or seeding a given torrentSummary. // Starts downloading and/or seeding a given torrentSummary.
startTorrentingSummary (torrentKey) { startTorrentingSummary (torrentKey) {
const s = TorrentSummary.getByKey(this.state, torrentKey) const s = TorrentSummary.getByKey(this.state, torrentKey)
if (!s) throw new Error('Missing key: ' + torrentKey) if (!s) throw new TorrentKeyNotFoundError(torrentKey)
// New torrent: give it a path // New torrent: give it a path
if (!s.path) { if (!s.path) {
@@ -93,6 +98,7 @@ module.exports = class TorrentListController {
fs.stat(fileOrFolder, function (err) { fs.stat(fileOrFolder, function (err) {
if (err) { if (err) {
s.error = 'path-missing' s.error = 'path-missing'
dispatch('backToList')
return return
} }
start() start()
@@ -101,7 +107,7 @@ module.exports = class TorrentListController {
function start () { function start () {
ipcRenderer.send('wt-start-torrenting', ipcRenderer.send('wt-start-torrenting',
s.torrentKey, s.torrentKey,
TorrentSummary.getTorrentID(s), TorrentSummary.getTorrentId(s),
s.path, s.path,
s.fileModtimes, s.fileModtimes,
s.selections) s.selections)
@@ -127,7 +133,9 @@ module.exports = class TorrentListController {
torrentSummary.selections[index] = !torrentSummary.selections[index] torrentSummary.selections[index] = !torrentSummary.selections[index]
// Let the WebTorrent process know to start or stop fetching that file // Let the WebTorrent process know to start or stop fetching that file
ipcRenderer.send('wt-select-files', infoHash, torrentSummary.selections) if (torrentSummary.status !== 'paused') {
ipcRenderer.send('wt-select-files', infoHash, torrentSummary.selections)
}
} }
confirmDeleteTorrent (infoHash, deleteData) { confirmDeleteTorrent (infoHash, deleteData) {
@@ -156,7 +164,7 @@ module.exports = class TorrentListController {
// remove torrent from saved list // remove torrent from saved list
this.state.saved.torrents.splice(index, 1) this.state.saved.torrents.splice(index, 1)
State.saveThrottled(this.state) dispatch('stateSave')
} }
// prevent user from going forward to a deleted torrent // prevent user from going forward to a deleted torrent
@@ -212,11 +220,41 @@ module.exports = class TorrentListController {
menu.append(new electron.remote.MenuItem({ menu.append(new electron.remote.MenuItem({
label: 'Save Torrent File As...', label: 'Save Torrent File As...',
click: () => saveTorrentFileAs(torrentSummary) click: () => dispatch('saveTorrentFileAs', torrentSummary.torrentKey)
})) }))
menu.popup(electron.remote.getCurrentWindow()) menu.popup(electron.remote.getCurrentWindow())
} }
// Takes a torrentSummary or torrentKey
// Shows a Save File dialog, then saves the .torrent file wherever the user requests
saveTorrentFileAs (torrentKey) {
const torrentSummary = TorrentSummary.getByKey(this.state, torrentKey)
if (!torrentSummary) throw new Error('Missing torrentKey: ' + torrentKey)
const downloadPath = this.state.saved.prefs.downloadPath
const newFileName = path.parse(torrentSummary.name).name + '.torrent'
const win = electron.remote.getCurrentWindow()
const opts = {
title: 'Save Torrent File',
defaultPath: path.join(downloadPath, newFileName),
filters: [
{ name: 'Torrent Files', extensions: ['torrent'] },
{ name: 'All Files', extensions: ['*'] }
]
}
electron.remote.dialog.showSaveDialog(win, opts, function (savePath) {
console.log('Saving torrent ' + torrentKey + ' to ' + savePath)
if (!savePath) return // They clicked Cancel
const torrentPath = TorrentSummary.getTorrentPath(torrentSummary)
fs.readFile(torrentPath, function (err, torrentFile) {
if (err) return dispatch('error', err)
fs.writeFile(savePath, torrentFile, function (err) {
if (err) return dispatch('error', err)
})
})
})
}
} }
// Recursively finds {name, path, size} for all files in a folder // Recursively finds {name, path, size} for all files in a folder
@@ -277,27 +315,3 @@ function moveItemToTrash (torrentSummary) {
function showItemInFolder (torrentSummary) { function showItemInFolder (torrentSummary) {
ipcRenderer.send('showItemInFolder', TorrentSummary.getFileOrFolder(torrentSummary)) ipcRenderer.send('showItemInFolder', TorrentSummary.getFileOrFolder(torrentSummary))
} }
function saveTorrentFileAs (torrentSummary) {
const downloadPath = this.state.saved.prefs.downloadPath
const newFileName = path.parse(torrentSummary.name).name + '.torrent'
const opts = {
title: 'Save Torrent File',
defaultPath: path.join(downloadPath, newFileName),
filters: [
{ name: 'Torrent Files', extensions: ['torrent'] },
{ name: 'All Files', extensions: ['*'] }
]
}
const win = electron.remote.getCurrentWindow()
electron.remote.dialog.showSaveDialog(win, opts, function (savePath) {
if (!savePath) return // They clicked Cancel
const torrentPath = TorrentSummary.getTorrentPath(torrentSummary)
fs.readFile(torrentPath, function (err, torrentFile) {
if (err) return dispatch('error', err)
fs.writeFile(savePath, torrentFile, function (err) {
if (err) return dispatch('error', err)
})
})
})
}

View File

@@ -1,4 +1,4 @@
const State = require('../lib/state') const {dispatch} = require('../lib/dispatcher')
// Controls the UI checking for new versions of the app, prompting install // Controls the UI checking for new versions of the app, prompting install
module.exports = class UpdateController { module.exports = class UpdateController {
@@ -21,6 +21,6 @@ module.exports = class UpdateController {
let skipped = this.state.saved.skippedVersions let skipped = this.state.saved.skippedVersions
if (!skipped) skipped = this.state.saved.skippedVersions = [] if (!skipped) skipped = this.state.saved.skippedVersions = []
skipped.push(version) skipped.push(version)
State.saveThrottled(this.state) dispatch('stateSave')
} }
} }

View File

@@ -1,30 +0,0 @@
module.exports = captureVideoFrame
function captureVideoFrame (video, format) {
if (typeof video === 'string') {
video = document.querySelector(video)
}
if (video == null || video.nodeName !== 'VIDEO') {
throw new Error('First argument must be a <video> element or selector')
}
if (format == null) {
format = 'png'
}
if (format !== 'png' && format !== 'jpg' && format !== 'webp') {
throw new Error('Second argument must be one of "png", "jpg", or "webp"')
}
const canvas = document.createElement('canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0)
const dataUri = canvas.toDataURL('image/' + format)
const data = dataUri.split(',')[1]
return new Buffer(data, 'base64')
}

View File

@@ -14,6 +14,7 @@ module.exports = {
} }
const config = require('../../config') const config = require('../../config')
const {CastingError} = require('./errors')
// Lazy load these for a ~300ms improvement in startup time // Lazy load these for a ~300ms improvement in startup time
let airplayer, chromecasts, dlnacasts let airplayer, chromecasts, dlnacasts
@@ -32,6 +33,15 @@ function init (appState, callback) {
state = appState state = appState
update = callback update = callback
// Don't actually cast during integration tests
// (Otherwise you'd need a physical Chromecast + AppleTV + DLNA TV to run them.)
if (config.IS_TEST) {
state.devices.chromecast = testPlayer('chromecast')
state.devices.airplay = testPlayer('airplay')
state.devices.dlna = testPlayer('dlna')
return
}
// Load modules, scan the network for devices // Load modules, scan the network for devices
airplayer = require('airplayer')() airplayer = require('airplayer')()
chromecasts = require('chromecasts')() chromecasts = require('chromecasts')()
@@ -57,6 +67,32 @@ function init (appState, callback) {
}) })
} }
// integration test player implementation
function testPlayer (type) {
return {
getDevices,
open,
play,
pause,
stop,
status,
seek,
volume
}
function getDevices () {
return [{name: type + '-1'}, {name: type + '-2'}]
}
function open () {}
function play () {}
function pause () {}
function stop () {}
function status () {}
function seek () {}
function volume () {}
}
// chromecast player implementation // chromecast player implementation
function chromecastPlayer () { function chromecastPlayer () {
const ret = { const ret = {
@@ -126,13 +162,7 @@ function chromecastPlayer () {
} }
function status () { function status () {
ret.device.status(function (err, status) { ret.device.status(handleStatus)
if (err) return console.log('error getting %s status: %o', state.playing.location, err)
state.playing.isPaused = status.playerState === 'PAUSED'
state.playing.currentTime = status.currentTime
state.playing.volume = status.volume.muted ? 0 : status.volume.level
update()
})
} }
function seek (time, callback) { function seek (time, callback) {
@@ -306,13 +336,7 @@ function dlnaPlayer (player) {
} }
function status () { function status () {
ret.device.status(function (err, status) { ret.device.status(handleStatus)
if (err) return console.log('error getting %s status: %o', state.playing.location, err)
state.playing.isPaused = status.playerState === 'PAUSED'
state.playing.currentTime = status.currentTime
state.playing.volume = status.volume.level
update()
})
} }
function seek (time, callback) { function seek (time, callback) {
@@ -328,6 +352,18 @@ function dlnaPlayer (player) {
} }
} }
function handleStatus (err, status) {
if (err || !status) {
return console.log('error getting %s status: %o',
state.playing.location,
err || 'missing response')
}
state.playing.isPaused = status.playerState === 'PAUSED'
state.playing.currentTime = status.currentTime
state.playing.volume = status.volume.muted ? 0 : status.volume.level
update()
}
// Start polling cast device state, whenever we're connected // Start polling cast device state, whenever we're connected
function startStatusInterval () { function startStatusInterval () {
statusInterval = setInterval(function () { statusInterval = setInterval(function () {
@@ -350,14 +386,16 @@ function toggleMenu (location) {
// Never cast to two devices at the same time // Never cast to two devices at the same time
if (state.playing.location !== 'local') { if (state.playing.location !== 'local') {
throw new Error('You can\'t connect to ' + location + throw new CastingError(
' when already connected to another device') `You can't connect to ${location} when already connected to another device`
} ) }
// Find all cast devices of the given type // Find all cast devices of the given type
const player = getPlayer(location) const player = getPlayer(location)
const devices = player ? player.getDevices() : [] const devices = player ? player.getDevices() : []
if (devices.length === 0) throw new Error('No ' + location + ' devices available') if (devices.length === 0) {
throw new CastingError(`No ${location} devices available`)
}
// Show a menu // Show a menu
state.devices.castMenu = {location, devices} state.devices.castMenu = {location, devices}

View File

@@ -1,15 +1,41 @@
const ExtendableError = require('es6-error')
/* Generic errors */
class CastingError extends ExtendableError {}
class PlaybackError extends ExtendableError {}
class SoundError extends ExtendableError {}
class TorrentError extends ExtendableError {}
/* Playback */
class UnplayableTorrentError extends PlaybackError {
constructor () { super('Can\'t play any files in torrent') }
}
class UnplayableFileError extends PlaybackError {
constructor () { super('Can\'t play that file') }
}
/* Sound */
class InvalidSoundNameError extends SoundError {
constructor (name) { super(`Invalid sound name: ${name}`) }
}
/* Torrent */
class TorrentKeyNotFoundError extends TorrentError {
constructor (torrentKey) { super(`Can't resolve torrent key ${torrentKey}`) }
}
module.exports = { module.exports = {
CastingError,
PlaybackError,
SoundError,
TorrentError,
UnplayableTorrentError, UnplayableTorrentError,
UnplayableFileError UnplayableFileError,
InvalidSoundNameError,
TorrentKeyNotFoundError
} }
function UnplayableTorrentError () {
this.message = 'Can\'t play any files in torrent'
}
function UnplayableFileError () {
this.message = 'Can\'t play that file'
}
UnplayableTorrentError.prototype = Error
UnplayableFileError.prototype = Error

View File

@@ -4,10 +4,11 @@ module.exports = {
run run
} }
const semver = require('semver')
const config = require('../../config')
const TorrentSummary = require('./torrent-summary')
const fs = require('fs') const fs = require('fs')
const path = require('path')
const semver = require('semver')
const config = require('../../config')
// Change `state.saved` (which will be saved back to config.json on exit) as // Change `state.saved` (which will be saved back to config.json on exit) as
// needed, for example to deal with config.json format changes across versions // needed, for example to deal with config.json format changes across versions
@@ -18,33 +19,22 @@ function run (state) {
} }
const version = state.saved.version const version = state.saved.version
const saved = state.saved
if (semver.lt(version, '0.7.0')) { if (semver.lt(version, '0.7.0')) migrate_0_7_0(saved)
migrate_0_7_0(state.saved) if (semver.lt(version, '0.7.2')) migrate_0_7_2(saved)
} if (semver.lt(version, '0.11.0')) migrate_0_11_0(saved)
if (semver.lt(version, '0.12.0')) migrate_0_12_0(saved)
if (semver.lt(version, '0.7.2')) { if (semver.lt(version, '0.14.0')) migrate_0_14_0(saved)
migrate_0_7_2(state.saved) if (semver.lt(version, '0.17.0')) migrate_0_17_0(saved)
} if (semver.lt(version, '0.17.2')) migrate_0_17_2(saved)
if (semver.lt(version, '0.11.0')) {
migrate_0_11_0(state.saved)
}
if (semver.lt(version, '0.12.0')) {
migrate_0_12_0(state.saved)
}
if (semver.lt(version, '0.14.0')) {
migrate_0_14_0(state.saved)
}
// Config is now on the new version // Config is now on the new version
state.saved.version = config.APP_VERSION state.saved.version = config.APP_VERSION
} }
function migrate_0_7_0 (saved) { function migrate_0_7_0 (saved) {
const fs = require('fs-extra') const cpFile = require('cp-file')
const path = require('path') const path = require('path')
saved.torrents.forEach(function (ts) { saved.torrents.forEach(function (ts) {
@@ -66,7 +56,7 @@ function migrate_0_7_0 (saved) {
dst = path.join(config.TORRENT_PATH, infoHash + '.torrent') dst = path.join(config.TORRENT_PATH, infoHash + '.torrent')
// Synchronous FS calls aren't ideal, but probably OK in a migration // Synchronous FS calls aren't ideal, but probably OK in a migration
// that only runs once // that only runs once
if (src !== dst) fs.copySync(src, dst) if (src !== dst) cpFile.sync(src, dst)
delete ts.torrentPath delete ts.torrentPath
ts.torrentFileName = infoHash + '.torrent' ts.torrentFileName = infoHash + '.torrent'
@@ -81,7 +71,7 @@ function migrate_0_7_0 (saved) {
dst = path.join(config.POSTER_PATH, infoHash + extension) dst = path.join(config.POSTER_PATH, infoHash + extension)
// Synchronous FS calls aren't ideal, but probably OK in a migration // Synchronous FS calls aren't ideal, but probably OK in a migration
// that only runs once // that only runs once
if (src !== dst) fs.copySync(src, dst) if (src !== dst) cpFile.sync(src, dst)
delete ts.posterURL delete ts.posterURL
ts.posterFileName = infoHash + extension ts.posterFileName = infoHash + extension
@@ -112,6 +102,8 @@ function migrate_0_11_0 (saved) {
} }
function migrate_0_12_0 (saved) { function migrate_0_12_0 (saved) {
const TorrentSummary = require('./torrent-summary')
if (saved.prefs.openExternalPlayer == null && saved.prefs.playInVlc != null) { if (saved.prefs.openExternalPlayer == null && saved.prefs.playInVlc != null) {
saved.prefs.openExternalPlayer = saved.prefs.playInVlc saved.prefs.openExternalPlayer = saved.prefs.playInVlc
} }
@@ -133,7 +125,7 @@ function migrate_0_12_0 (saved) {
if (!fileOrFolder) return if (!fileOrFolder) return
try { try {
fs.statSync(fileOrFolder) fs.statSync(fileOrFolder)
} catch (e) { } catch (err) {
// Default torrent with "missing path" error. Clear path. // Default torrent with "missing path" error. Clear path.
delete torrentSummary.path delete torrentSummary.path
} }
@@ -145,3 +137,72 @@ function migrate_0_14_0 (saved) {
delete ts.defaultPlayFileIndex delete ts.defaultPlayFileIndex
}) })
} }
function migrate_0_17_0 (saved) {
// Fix a sad, sad bug that resulted in 100MB+ config.json files
saved.torrents.forEach(function (ts) {
if (!ts.files) return
ts.files.forEach(function (file) {
if (!file.audioInfo || !file.audioInfo.picture) return
// This contained a Buffer, which 30x'd in size when serialized to JSON
delete file.audioInfo.picture
})
})
}
function migrate_0_17_2 (saved) {
// Remove the trailing dot (.) from the Wired CD torrent name, since
// folders/files that end in a trailing dot (.) or space are not deletable from
// Windows Explorer. See: https://github.com/feross/webtorrent-desktop/issues/905
const cpFile = require('cp-file')
const rimraf = require('rimraf')
const OLD_NAME = 'The WIRED CD - Rip. Sample. Mash. Share.'
const NEW_NAME = 'The WIRED CD - Rip. Sample. Mash. Share'
const OLD_HASH = '3ba219a8634bf7bae3d848192b2da75ae995589d'
const NEW_HASH = 'a88fda5954e89178c372716a6a78b8180ed4dad3'
const ts = saved.torrents.find((ts) => {
return ts.infoHash === OLD_HASH
})
if (!ts) return // Wired CD torrent does not exist
// New versions of WebTorrent ship with a fixed torrent file. Let's fix up the
// name in existing versions of WebTorrent.
ts.name = ts.displayName = NEW_NAME
ts.files.forEach((file) => {
file.path = file.path.replace(OLD_NAME, NEW_NAME)
})
// Changing the torrent name causes the info hash to change
ts.infoHash = NEW_HASH
ts.magnetURI = ts.magnetURI.replace(OLD_HASH, NEW_HASH)
try {
fs.renameSync(
path.join(config.POSTER_PATH, ts.posterFileName),
path.join(config.POSTER_PATH, NEW_HASH + '.jpg')
)
} catch (err) {}
ts.posterFileName = NEW_HASH + '.jpg'
rimraf.sync(path.join(config.TORRENT_PATH, ts.torrentFileName))
cpFile.sync(
path.join(config.STATIC_PATH, 'wiredCd.torrent'),
path.join(config.TORRENT_PATH, NEW_HASH + '.torrent')
)
ts.torrentFileName = NEW_HASH + '.torrent'
if (ts.path) {
// If torrent folder already exists on disk, try to rename it
try {
fs.renameSync(
path.join(ts.path, OLD_NAME),
path.join(ts.path, NEW_NAME)
)
} catch (err) {}
}
}

View File

@@ -37,7 +37,9 @@ function getPreviousIndex (state) {
} }
function getCurrentLocalURL (state) { function getCurrentLocalURL (state) {
return state.server.localURL + '/' + state.playing.fileIndex return state.server
? state.server.localURL + '/' + state.playing.fileIndex
: ''
} }
function updateCache (state) { function updateCache (state) {
@@ -70,7 +72,7 @@ function updateCache (state) {
function findPreviousIndex (state) { function findPreviousIndex (state) {
const files = TorrentSummary.getByKey(state, state.playing.infoHash).files const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
for (var i = state.playing.fileIndex - 1; i >= 0; i--) { for (let i = state.playing.fileIndex - 1; i >= 0; i--) {
if (TorrentPlayer.isPlayable(files[i])) return i if (TorrentPlayer.isPlayable(files[i])) return i
} }
return null return null
@@ -78,7 +80,7 @@ function findPreviousIndex (state) {
function findNextIndex (state) { function findNextIndex (state) {
const files = TorrentSummary.getByKey(state, state.playing.infoHash).files const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
for (var i = state.playing.fileIndex + 1; i < files.length; i++) { for (let i = state.playing.fileIndex + 1; i < files.length; i++) {
if (TorrentPlayer.isPlayable(files[i])) return i if (TorrentPlayer.isPlayable(files[i])) return i
} }
return null return null

View File

@@ -1,12 +1,12 @@
module.exports = { module.exports = {
preload,
play play
} }
const config = require('../../config') const config = require('../../config')
const {InvalidSoundNameError} = require('./errors')
const path = require('path') const path = require('path')
const VOLUME = 0.15 const VOLUME = 0.25
/* Cache of Audio elements, for instant playback */ /* Cache of Audio elements, for instant playback */
const cache = {} const cache = {}
@@ -18,11 +18,11 @@ const sounds = {
}, },
DELETE: { DELETE: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'delete.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'delete.wav'),
volume: VOLUME volume: VOLUME * 0.5
}, },
DISABLE: { DISABLE: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'disable.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'disable.wav'),
volume: VOLUME volume: VOLUME * 0.5
}, },
DONE: { DONE: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'done.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'done.wav'),
@@ -30,7 +30,7 @@ const sounds = {
}, },
ENABLE: { ENABLE: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'enable.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'enable.wav'),
volume: VOLUME volume: VOLUME * 0.5
}, },
ERROR: { ERROR: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'error.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'error.wav'),
@@ -42,18 +42,7 @@ const sounds = {
}, },
STARTUP: { STARTUP: {
url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'startup.wav'), url: 'file://' + path.join(config.STATIC_PATH, 'sound', 'startup.wav'),
volume: VOLUME * 2 volume: VOLUME
}
}
function preload () {
for (let name in sounds) {
if (!cache[name]) {
const sound = sounds[name]
const audio = cache[name] = new window.Audio()
audio.volume = sound.volume
audio.src = sound.url
}
} }
} }
@@ -62,7 +51,7 @@ function play (name) {
if (!audio) { if (!audio) {
const sound = sounds[name] const sound = sounds[name]
if (!sound) { if (!sound) {
throw new Error('Invalid sound name') throw new InvalidSoundNameError(name)
} }
audio = cache[name] = new window.Audio() audio = cache[name] = new window.Audio()
audio.volume = sound.volume audio.volume = sound.volume

View File

@@ -3,17 +3,26 @@ const path = require('path')
const {EventEmitter} = require('events') const {EventEmitter} = require('events')
const config = require('../../config') const config = require('../../config')
const migrations = require('./migrations')
const SAVE_DEBOUNCE_INTERVAL = 1000
appConfig.filePath = path.join(config.CONFIG_PATH, 'config.json')
const State = module.exports = Object.assign(new EventEmitter(), { const State = module.exports = Object.assign(new EventEmitter(), {
getDefaultPlayState, getDefaultPlayState,
load, load,
save, // state.save() calls are rate-limited. Use state.saveImmediate() to skip limit.
saveThrottled save: function () {
// Perf optimization: Lazy-require debounce (and it's dependencies)
const debounce = require('debounce')
// After first State.save() invokation, future calls go straight to the
// debounced function
State.save = debounce(saveImmediate, SAVE_DEBOUNCE_INTERVAL)
State.save(...arguments)
},
saveImmediate
}) })
appConfig.filePath = path.join(config.CONFIG_PATH, 'config.json')
function getDefaultState () { function getDefaultState () {
const LocationHistory = require('location-history') const LocationHistory = require('location-history')
@@ -68,7 +77,9 @@ function getDefaultState () {
* Getters, for convenience * Getters, for convenience
*/ */
getPlayingTorrentSummary, getPlayingTorrentSummary,
getPlayingFileSummary getPlayingFileSummary,
getExternalPlayerName,
shouldHidePlayerControls
} }
} }
@@ -97,8 +108,9 @@ function getDefaultPlayState () {
} }
/* If the saved state file doesn't exist yet, here's what we use instead */ /* If the saved state file doesn't exist yet, here's what we use instead */
function setupSavedState (cb) { function setupStateSaved (cb) {
const fs = require('fs-extra') const cpFile = require('cp-file')
const fs = require('fs')
const parseTorrent = require('parse-torrent') const parseTorrent = require('parse-torrent')
const parallel = require('run-parallel') const parallel = require('run-parallel')
@@ -107,7 +119,8 @@ function setupSavedState (cb) {
downloadPath: config.DEFAULT_DOWNLOAD_PATH, downloadPath: config.DEFAULT_DOWNLOAD_PATH,
isFileHandler: false, isFileHandler: false,
openExternalPlayer: false, openExternalPlayer: false,
externalPlayerPath: null externalPlayerPath: null,
startup: false
}, },
torrents: config.DEFAULT_TORRENTS.map(createTorrentObject), torrents: config.DEFAULT_TORRENTS.map(createTorrentObject),
version: config.APP_VERSION /* make sure we can upgrade gracefully later */ version: config.APP_VERSION /* make sure we can upgrade gracefully later */
@@ -118,18 +131,16 @@ function setupSavedState (cb) {
config.DEFAULT_TORRENTS.map(function (t, i) { config.DEFAULT_TORRENTS.map(function (t, i) {
const infoHash = saved.torrents[i].infoHash const infoHash = saved.torrents[i].infoHash
tasks.push(function (cb) { tasks.push(function (cb) {
fs.copy( cpFile(
path.join(config.STATIC_PATH, t.posterFileName), path.join(config.STATIC_PATH, t.posterFileName),
path.join(config.POSTER_PATH, infoHash + path.extname(t.posterFileName)), path.join(config.POSTER_PATH, infoHash + path.extname(t.posterFileName))
cb ).then(cb).catch(cb)
)
}) })
tasks.push(function (cb) { tasks.push(function (cb) {
fs.copy( cpFile(
path.join(config.STATIC_PATH, t.torrentFileName), path.join(config.STATIC_PATH, t.torrentFileName),
path.join(config.TORRENT_PATH, infoHash + '.torrent'), path.join(config.TORRENT_PATH, infoHash + '.torrent')
cb ).then(cb).catch(cb)
)
}) })
}) })
@@ -139,6 +150,7 @@ function setupSavedState (cb) {
}) })
function createTorrentObject (t) { function createTorrentObject (t) {
// TODO: Doing several fs.readFileSync calls during first startup is not ideal
const torrent = fs.readFileSync(path.join(config.STATIC_PATH, t.torrentFileName)) const torrent = fs.readFileSync(path.join(config.STATIC_PATH, t.torrentFileName))
const parsedTorrent = parseTorrent(torrent) const parsedTorrent = parseTorrent(torrent)
@@ -151,7 +163,8 @@ function setupSavedState (cb) {
torrentFileName: parsedTorrent.infoHash + '.torrent', torrentFileName: parsedTorrent.infoHash + '.torrent',
magnetURI: parseTorrent.toMagnetURI(parsedTorrent), magnetURI: parseTorrent.toMagnetURI(parsedTorrent),
files: parsedTorrent.files, files: parsedTorrent.files,
selections: parsedTorrent.files.map((x) => true) selections: parsedTorrent.files.map((x) => true),
testID: t.testID
} }
} }
} }
@@ -167,30 +180,50 @@ function getPlayingFileSummary () {
return torrentSummary.files[this.playing.fileIndex] return torrentSummary.files[this.playing.fileIndex]
} }
function load (cb) { function getExternalPlayerName () {
const state = getDefaultState() const playerPath = this.saved.prefs.externalPlayerPath
if (!playerPath) return 'VLC'
return path.basename(playerPath).split('.')[0]
}
function shouldHidePlayerControls () {
return this.location.url() === 'player' &&
this.playing.mouseStationarySince !== 0 &&
new Date().getTime() - this.playing.mouseStationarySince > 2000 &&
!this.playing.mouseInControls &&
!this.playing.isPaused &&
this.playing.location === 'local' &&
this.playing.playbackRate === 1
}
function load (cb) {
appConfig.read(function (err, saved) { appConfig.read(function (err, saved) {
if (err || !saved.version) { if (err || !saved.version) {
console.log('Missing config file: Creating new one') console.log('Missing config file: Creating new one')
setupSavedState(onSaved) setupStateSaved(onSavedState)
} else { } else {
onSaved(null, saved) onSavedState(null, saved)
} }
}) })
function onSaved (err, saved) { function onSavedState (err, saved) {
if (err) return cb(err) if (err) return cb(err)
const state = getDefaultState()
state.saved = saved state.saved = saved
migrations.run(state)
if (process.type === 'renderer') {
// Perf optimization: Save require() calls in the main process
const migrations = require('./migrations')
migrations.run(state)
}
cb(null, state) cb(null, state)
} }
} }
// Write state.saved to the JSON state file // Write state.saved to the JSON state file
function save (state, cb) { function saveImmediate (state, cb) {
console.log('Saving state to ' + appConfig.filePath) console.log('Saving state to ' + appConfig.filePath)
delete state.saveStateTimeout
// Clean up, so that we're not saving any pending state // Clean up, so that we're not saving any pending state
const copy = Object.assign({}, state.saved) const copy = Object.assign({}, state.saved)
@@ -204,9 +237,6 @@ function save (state, cb) {
if (key === 'progress' || key === 'torrentKey') { if (key === 'progress' || key === 'torrentKey') {
continue // Don't save progress info or key for the webtorrent process continue // Don't save progress info or key for the webtorrent process
} }
if (key === 'playStatus') {
continue // Don't save whether a torrent is playing / pending
}
if (key === 'error') { if (key === 'error') {
continue // Don't save error states continue // Don't save error states
} }
@@ -217,15 +247,6 @@ function save (state, cb) {
appConfig.write(copy, (err) => { appConfig.write(copy, (err) => {
if (err) console.error(err) if (err) console.error(err)
else State.emit('savedState') else State.emit('stateSaved')
}) })
} }
// Write, but no more than once a second
function saveThrottled (state) {
if (state.saveStateTimeout) return
state.saveStateTimeout = setTimeout(function () {
if (!state.saveStateTimeout) return
save(state)
}, 1000)
}

View File

@@ -2,15 +2,12 @@
// Reports back so that we can improve WebTorrent Desktop // Reports back so that we can improve WebTorrent Desktop
module.exports = { module.exports = {
init, init,
send,
logUncaughtError, logUncaughtError,
logPlayAttempt logPlayAttempt
} }
const crypto = require('crypto')
const electron = require('electron') const electron = require('electron')
const https = require('https')
const os = require('os')
const url = require('url')
const config = require('../../config') const config = require('../../config')
@@ -18,28 +15,49 @@ let telemetry
function init (state) { function init (state) {
telemetry = state.saved.telemetry telemetry = state.saved.telemetry
// First app run
if (!telemetry) { if (!telemetry) {
telemetry = state.saved.telemetry = createSummary() const crypto = require('crypto')
telemetry = state.saved.telemetry = {
userID: crypto.randomBytes(32).toString('hex') // 256-bit random ID
}
reset() reset()
} }
}
function send (state) {
const now = new Date() const now = new Date()
telemetry.version = config.APP_VERSION telemetry.version = config.APP_VERSION
telemetry.timestamp = now.toISOString() telemetry.timestamp = now.toISOString()
telemetry.localTime = now.toTimeString() telemetry.localTime = now.toTimeString()
telemetry.screens = getScreenInfo() telemetry.screens = getScreenInfo()
telemetry.system = getSystemInfo() telemetry.system = getSystemInfo()
telemetry.approxNumTorrents = getApproxNumTorrents(state) telemetry.torrentStats = getTorrentStats(state)
telemetry.approxNumTorrents = telemetry.torrentStats.approxCount
if (config.IS_PRODUCTION) { if (!config.IS_PRODUCTION) {
postToServer()
// If the user keeps WebTorrent running for a long time, post every 12h
setInterval(postToServer, 12 * 3600 * 1000)
} else {
// Development: telemetry used only for local debugging // Development: telemetry used only for local debugging
// Empty uncaught errors, etc at the start of every run // Empty uncaught errors, etc at the start of every run
reset() return reset()
} }
const get = require('simple-get')
const opts = {
url: config.TELEMETRY_URL,
body: telemetry,
json: true
}
get.post(opts, function (err, res) {
if (err) return console.error('Error sending telemetry', err)
if (res.statusCode !== 200) {
return console.error(`Error sending telemetry, status code: ${res.statusCode}`)
}
console.log('Sent telemetry')
reset()
})
} }
function reset () { function reset () {
@@ -54,41 +72,6 @@ function reset () {
} }
} }
function postToServer () {
// Serialize the telemetry summary
const payload = new Buffer(JSON.stringify(telemetry), 'utf8')
// POST to our server
const options = url.parse(config.TELEMETRY_URL)
options.method = 'POST'
options.headers = {
'Content-Type': 'application/json',
'Content-Length': payload.length
}
const req = https.request(options, function (res) {
if (res.statusCode === 200) {
console.log('Successfully posted telemetry summary')
reset()
} else {
console.error('Couldn\'t post telemetry summary, got HTTP ' + res.statusCode)
}
})
req.on('error', function (e) {
console.error('Couldn\'t post telemetry summary', e)
})
req.write(payload)
req.end()
}
// Creates a new telemetry summary. Gives the user a unique ID,
// collects screen resolution, etc
function createSummary () {
// Make a 256-bit random unique ID
const userID = crypto.randomBytes(32).toString('hex')
return { userID }
}
// Track screen resolution // Track screen resolution
function getScreenInfo () { function getScreenInfo () {
return electron.screen.getAllDisplays().map((screen) => ({ return electron.screen.getAllDisplays().map((screen) => ({
@@ -100,22 +83,69 @@ function getScreenInfo () {
// Track basic system info like OS version and amount of RAM // Track basic system info like OS version and amount of RAM
function getSystemInfo () { function getSystemInfo () {
const os = require('os')
return { return {
osPlatform: process.platform, osPlatform: process.platform,
osRelease: os.type() + ' ' + os.release(), osRelease: os.type() + ' ' + os.release(),
architecture: os.arch(), architecture: os.arch(),
totalMemoryMB: os.totalmem() / (1 << 20), systemArchitecture: config.OS_SYSARCH,
totalMemoryMB: roundPow2(os.totalmem() / (1 << 20)),
numCores: os.cpus().length numCores: os.cpus().length
} }
} }
// Get the number of torrents, rounded to the nearest power of two // Get stats like the # of torrents currently active, # in list, total size
function getApproxNumTorrents (state) { function getTorrentStats (state) {
const exactNum = state.saved.torrents.length const count = state.saved.torrents.length
if (exactNum === 0) return 0 let sizeMB = 0
let byStatus = {
new: { count: 0, sizeMB: 0 },
downloading: { count: 0, sizeMB: 0 },
seeding: { count: 0, sizeMB: 0 },
paused: { count: 0, sizeMB: 0 }
}
// First, count torrents & total file size
for (let i = 0; i < count; i++) {
const t = state.saved.torrents[i]
const stat = byStatus[t.status]
if (!t || !t.files || !stat) continue
stat.count++
for (let j = 0; j < t.files.length; j++) {
const f = t.files[j]
if (!f || !f.length) continue
const fileSizeMB = f.length / (1 << 20)
sizeMB += fileSizeMB
stat.sizeMB += fileSizeMB
}
}
// Then, round all the counts and sums to the nearest power of 2
const ret = roundTorrentStats({count, sizeMB})
ret.byStatus = {
new: roundTorrentStats(byStatus.new),
downloading: roundTorrentStats(byStatus.downloading),
seeding: roundTorrentStats(byStatus.seeding),
paused: roundTorrentStats(byStatus.paused)
}
return ret
}
function roundTorrentStats (stats) {
return {
approxCount: roundPow2(stats.count),
approxSizeMB: roundPow2(stats.sizeMB)
}
}
// Rounds to the nearest power of 2, for privacy and easy bucketing.
// Rounds 35 to 32, 70 to 64, 5 to 4, 1 to 1, 0 to 0.
// Supports nonnegative numbers only.
function roundPow2 (n) {
if (n <= 0) return 0
// Otherwise, return 1, 2, 4, 8, etc by rounding in log space // Otherwise, return 1, 2, 4, 8, etc by rounding in log space
const log2 = Math.log(exactNum) / Math.log(2) const log2 = Math.log(n) / Math.log(2)
return 1 << Math.round(log2) return Math.pow(2, Math.round(log2))
} }
// An uncaught error happened in the main process or in one of the windows // An uncaught error happened in the main process or in one of the windows
@@ -176,7 +206,7 @@ function getElemString (elem) {
let ret = elem.tagName let ret = elem.tagName
try { try {
ret += '.' + Array.from(elem.classList).join('.') ret += '.' + Array.from(elem.classList).join('.')
} catch (e) {} } catch (err) {}
return ret return ret
} }

View File

@@ -1,6 +1,6 @@
module.exports = torrentPoster module.exports = torrentPoster
const captureVideoFrame = require('./capture-video-frame') const captureFrame = require('capture-frame')
const path = require('path') const path = require('path')
function torrentPoster (torrent, cb) { function torrentPoster (torrent, cb) {
@@ -61,7 +61,7 @@ function torrentPosterFromVideo (file, torrent, cb) {
function onSeeked () { function onSeeked () {
video.removeEventListener('seeked', onSeeked) video.removeEventListener('seeked', onSeeked)
const buf = captureVideoFrame(video) const buf = captureFrame(video)
// unload video element // unload video element
video.pause() video.pause()

View File

@@ -2,7 +2,7 @@ module.exports = {
getPosterPath, getPosterPath,
getTorrentPath, getTorrentPath,
getByKey, getByKey,
getTorrentID, getTorrentId,
getFileOrFolder getFileOrFolder
} }
@@ -28,7 +28,7 @@ function getPosterPath (torrentSummary) {
// Expects a torrentSummary // Expects a torrentSummary
// Returns a torrentID: filename, magnet URI, or infohash // Returns a torrentID: filename, magnet URI, or infohash
function getTorrentID (torrentSummary) { function getTorrentId (torrentSummary) {
const s = torrentSummary const s = torrentSummary
if (s.torrentFileName) { // Load torrent file from disk if (s.torrentFileName) { // Load torrent file from disk
return getTorrentPath(s) return getTorrentPath(s)
@@ -53,5 +53,6 @@ function getByKey (state, torrentKey) {
function getFileOrFolder (torrentSummary) { function getFileOrFolder (torrentSummary) {
const ts = torrentSummary const ts = torrentSummary
if (!ts.path || !ts.files || ts.files.length === 0) return null if (!ts.path || !ts.files || ts.files.length === 0) return null
return path.join(ts.path, ts.files[0].path.split('/')[0]) const dirname = ts.files[0].path.split(path.sep)[0]
return path.join(ts.path, dirname)
} }

View File

@@ -1,8 +1,34 @@
/**
* Perf optimization: Hook into require() to modify how certain modules load:
*
* - `lodash/merge` (used by `material-ui`) causes 119 require() calls at startup,
* which take ~100ms. Replace it with `lodash.merge` which is equivalent.
* See: https://github.com/callemall/material-ui/pull/4380#issuecomment-250894552
*
* - `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.
*/
let Module = require('module')
const _require = Module.prototype.require
Module.prototype.require = function (id) {
if (id === 'lodash/merge') id = 'lodash.merge'
if (id === 'inline-style-prefixer') return {}
return _require.apply(this, arguments)
}
console.time('init') console.time('init')
const crashReporter = require('../crash-reporter') const crashReporter = require('../crash-reporter')
crashReporter.init() crashReporter.init()
// Perf optimization: Start asynchronously read on config file before all the
// blocking require() calls below.
const State = require('./lib/state')
State.load(onState)
const createGetter = require('fn-getter')
const dragDrop = require('drag-drop') const dragDrop = require('drag-drop')
const electron = require('electron') const electron = require('electron')
const fs = require('fs') const fs = require('fs')
@@ -12,22 +38,16 @@ const ReactDOM = require('react-dom')
const config = require('../config') const config = require('../config')
const telemetry = require('./lib/telemetry') const telemetry = require('./lib/telemetry')
const sound = require('./lib/sound') const sound = require('./lib/sound')
const State = require('./lib/state')
const TorrentPlayer = require('./lib/torrent-player') const TorrentPlayer = require('./lib/torrent-player')
// Perf optimization: Needed immediately, so do not lazy load it below
const TorrentListController = require('./controllers/torrent-list-controller')
// Required by Material UI -- adds `onTouchTap` event // Required by Material UI -- adds `onTouchTap` event
require('react-tap-event-plugin')() require('react-tap-event-plugin')()
const App = require('./pages/app') const App = require('./pages/app')
const MediaController = require('./controllers/media-controller')
const UpdateController = require('./controllers/update-controller')
const PrefsController = require('./controllers/prefs-controller')
const PlaybackController = require('./controllers/playback-controller')
const SubtitlesController = require('./controllers/subtitles-controller')
const TorrentListController = require('./controllers/torrent-list-controller')
const TorrentController = require('./controllers/torrent-controller')
// Electron apps have two processes: a main process (node) runs first and starts // Electron apps have two processes: a main process (node) runs first and starts
// a renderer process (essentially a Chrome window). We're in the renderer process, // a renderer process (essentially a Chrome window). We're in the renderer process,
// and this IPC channel receives from and sends messages to the main process // and this IPC channel receives from and sends messages to the main process
@@ -50,31 +70,52 @@ let state
// Root React component // Root React component
let app let app
State.load(onState)
// Called once when the application loads. (Not once per window.) // Called once when the application loads. (Not once per window.)
// Connects to the torrent networks, sets up the UI and OS integrations like // Connects to the torrent networks, sets up the UI and OS integrations like
// the dock icon and drag+drop. // the dock icon and drag+drop.
function onState (err, _state) { function onState (err, _state) {
if (err) return onError(err) if (err) return onError(err)
state = window.state = _state // Make available for easier debugging
// Make available for easier debugging
state = window.state = _state
window.dispatch = dispatch
telemetry.init(state) telemetry.init(state)
// Log uncaught JS errors // Log uncaught JS errors
window.addEventListener('error', window.addEventListener(
(e) => telemetry.logUncaughtError('window', e), 'error', (e) => telemetry.logUncaughtError('window', e), true /* capture */
true /* capture */) )
// Create controllers // Create controllers
controllers = { controllers = {
media: new MediaController(state), media: createGetter(() => {
update: new UpdateController(state), const MediaController = require('./controllers/media-controller')
prefs: new PrefsController(state, config), return new MediaController(state)
playback: new PlaybackController(state, config, update), }),
subtitles: new SubtitlesController(state), playback: createGetter(() => {
torrentList: new TorrentListController(state), const PlaybackController = require('./controllers/playback-controller')
torrent: new TorrentController(state) 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)
}),
torrent: createGetter(() => {
const TorrentController = require('./controllers/torrent-controller')
return new TorrentController(state)
}),
torrentList: createGetter(() => {
return new TorrentListController(state)
}),
update: createGetter(() => {
const UpdateController = require('./controllers/update-controller')
return new UpdateController(state)
})
} }
// Add first page to location history // Add first page to location history
@@ -89,23 +130,18 @@ function onState (err, _state) {
// Restart everything we were torrenting last time the app ran // Restart everything we were torrenting last time the app ran
resumeTorrents() resumeTorrents()
// Initialize ReactDOM
app = ReactDOM.render(<App state={state} />, document.querySelector('#body'))
// Calling update() updates the UI given the current state // Calling update() updates the UI given the current state
// Do this at least once a second to give every file in every torrentSummary // 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 // a progress bar and to keep the cursor in sync when playing a video
setInterval(update, 1000) setInterval(update, 1000)
app = ReactDOM.render(<App state={state} />, document.querySelector('#body'))
// Lazy-load other stuff, like the AppleTV module, later to keep startup fast
window.setTimeout(delayedInit, config.DELAYED_INIT)
// Listen for messages from the main process // Listen for messages from the main process
setupIpc() setupIpc()
// Warn if the download dir is gone, eg b/c an external drive is unplugged // Drag and drop files/text to start torrenting or seeding
checkDownloadPath()
// OS integrations:
// ...drag and drop files/text to start torrenting or seeding
dragDrop('body', { dragDrop('body', {
onDrop: onOpen, onDrop: onOpen,
onDropText: onOpen onDropText: onOpen
@@ -118,18 +154,33 @@ function onState (err, _state) {
window.addEventListener('focus', onFocus) window.addEventListener('focus', onFocus)
window.addEventListener('blur', onBlur) window.addEventListener('blur', onBlur)
// ...window visibility state. if (electron.remote.getCurrentWindow().isVisible()) {
document.addEventListener('webkitvisibilitychange', onVisibilityChange) 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 // Done! Ideally we want to get here < 500ms after the user clicks the app
sound.play('STARTUP')
console.timeEnd('init') console.timeEnd('init')
} }
// Runs a few seconds after the app loads, to avoid slowing down startup time // Runs a few seconds after the app loads, to avoid slowing down startup time
function delayedInit () { 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() lazyLoadCast()
sound.preload()
} }
// Lazily loads Chromecast and Airplay support // Lazily loads Chromecast and Airplay support
@@ -147,7 +198,7 @@ function lazyLoadCast () {
// 3. dispatch - the event handler calls dispatch(), main.js sends it to a controller // 3. dispatch - the event handler calls dispatch(), main.js sends it to a controller
// 4. controller - the controller handles the event, changing the state object // 4. controller - the controller handles the event, changing the state object
function update () { function update () {
controllers.playback.showOrHidePlayerControls() controllers.playback().showOrHidePlayerControls()
app.setState(state) app.setState(state)
updateElectron() updateElectron()
} }
@@ -175,50 +226,54 @@ const dispatchHandlers = {
'openFiles': () => ipcRenderer.send('openFiles'), /* shows the open file dialog */ 'openFiles': () => ipcRenderer.send('openFiles'), /* shows the open file dialog */
'openTorrentAddress': () => { state.modal = { id: 'open-torrent-address-modal' } }, 'openTorrentAddress': () => { state.modal = { id: 'open-torrent-address-modal' } },
'addTorrent': (torrentId) => controllers.torrentList.addTorrent(torrentId), 'addTorrent': (torrentId) => controllers.torrentList().addTorrent(torrentId),
'showCreateTorrent': (paths) => controllers.torrentList.showCreateTorrent(paths), 'showCreateTorrent': (paths) => controllers.torrentList().showCreateTorrent(paths),
'createTorrent': (options) => controllers.torrentList.createTorrent(options), 'createTorrent': (options) => controllers.torrentList().createTorrent(options),
'toggleTorrent': (infoHash) => controllers.torrentList.toggleTorrent(infoHash), 'toggleTorrent': (infoHash) => controllers.torrentList().toggleTorrent(infoHash),
'toggleTorrentFile': (infoHash, index) => 'toggleTorrentFile': (infoHash, index) =>
controllers.torrentList.toggleTorrentFile(infoHash, index), controllers.torrentList().toggleTorrentFile(infoHash, index),
'confirmDeleteTorrent': (infoHash, deleteData) => 'confirmDeleteTorrent': (infoHash, deleteData) =>
controllers.torrentList.confirmDeleteTorrent(infoHash, deleteData), controllers.torrentList().confirmDeleteTorrent(infoHash, deleteData),
'deleteTorrent': (infoHash, deleteData) => 'deleteTorrent': (infoHash, deleteData) =>
controllers.torrentList.deleteTorrent(infoHash, deleteData), controllers.torrentList().deleteTorrent(infoHash, deleteData),
'toggleSelectTorrent': (infoHash) => 'toggleSelectTorrent': (infoHash) =>
controllers.torrentList.toggleSelectTorrent(infoHash), controllers.torrentList().toggleSelectTorrent(infoHash),
'openTorrentContextMenu': (infoHash) => 'openTorrentContextMenu': (infoHash) =>
controllers.torrentList.openTorrentContextMenu(infoHash), controllers.torrentList().openTorrentContextMenu(infoHash),
'startTorrentingSummary': (torrentKey) => 'startTorrentingSummary': (torrentKey) =>
controllers.torrentList.startTorrentingSummary(torrentKey), controllers.torrentList().startTorrentingSummary(torrentKey),
'saveTorrentFileAs': (torrentKey) =>
controllers.torrentList().saveTorrentFileAs(torrentKey),
// Playback // Playback
'playFile': (infoHash, index) => controllers.playback.playFile(infoHash, index), 'playFile': (infoHash, index) => controllers.playback().playFile(infoHash, index),
'playPause': () => controllers.playback.playPause(), 'playPause': () => controllers.playback().playPause(),
'nextTrack': () => controllers.playback.nextTrack(), 'nextTrack': () => controllers.playback().nextTrack(),
'previousTrack': () => controllers.playback.previousTrack(), 'previousTrack': () => controllers.playback().previousTrack(),
'skip': (time) => controllers.playback.skip(time), 'skip': (time) => controllers.playback().skip(time),
'skipTo': (time) => controllers.playback.skipTo(time), 'skipTo': (time) => controllers.playback().skipTo(time),
'changePlaybackRate': (dir) => controllers.playback.changePlaybackRate(dir), 'changePlaybackRate': (dir) => controllers.playback().changePlaybackRate(dir),
'changeVolume': (delta) => controllers.playback.changeVolume(delta), 'changeVolume': (delta) => controllers.playback().changeVolume(delta),
'setVolume': (vol) => controllers.playback.setVolume(vol), 'setVolume': (vol) => controllers.playback().setVolume(vol),
'openItem': (infoHash, index) => controllers.playback.openItem(infoHash, index), 'openItem': (infoHash, index) => controllers.playback().openItem(infoHash, index),
// Subtitles // Subtitles
'openSubtitles': () => controllers.subtitles.openSubtitles(), 'openSubtitles': () => controllers.subtitles().openSubtitles(),
'selectSubtitle': (index) => controllers.subtitles.selectSubtitle(index), 'selectSubtitle': (index) => controllers.subtitles().selectSubtitle(index),
'toggleSubtitlesMenu': () => controllers.subtitles.toggleSubtitlesMenu(), 'toggleSubtitlesMenu': () => controllers.subtitles().toggleSubtitlesMenu(),
'checkForSubtitles': () => controllers.subtitles.checkForSubtitles(), 'checkForSubtitles': () => controllers.subtitles().checkForSubtitles(),
'addSubtitles': (files, autoSelect) => controllers.subtitles.addSubtitles(files, autoSelect), 'addSubtitles': (files, autoSelect) => controllers.subtitles().addSubtitles(files, autoSelect),
// Local media: <video>, <audio>, external players // Local media: <video>, <audio>, external players
'mediaStalled': () => controllers.media.mediaStalled(), 'mediaStalled': () => controllers.media().mediaStalled(),
'mediaError': (err) => controllers.media.mediaError(err), 'mediaError': (err) => controllers.media().mediaError(err),
'mediaSuccess': () => controllers.media.mediaSuccess(), 'mediaSuccess': () => controllers.media().mediaSuccess(),
'mediaTimeUpdate': () => controllers.media.mediaTimeUpdate(), 'mediaTimeUpdate': () => controllers.media().mediaTimeUpdate(),
'mediaMouseMoved': () => controllers.media.mediaMouseMoved(), 'mediaMouseMoved': () => controllers.media().mediaMouseMoved(),
'openExternalPlayer': () => controllers.media.openExternalPlayer(), 'mediaControlsMouseEnter': () => controllers.media().controlsMouseEnter(),
'externalPlayerNotFound': () => controllers.media.externalPlayerNotFound(), 'mediaControlsMouseLeave': () => controllers.media().controlsMouseLeave(),
'openExternalPlayer': () => controllers.media().openExternalPlayer(),
'externalPlayerNotFound': () => controllers.media().externalPlayerNotFound(),
// Remote casting: Chromecast, Airplay, etc // Remote casting: Chromecast, Airplay, etc
'toggleCastMenu': (deviceType) => lazyLoadCast().toggleMenu(deviceType), 'toggleCastMenu': (deviceType) => lazyLoadCast().toggleMenu(deviceType),
@@ -226,13 +281,13 @@ const dispatchHandlers = {
'stopCasting': () => lazyLoadCast().stop(), 'stopCasting': () => lazyLoadCast().stop(),
// Preferences screen // Preferences screen
'preferences': () => controllers.prefs.show(), 'preferences': () => controllers.prefs().show(),
'updatePreferences': (key, value) => controllers.prefs.update(key, value), 'updatePreferences': (key, value) => controllers.prefs().update(key, value),
'checkDownloadPath': checkDownloadPath, 'checkDownloadPath': checkDownloadPath,
// Update (check for new versions on Linux, where there's no auto updater) // Update (check for new versions on Linux, where there's no auto updater)
'updateAvailable': (version) => controllers.update.updateAvailable(version), 'updateAvailable': (version) => controllers.update().updateAvailable(version),
'skipVersion': (version) => controllers.update.skipVersion(version), 'skipVersion': (version) => controllers.update().skipVersion(version),
// Navigation between screens (back, forward, ESC, etc) // Navigation between screens (back, forward, ESC, etc)
'exitModal': () => { state.modal = null }, 'exitModal': () => { state.modal = null },
@@ -252,8 +307,8 @@ const dispatchHandlers = {
'onOpen': onOpen, 'onOpen': onOpen,
'error': onError, 'error': onError,
'uncaughtError': (proc, err) => telemetry.logUncaughtError(proc, err), 'uncaughtError': (proc, err) => telemetry.logUncaughtError(proc, err),
'saveState': () => State.save(state), 'stateSave': () => State.save(state),
'saveStateThrottled': () => State.saveThrottled(state), 'stateSaveImmediate': () => State.saveImmediate(state),
'update': () => {} // No-op, just trigger an update 'update': () => {} // No-op, just trigger an update
} }
@@ -270,7 +325,7 @@ function dispatch (action, ...args) {
// Update the virtual DOM, unless it's just a mouse move event // Update the virtual DOM, unless it's just a mouse move event
if (action !== 'mediaMouseMoved' || if (action !== 'mediaMouseMoved' ||
controllers.playback.showOrHidePlayerControls()) { controllers.playback().showOrHidePlayerControls()) {
update() update()
} }
} }
@@ -283,8 +338,9 @@ function setupIpc () {
ipcRenderer.on('dispatch', (e, ...args) => dispatch(...args)) ipcRenderer.on('dispatch', (e, ...args) => dispatch(...args))
ipcRenderer.on('fullscreenChanged', onFullscreenChanged) ipcRenderer.on('fullscreenChanged', onFullscreenChanged)
ipcRenderer.on('windowBoundsChanged', onWindowBoundsChanged)
const tc = controllers.torrent const tc = controllers.torrent()
ipcRenderer.on('wt-infohash', (e, ...args) => tc.torrentInfoHash(...args)) ipcRenderer.on('wt-infohash', (e, ...args) => tc.torrentInfoHash(...args))
ipcRenderer.on('wt-metadata', (e, ...args) => tc.torrentMetadata(...args)) ipcRenderer.on('wt-metadata', (e, ...args) => tc.torrentMetadata(...args))
ipcRenderer.on('wt-done', (e, ...args) => tc.torrentDone(...args)) ipcRenderer.on('wt-done', (e, ...args) => tc.torrentDone(...args))
@@ -302,7 +358,7 @@ function setupIpc () {
ipcRenderer.send('ipcReady') ipcRenderer.send('ipcReady')
State.on('savedState', () => ipcRenderer.send('savedState')) State.on('stateSaved', () => ipcRenderer.send('stateSaved'))
} }
// Quits any modal popovers and returns to the torrent list screen // Quits any modal popovers and returns to the torrent list screen
@@ -337,7 +393,7 @@ function resumeTorrents () {
return torrentSummary return torrentSummary
}) })
.filter((s) => s.status !== 'paused') .filter((s) => s.status !== 'paused')
.forEach((s) => controllers.torrentList.startTorrentingSummary(s.torrentKey)) .forEach((s) => controllers.torrentList().startTorrentingSummary(s.torrentKey))
} }
// Set window dimensions to match video dimensions or fill the screen // Set window dimensions to match video dimensions or fill the screen
@@ -386,20 +442,20 @@ function onOpen (files) {
const url = state.location.url() const url = state.location.url()
const allTorrents = files.every(TorrentPlayer.isTorrent) const allTorrents = files.every(TorrentPlayer.isTorrent)
const allSubtitles = files.every(controllers.subtitles.isSubtitle) const allSubtitles = files.every(controllers.subtitles().isSubtitle)
if (allTorrents) { if (allTorrents) {
// Drop torrents onto the app: go to home screen, add torrents, no matter what // Drop torrents onto the app: go to home screen, add torrents, no matter what
dispatch('backToList') dispatch('backToList')
// All .torrent files? Add them. // All .torrent files? Add them.
files.forEach((file) => controllers.torrentList.addTorrent(file)) files.forEach((file) => controllers.torrentList().addTorrent(file))
} else if (url === 'player' && allSubtitles) { } else if (url === 'player' && allSubtitles) {
// Drop subtitles onto a playing video: add subtitles // Drop subtitles onto a playing video: add subtitles
controllers.subtitles.addSubtitles(files, true) controllers.subtitles().addSubtitles(files, true)
} else if (url === 'home') { } else if (url === 'home') {
// Drop files onto home screen: show Create Torrent // Drop files onto home screen: show Create Torrent
state.modal = null state.modal = null
controllers.torrentList.showCreateTorrent(files) controllers.torrentList().showCreateTorrent(files)
} else { } else {
// Drop files onto any other screen: show error // Drop files onto any other screen: show error
return onError('Please go back to the torrent list before creating a new torrent.') return onError('Please go back to the torrent list before creating a new torrent.')
@@ -421,13 +477,7 @@ function onError (err) {
function onPaste (e) { function onPaste (e) {
if (e.target.tagName.toLowerCase() === 'input') return if (e.target.tagName.toLowerCase() === 'input') return
controllers.torrentList().addTorrent(electron.clipboard.readText())
const torrentIds = electron.clipboard.readText().split('\n')
torrentIds.forEach(function (torrentId) {
torrentId = torrentId.trim()
if (torrentId.length === 0) return
controllers.torrentList.addTorrent(torrentId)
})
update() update()
} }
@@ -457,6 +507,13 @@ function onFullscreenChanged (e, isFullScreen) {
update() update()
} }
function onWindowBoundsChanged (e, newBounds) {
if (state.location.url() !== 'player') {
state.saved.bounds = newBounds
dispatch('stateSave')
}
}
function checkDownloadPath () { function checkDownloadPath () {
fs.stat(state.saved.prefs.downloadPath, function (err, stat) { fs.stat(state.saved.prefs.downloadPath, function (err, stat) {
if (err) { if (err) {

View File

@@ -1,39 +1,48 @@
const colors = require('material-ui/styles/colors') const colors = require('material-ui/styles/colors')
const createGetter = require('fn-getter')
const React = require('react') const React = require('react')
const darkBaseTheme = require('material-ui/styles/baseThemes/darkBaseTheme').default const darkBaseTheme = require('material-ui/styles/baseThemes/darkBaseTheme').default
const lightBaseTheme = require('material-ui/styles/baseThemes/lightBaseTheme').default
const getMuiTheme = require('material-ui/styles/getMuiTheme').default const getMuiTheme = require('material-ui/styles/getMuiTheme').default
const MuiThemeProvider = require('material-ui/styles/MuiThemeProvider').default const MuiThemeProvider = require('material-ui/styles/MuiThemeProvider').default
const Header = require('../components/header') const Header = require('../components/header')
// Perf optimization: Needed immediately, so do not lazy load it below
const TorrentListPage = require('./torrent-list-page')
const Views = { const Views = {
'home': require('./torrent-list-page'), 'home': createGetter(() => TorrentListPage),
'player': require('./player-page'), 'player': createGetter(() => require('./player-page')),
'create-torrent': require('./create-torrent-page'), 'create-torrent': createGetter(() => require('./create-torrent-page')),
'preferences': require('./preferences-page') 'preferences': createGetter(() => require('./preferences-page'))
} }
const Modals = { const Modals = {
'open-torrent-address-modal': require('../components/open-torrent-address-modal'), 'open-torrent-address-modal': createGetter(
'remove-torrent-modal': require('../components/remove-torrent-modal'), () => require('../components/open-torrent-address-modal')
'update-available-modal': require('../components/update-available-modal'), ),
'unsupported-media-modal': require('../components/unsupported-media-modal') 'remove-torrent-modal': createGetter(() => require('../components/remove-torrent-modal')),
'update-available-modal': createGetter(() => require('../components/update-available-modal')),
'unsupported-media-modal': createGetter(() => require('../components/unsupported-media-modal'))
} }
const fontFamily = process.platform === 'win32' const fontFamily = process.platform === 'win32'
? '"Segoe UI", sans-serif' ? '"Segoe UI", sans-serif'
: 'BlinkMacSystemFont, "Helvetica Neue", Helvetica, sans-serif' : 'BlinkMacSystemFont, "Helvetica Neue", Helvetica, sans-serif'
lightBaseTheme.fontFamily = fontFamily
darkBaseTheme.fontFamily = fontFamily darkBaseTheme.fontFamily = fontFamily
darkBaseTheme.palette.primary1Color = colors.cyan500 darkBaseTheme.userAgent = false
darkBaseTheme.palette.primary2Color = colors.cyan500 darkBaseTheme.palette.primary1Color = colors.grey50
darkBaseTheme.palette.primary2Color = colors.grey50
darkBaseTheme.palette.primary3Color = colors.grey600 darkBaseTheme.palette.primary3Color = colors.grey600
darkBaseTheme.palette.accent1Color = colors.redA200 darkBaseTheme.palette.accent1Color = colors.redA200
darkBaseTheme.palette.accent2Color = colors.redA400 darkBaseTheme.palette.accent2Color = colors.redA400
darkBaseTheme.palette.accent3Color = colors.redA100 darkBaseTheme.palette.accent3Color = colors.redA100
let darkMuiTheme
let lightMuiTheme
class App extends React.Component { class App extends React.Component {
render () { render () {
const state = this.props.state const state = this.props.state
@@ -43,12 +52,7 @@ class App extends React.Component {
// * The mouse is over the controls or we're scrubbing (see CSS) // * The mouse is over the controls or we're scrubbing (see CSS)
// * The video is paused // * The video is paused
// * The video is playing remotely on Chromecast or Airplay // * The video is playing remotely on Chromecast or Airplay
const hideControls = state.location.url() === 'player' && const hideControls = state.shouldHidePlayerControls()
state.playing.mouseStationarySince !== 0 &&
new Date().getTime() - state.playing.mouseStationarySince > 2000 &&
!state.playing.isPaused &&
state.playing.location === 'local' &&
state.playing.playbackRate === 1
const cls = [ const cls = [
'view-' + state.location.url(), /* e.g. view-home, view-player */ 'view-' + state.location.url(), /* e.g. view-home, view-player */
@@ -58,8 +62,12 @@ class App extends React.Component {
if (state.window.isFocused) cls.push('is-focused') if (state.window.isFocused) cls.push('is-focused')
if (hideControls) cls.push('hide-video-controls') if (hideControls) cls.push('hide-video-controls')
const vdom = ( if (!darkMuiTheme) {
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> darkMuiTheme = getMuiTheme(darkBaseTheme)
}
return (
<MuiThemeProvider muiTheme={darkMuiTheme}>
<div className={'app ' + cls.join(' ')}> <div className={'app ' + cls.join(' ')}>
<Header state={state} /> <Header state={state} />
{this.getErrorPopover()} {this.getErrorPopover()}
@@ -68,8 +76,6 @@ class App extends React.Component {
</div> </div>
</MuiThemeProvider> </MuiThemeProvider>
) )
return vdom
} }
getErrorPopover () { getErrorPopover () {
@@ -93,9 +99,17 @@ class App extends React.Component {
getModal () { getModal () {
const state = this.props.state const state = this.props.state
if (!state.modal) return if (!state.modal) return
const ModalContents = Modals[state.modal.id]
if (!lightMuiTheme) {
const lightBaseTheme = require('material-ui/styles/baseThemes/lightBaseTheme').default
lightBaseTheme.fontFamily = fontFamily
lightBaseTheme.userAgent = false
lightMuiTheme = getMuiTheme(lightBaseTheme)
}
const ModalContents = Modals[state.modal.id]()
return ( return (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}> <MuiThemeProvider muiTheme={lightMuiTheme}>
<div key='modal' className='modal'> <div key='modal' className='modal'>
<div key='modal-background' className='modal-background' /> <div key='modal-background' className='modal-background' />
<div key='modal-content' className='modal-content'> <div key='modal-content' className='modal-content'>
@@ -108,7 +122,7 @@ class App extends React.Component {
getView () { getView () {
const state = this.props.state const state = this.props.state
const View = Views[state.location.url()] const View = Views[state.location.url()]()
return (<View state={state} />) return (<View state={state} />)
} }
} }

View File

@@ -99,14 +99,14 @@ class CreateTorrentPage extends React.Component {
</ShowMore> </ShowMore>
<div className='float-right'> <div className='float-right'>
<FlatButton <FlatButton
className='control' className='control cancel'
label='Cancel' label='Cancel'
style={{ style={{
marginRight: 10 marginRight: 10
}} }}
onClick={dispatcher('cancel')} /> onClick={dispatcher('cancel')} />
<RaisedButton <RaisedButton
className='control' className='control create-torrent-button'
label='Create Torrent' label='Create Torrent'
primary primary
onClick={this.handleSubmit} /> onClick={this.handleSubmit} />

View File

@@ -2,11 +2,11 @@ const React = require('react')
const Bitfield = require('bitfield') const Bitfield = require('bitfield')
const prettyBytes = require('prettier-bytes') const prettyBytes = require('prettier-bytes')
const zeroFill = require('zero-fill') const zeroFill = require('zero-fill')
const path = require('path')
const TorrentSummary = require('../lib/torrent-summary') const TorrentSummary = require('../lib/torrent-summary')
const Playlist = require('../lib/playlist') const Playlist = require('../lib/playlist')
const {dispatch, dispatcher} = require('../lib/dispatcher') const {dispatch, dispatcher} = require('../lib/dispatcher')
const config = require('../../config')
// Shows a streaming video player. Standard features + Chromecast + Airplay // Shows a streaming video player. Standard features + Chromecast + Airplay
module.exports = class Player extends React.Component { module.exports = class Player extends React.Component {
@@ -26,6 +26,15 @@ module.exports = class Player extends React.Component {
</div> </div>
) )
} }
onComponentWillUnmount () {
// Unload the media element so that Chromium stops trying to fetch data
const tag = document.querySelector('audio,video')
if (!tag) return
tag.pause()
tag.src = ''
tag.load()
}
} }
// Handles volume change by wheel // Handles volume change by wheel
@@ -289,11 +298,8 @@ function renderCastScreen (state) {
castType = 'DLNA' castType = 'DLNA'
isCast = true isCast = true
} else if (state.playing.location === 'external') { } else if (state.playing.location === 'external') {
// TODO: get the player name in a more reliable way
const playerPath = state.saved.prefs.externalPlayerPath
const playerName = playerPath ? path.basename(playerPath).split('.')[0] : 'VLC'
castIcon = 'tv' castIcon = 'tv'
castType = playerName castType = state.getExternalPlayerName()
isCast = false isCast = false
} else if (state.playing.location === 'error') { } else if (state.playing.location === 'error') {
castIcon = 'error_outline' castIcon = 'error_outline'
@@ -432,7 +438,7 @@ function renderPlayerControls (state) {
] ]
if (state.playing.type === 'video') { if (state.playing.type === 'video') {
// show closed captions icon // Show closed captions icon
elements.push(( elements.push((
<i <i
key='subtitles' key='subtitles'
@@ -500,8 +506,6 @@ function renderPlayerControls (state) {
'color-stop(' + (volume * 100) + '%, #727272))' 'color-stop(' + (volume * 100) + '%, #727272))'
} }
// TODO: dcposch change the range input to use value / onChanged instead of
// "readonly" / onMouse[Down,Move,Up]
elements.push(( elements.push((
<div key='volume' className='volume float-left'> <div key='volume' className='volume float-left'>
<i <i
@@ -527,7 +531,7 @@ function renderPlayerControls (state) {
</span> </span>
)) ))
// render playback rate // Render playback rate
if (state.playing.playbackRate !== 1) { if (state.playing.playbackRate !== 1) {
elements.push(( elements.push((
<span key='rate' className='rate float-left'> <span key='rate' className='rate float-left'>
@@ -537,7 +541,9 @@ function renderPlayerControls (state) {
} }
return ( return (
<div key='controls' className='controls'> <div key='controls' className='controls'
onMouseEnter={dispatcher('mediaControlsMouseEnter')}
onMouseLeave={dispatcher('mediaControlsMouseLeave')}>
{elements} {elements}
{renderCastOptions(state)} {renderCastOptions(state)}
{renderSubtitleOptions(state)} {renderSubtitleOptions(state)}
@@ -589,14 +595,19 @@ function renderPlayerControls (state) {
// 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) {
if (config.IS_TEST) return // Don't integration test the loading bar. Screenshots won't match.
const torrentSummary = state.getPlayingTorrentSummary() const torrentSummary = state.getPlayingTorrentSummary()
if (!torrentSummary.progress) { if (!torrentSummary.progress) {
return [] return null
} }
// Find all contiguous parts of the torrent which are loaded // Find all contiguous parts of the torrent which are loaded
const prog = torrentSummary.progress const prog = torrentSummary.progress
const fileProg = prog.files[state.playing.fileIndex] const fileProg = prog.files[state.playing.fileIndex]
if (!fileProg) return null
const parts = [] const parts = []
let lastPiecePresent = false let lastPiecePresent = false
for (let i = fileProg.startPiece; i <= fileProg.endPiece; i++) { for (let i = fileProg.startPiece; i <= fileProg.endPiece; i++) {
@@ -618,6 +629,7 @@ function renderLoadingBar (state) {
return (<div key={i} className='loading-bar-part' style={style} />) return (<div key={i} className='loading-bar-part' style={style} />)
}) })
return (<div key='loading-bar' className='loading-bar'>{loadingBarElems}</div>) return (<div key='loading-bar' className='loading-bar'>{loadingBarElems}</div>)
} }

View File

@@ -1,13 +1,14 @@
const colors = require('material-ui/styles/colors')
const path = require('path') const path = require('path')
const React = require('react') const React = require('react')
const colors = require('material-ui/styles/colors')
const Checkbox = require('material-ui/Checkbox').default const Checkbox = require('material-ui/Checkbox').default
const RaisedButton = require('material-ui/RaisedButton').default
const Heading = require('../components/heading') const Heading = require('../components/heading')
const PathSelector = require('../components/path-selector') const PathSelector = require('../components/path-selector')
const RaisedButton = require('material-ui/RaisedButton').default
const {dispatch} = require('../lib/dispatcher') const {dispatch} = require('../lib/dispatcher')
const config = require('../../config')
class PreferencesPage extends React.Component { class PreferencesPage extends React.Component {
constructor (props) { constructor (props) {
@@ -21,6 +22,9 @@ class PreferencesPage extends React.Component {
this.handleExternalPlayerPathChange = this.handleExternalPlayerPathChange =
this.handleExternalPlayerPathChange.bind(this) this.handleExternalPlayerPathChange.bind(this)
this.handleStartupChange =
this.handleStartupChange.bind(this)
} }
downloadPathSelector () { downloadPathSelector () {
@@ -59,14 +63,12 @@ class PreferencesPage extends React.Component {
} }
externalPlayerPathSelector () { externalPlayerPathSelector () {
const playerName = path.basename( const playerPath = this.props.state.unsaved.prefs.externalPlayerPath
this.props.state.unsaved.prefs.externalPlayerPath || 'VLC' const playerName = this.props.state.getExternalPlayerName()
)
const description = this.props.state.unsaved.prefs.openExternalPlayer const description = this.props.state.unsaved.prefs.openExternalPlayer
? `Torrent media files will always play in ${playerName}.` ? `Torrent media files will always play in ${playerName}.`
: `Torrent media files will play in ${playerName} if WebTorrent cannot ` + : `Torrent media files will play in ${playerName} if WebTorrent cannot play them.`
'play them.'
return ( return (
<Preference> <Preference>
@@ -79,16 +81,12 @@ class PreferencesPage extends React.Component {
displayValue={playerName} displayValue={playerName}
onChange={this.handleExternalPlayerPathChange} onChange={this.handleExternalPlayerPathChange}
title='External player' title='External player'
value={this.props.state.unsaved.prefs.externalPlayerPath} /> value={playerPath ? path.dirname(playerPath) : null} />
</Preference> </Preference>
) )
} }
handleExternalPlayerPathChange (filePath) { handleExternalPlayerPathChange (filePath) {
if (path.extname(filePath) === '.app') {
// Mac: Use executable in packaged .app bundle
filePath += '/Contents/MacOS/' + path.basename(filePath, '.app')
}
dispatch('updatePreferences', 'externalPlayerPath', filePath) dispatch('updatePreferences', 'externalPlayerPath', filePath)
} }
@@ -112,6 +110,29 @@ class PreferencesPage extends React.Component {
) )
} }
handleStartupChange (e, isChecked) {
dispatch('updatePreferences', 'startup', isChecked)
}
setStartupSection () {
if (config.IS_PORTABLE) {
return
}
return (
<PreferencesSection title='Startup'>
<Preference>
<Checkbox
className='control'
checked={this.props.state.unsaved.prefs.startup}
label={'Open WebTorrent on startup.'}
onCheck={this.handleStartupChange}
/>
</Preference>
</PreferencesSection>
)
}
handleSetDefaultApp () { handleSetDefaultApp () {
dispatch('updatePreferences', 'isFileHandler', true) dispatch('updatePreferences', 'isFileHandler', true)
} }
@@ -134,6 +155,7 @@ class PreferencesPage extends React.Component {
<PreferencesSection title='Default torrent app'> <PreferencesSection title='Default torrent app'>
{this.setDefaultAppButton()} {this.setDefaultAppButton()}
</PreferencesSection> </PreferencesSection>
{this.setStartupSection()}
</div> </div>
) )
} }

View File

@@ -1,6 +1,9 @@
const React = require('react') const React = require('react')
const prettyBytes = require('prettier-bytes') const prettyBytes = require('prettier-bytes')
const Checkbox = require('material-ui/Checkbox').default
const LinearProgress = require('material-ui/LinearProgress').default
const TorrentSummary = require('../lib/torrent-summary') const TorrentSummary = require('../lib/torrent-summary')
const TorrentPlayer = require('../lib/torrent-player') const TorrentPlayer = require('../lib/torrent-player')
const {dispatcher} = require('../lib/dispatcher') const {dispatcher} = require('../lib/dispatcher')
@@ -46,7 +49,7 @@ module.exports = class TorrentList extends React.Component {
// 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
const style = {} const style = {}
if (torrentSummary.posterFileName) { if (torrentSummary.posterFileName) {
const gradient = 'linear-gradient(to bottom, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0) 100%)' const gradient = 'linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%)'
const posterPath = TorrentSummary.getPosterPath(torrentSummary) const posterPath = TorrentSummary.getPosterPath(torrentSummary)
style.backgroundImage = `${gradient}, url('${posterPath}')` style.backgroundImage = `${gradient}, url('${posterPath}')`
} }
@@ -54,13 +57,12 @@ module.exports = class TorrentList extends React.Component {
// Foreground: name of the torrent, basic info like size, play button, // Foreground: name of the torrent, basic info like size, play button,
// cast buttons if available, and delete // cast buttons if available, and delete
const classes = ['torrent'] const classes = ['torrent']
// playStatus turns the play button into a loading spinner or error icon
if (torrentSummary.playStatus) classes.push(torrentSummary.playStatus)
if (isSelected) classes.push('selected') if (isSelected) classes.push('selected')
if (!infoHash) classes.push('disabled') if (!infoHash) classes.push('disabled')
if (!torrentSummary.torrentKey) throw new Error('Missing torrentKey') if (!torrentSummary.torrentKey) throw new Error('Missing torrentKey')
return ( return (
<div <div
id={torrentSummary.testID && ('torrent-' + torrentSummary.testID)}
key={torrentSummary.torrentKey} key={torrentSummary.torrentKey}
style={style} style={style}
className={classes.join(' ')} className={classes.join(' ')}
@@ -69,6 +71,7 @@ module.exports = class TorrentList extends React.Component {
{this.renderTorrentMetadata(torrentSummary)} {this.renderTorrentMetadata(torrentSummary)}
{infoHash ? this.renderTorrentButtons(torrentSummary) : null} {infoHash ? this.renderTorrentButtons(torrentSummary) : null}
{isSelected ? this.renderTorrentDetails(torrentSummary) : null} {isSelected ? this.renderTorrentDetails(torrentSummary) : null}
<hr />
</div> </div>
) )
} }
@@ -82,31 +85,72 @@ module.exports = class TorrentList extends React.Component {
// If it's downloading/seeding then show progress info // If it's downloading/seeding then show progress info
const prog = torrentSummary.progress const prog = torrentSummary.progress
let progElems
if (torrentSummary.error) { if (torrentSummary.error) {
elements.push( progElems = [getErrorMessage(torrentSummary)]
<div key='progress-info' className='ellipsis'>
{getErrorMessage(torrentSummary)}
</div>
)
} else if (torrentSummary.status !== 'paused' && prog) { } else if (torrentSummary.status !== 'paused' && prog) {
elements.push( progElems = [
<div key='progress-info' className='ellipsis'> renderDownloadCheckbox(),
{renderProgressBar()} renderTorrentStatus(),
{renderPercentProgress()} renderProgressBar(),
{renderTotalProgress()} renderPercentProgress(),
{renderPeers()} renderTotalProgress(),
{renderDownloadSpeed()} renderPeers(),
{renderUploadSpeed()} renderSpeeds(),
{renderEta()} renderEta()
</div> ]
) } else {
progElems = [
renderDownloadCheckbox(),
renderTorrentStatus()
]
} }
elements.push(
<div key='progress-info' className='ellipsis'>
{progElems}
</div>
)
return (<div key='metadata' className='metadata'>{elements}</div>) return (<div key='metadata' className='metadata'>{elements}</div>)
function renderDownloadCheckbox () {
const infoHash = torrentSummary.infoHash
const isActive = ['downloading', 'seeding'].includes(torrentSummary.status)
return (
<Checkbox
key='download-button'
className={'control download ' + torrentSummary.status}
style={{
display: 'inline-block',
width: 32
}}
iconStyle={{
width: 20,
height: 20
}}
checked={isActive}
onClick={stopPropagation}
onCheck={dispatcher('toggleTorrent', infoHash)} />
)
}
function renderProgressBar () { function renderProgressBar () {
const progress = Math.floor(100 * prog.progress) const progress = Math.floor(100 * prog.progress)
return (<progress value={progress} max='100'>{progress}%</progress>) const styles = {
wrapper: {
display: 'inline-block',
marginRight: 8
},
progress: {
height: 8,
width: 30
}
}
return (
<div style={styles.wrapper}>
<LinearProgress style={styles.progress} mode='determinate' value={progress} />
</div>
)
} }
function renderPercentProgress () { function renderPercentProgress () {
@@ -130,14 +174,12 @@ module.exports = class TorrentList extends React.Component {
return (<span key='peers'>{prog.numPeers} {count}</span>) return (<span key='peers'>{prog.numPeers} {count}</span>)
} }
function renderDownloadSpeed () { function renderSpeeds () {
if (prog.downloadSpeed === 0) return let str = ''
return (<span key='download'> {prettyBytes(prog.downloadSpeed)}/s</span>) if (prog.downloadSpeed > 0) str += ' ↓ ' + prettyBytes(prog.downloadSpeed) + '/s'
} if (prog.uploadSpeed > 0) str += ' ↑ ' + prettyBytes(prog.uploadSpeed) + '/s'
if (str === '') return
function renderUploadSpeed () { return (<span key='download'>{str}</span>)
if (prog.uploadSpeed === 0) return
return (<span key='upload'> {prettyBytes(prog.uploadSpeed)}/s</span>)
} }
function renderEta () { function renderEta () {
@@ -158,7 +200,23 @@ module.exports = class TorrentList extends React.Component {
const minutesStr = (hours || minutes) ? minutes + 'm' : '' const minutesStr = (hours || minutes) ? minutes + 'm' : ''
const secondsStr = seconds + 's' const secondsStr = seconds + 's'
return (<span>ETA: {hoursStr} {minutesStr} {secondsStr}</span>) return (<span>{hoursStr} {minutesStr} {secondsStr} remaining</span>)
}
function renderTorrentStatus () {
let status
if (torrentSummary.status === 'paused') {
if (!torrentSummary.progress) status = ''
else if (torrentSummary.progress.progress === 1) status = 'Not seeding'
else status = 'Paused'
} else if (torrentSummary.status === 'downloading') {
status = 'Downloading'
} else if (torrentSummary.status === 'seeding') {
status = 'Seeding'
} else { // torrentSummary.status is 'new' or something unexpected
status = ''
}
return (<span>{status}</span>)
} }
} }
@@ -167,69 +225,23 @@ module.exports = class TorrentList extends React.Component {
renderTorrentButtons (torrentSummary) { renderTorrentButtons (torrentSummary) {
const infoHash = torrentSummary.infoHash const infoHash = torrentSummary.infoHash
let playIcon, playTooltip, playClass
if (torrentSummary.playStatus === 'timeout') {
playIcon = 'warning'
playTooltip = 'Playback timed out. No seeds? No internet? Click to try again.'
} else {
playIcon = 'play_arrow'
playTooltip = 'Start streaming'
}
let downloadIcon, downloadTooltip
if (torrentSummary.status === 'seeding') {
downloadIcon = 'file_upload'
downloadTooltip = 'Seeding. Click to stop.'
} else if (torrentSummary.status === 'downloading') {
downloadIcon = 'file_download'
downloadTooltip = 'Torrenting. Click to stop.'
} else {
downloadIcon = 'file_download'
downloadTooltip = 'Click to start torrenting.'
}
// Only show the play/dowload buttons for torrents that contain playable media // Only show the play/dowload buttons for torrents that contain playable media
let playButton, downloadButton, positionElem let playButton
if (!torrentSummary.error) { if (!torrentSummary.error && TorrentPlayer.isPlayableTorrentSummary(torrentSummary)) {
downloadButton = ( playButton = (
<i <i
key='download-button' key='play-button'
className={'button-round icon download ' + torrentSummary.status} title='Start streaming'
title={downloadTooltip} className={'icon play'}
onClick={dispatcher('toggleTorrent', infoHash)}> onClick={dispatcher('playFile', infoHash)}>
{downloadIcon} play_circle_outline
</i> </i>
) )
// Do we have a saved position? Show it using a radial progress bar on top
// of the play button, unless already showing a spinner there:
const willShowSpinner = torrentSummary.playStatus === 'requested'
const mostRecentFile = torrentSummary.files &&
torrentSummary.files[torrentSummary.mostRecentFileIndex]
if (mostRecentFile && mostRecentFile.currentTime && !willShowSpinner) {
const fraction = mostRecentFile.currentTime / mostRecentFile.duration
positionElem = this.renderRadialProgressBar(fraction, 'radial-progress-large')
playClass = 'resume-position'
}
if (TorrentPlayer.isPlayableTorrentSummary(torrentSummary)) {
playButton = (
<i
key='play-button'
title={playTooltip}
className={'button-round icon play ' + playClass}
onClick={dispatcher('playFile', infoHash)}>
{playIcon}
</i>
)
}
} }
return ( return (
<div key='buttons' className='buttons'> <div className='torrent-controls'>
{positionElem}
{playButton} {playButton}
{downloadButton}
<i <i
key='delete-button' key='delete-button'
className='icon delete' className='icon delete'
@@ -345,7 +357,7 @@ module.exports = class TorrentList extends React.Component {
</td> </td>
<td className='col-select' <td className='col-select'
onClick={dispatcher('toggleTorrentFile', infoHash, index)}> onClick={dispatcher('toggleTorrentFile', infoHash, index)}>
<i className='icon'>{isSelected ? 'close' : 'add'}</i> <i className='icon deselect-file'>{isSelected ? 'close' : 'add'}</i>
</td> </td>
</tr> </tr>
) )
@@ -373,6 +385,10 @@ module.exports = class TorrentList extends React.Component {
} }
} }
function stopPropagation (e) {
e.stopPropagation()
}
function getErrorMessage (torrentSummary) { function getErrorMessage (torrentSummary) {
const err = torrentSummary.error const err = torrentSummary.error
if (err === 'path-missing') { if (err === 'path-missing') {

View File

@@ -6,7 +6,8 @@ const crypto = require('crypto')
const deepEqual = require('deep-equal') const deepEqual = require('deep-equal')
const defaultAnnounceList = require('create-torrent').announceList const defaultAnnounceList = require('create-torrent').announceList
const electron = require('electron') const electron = require('electron')
const fs = require('fs-extra') const fs = require('fs')
const mkdirp = require('mkdirp')
const musicmetadata = require('musicmetadata') const musicmetadata = require('musicmetadata')
const networkAddress = require('network-address') const networkAddress = require('network-address')
const path = require('path') const path = require('path')
@@ -15,6 +16,7 @@ const zeroFill = require('zero-fill')
const crashReporter = require('../crash-reporter') const crashReporter = require('../crash-reporter')
const config = require('../config') const config = require('../config')
const {TorrentKeyNotFoundError} = require('./lib/errors')
const torrentPoster = require('./lib/torrent-poster') const torrentPoster = require('./lib/torrent-poster')
// Report when the process crashes // Report when the process crashes
@@ -53,11 +55,14 @@ const VERSION_STR = VERSION.match(/([0-9]+)/g)
*/ */
const VERSION_PREFIX = '-WD' + VERSION_STR + '-' const VERSION_PREFIX = '-WD' + VERSION_STR + '-'
/**
* Generate an ephemeral peer ID each time.
*/
const PEER_ID = Buffer.from(VERSION_PREFIX + crypto.randomBytes(9).toString('base64'))
// Connect to the WebTorrent and BitTorrent networks. WebTorrent Desktop is a hybrid // Connect to the WebTorrent and BitTorrent networks. WebTorrent Desktop is a hybrid
// client, as explained here: https://webtorrent.io/faq // client, as explained here: https://webtorrent.io/faq
const client = window.client = new WebTorrent({ let client = window.client = new WebTorrent({ peerId: PEER_ID })
peerId: Buffer.from(VERSION_PREFIX + crypto.randomBytes(6).toString('hex'))
})
// WebTorrent-to-HTTP streaming sever // WebTorrent-to-HTTP streaming sever
let server = null let server = null
@@ -68,8 +73,7 @@ let prevProgress = null
init() init()
function init () { function init () {
client.on('warning', (err) => ipc.send('wt-warning', null, err.message)) listenToClientEvents()
client.on('error', (err) => ipc.send('wt-error', null, err.message))
ipc.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) => ipc.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) =>
startTorrenting(torrentKey, torrentID, path, fileModtimes, selections)) startTorrenting(torrentKey, torrentID, path, fileModtimes, selections))
@@ -100,6 +104,11 @@ function init () {
console.timeEnd('init') console.timeEnd('init')
} }
function listenToClientEvents () {
client.on('warning', (err) => ipc.send('wt-warning', null, err.message))
client.on('error', (err) => ipc.send('wt-error', null, err.message))
}
// Starts a given TorrentID, which can be an infohash, magnet URI, etc. // Starts a given TorrentID, which can be an infohash, magnet URI, etc.
// Returns a WebTorrent object. See https://git.io/vik9M // Returns a WebTorrent object. See https://git.io/vik9M
function startTorrenting (torrentKey, torrentID, path, fileModtimes, selections) { function startTorrenting (torrentKey, torrentID, path, fileModtimes, selections) {
@@ -116,8 +125,6 @@ function startTorrenting (torrentKey, torrentID, path, fileModtimes, selections)
// Only download the files the user wants, not necessarily all files // Only download the files the user wants, not necessarily all files
torrent.once('ready', () => selectFiles(torrent, selections)) torrent.once('ready', () => selectFiles(torrent, selections))
return torrent
} }
function stopTorrenting (infoHash) { function stopTorrenting (infoHash) {
@@ -156,7 +163,7 @@ function addTorrentEvents (torrent) {
function torrentReady () { function torrentReady () {
const info = getTorrentInfo(torrent) const info = getTorrentInfo(torrent)
ipc.send('wt-ready', torrent.key, info) ipc.send('wt-ready', torrent.key, info)
ipc.send('wt-ready-' + torrent.infoHash, torrent.key, info) // TODO: hack ipc.send('wt-ready-' + torrent.infoHash, torrent.key, info)
updateTorrentProgress() updateTorrentProgress()
} }
@@ -195,19 +202,22 @@ function getTorrentFileInfo (file) {
} }
} }
// Every time we resolve a magnet URI, save the torrent file so that we never // Every time we resolve a magnet URI, save the torrent file so that we can use
// have to download it again. Never ask the DHT the same question twice. // it on next startup. Starting with the full torrent metadata will be faster
// than re-fetching it from peers using ut_metadata.
function saveTorrentFile (torrentKey) { function saveTorrentFile (torrentKey) {
const torrent = getTorrent(torrentKey) const torrent = getTorrent(torrentKey)
checkIfTorrentFileExists(torrent.infoHash, function (torrentPath, exists) { const torrentPath = path.join(config.TORRENT_PATH, torrent.infoHash + '.torrent')
fs.access(torrentPath, fs.constants.R_OK, function (err) {
const fileName = torrent.infoHash + '.torrent' const fileName = torrent.infoHash + '.torrent'
if (exists) { if (!err) {
// We've already saved the file // We've already saved the file
return ipc.send('wt-file-saved', torrentKey, fileName) return ipc.send('wt-file-saved', torrentKey, fileName)
} }
// Otherwise, save the .torrent file, under the app config folder // Otherwise, save the .torrent file, under the app config folder
fs.mkdir(config.TORRENT_PATH, function (_) { mkdirp(config.TORRENT_PATH, function (_) {
fs.writeFile(torrentPath, torrent.torrentFile, function (err) { fs.writeFile(torrentPath, torrent.torrentFile, function (err) {
if (err) return console.log('error saving torrent file %s: %o', torrentPath, err) if (err) return console.log('error saving torrent file %s: %o', torrentPath, err)
console.log('saved torrent file %s', torrentPath) console.log('saved torrent file %s', torrentPath)
@@ -217,15 +227,6 @@ function saveTorrentFile (torrentKey) {
}) })
} }
// Checks whether we've already resolved a given infohash to a torrent file
// Calls back with (torrentPath, exists). Logs, does not call back on error
function checkIfTorrentFileExists (infoHash, cb) {
const torrentPath = path.join(config.TORRENT_PATH, infoHash + '.torrent')
fs.exists(torrentPath, function (exists) {
cb(torrentPath, exists)
})
}
// Save a JPG that represents a torrent. // Save a JPG that represents a torrent.
// Auto chooses either a frame from a video file, an image, etc // Auto chooses either a frame from a video file, an image, etc
function generateTorrentPoster (torrentKey) { function generateTorrentPoster (torrentKey) {
@@ -233,7 +234,7 @@ function generateTorrentPoster (torrentKey) {
torrentPoster(torrent, function (err, buf, extension) { torrentPoster(torrent, function (err, buf, extension) {
if (err) return console.log('error generating poster: %o', err) if (err) return console.log('error generating poster: %o', err)
// save it for next time // save it for next time
fs.mkdirp(config.POSTER_PATH, function (err) { mkdirp(config.POSTER_PATH, function (err) {
if (err) return console.log('error creating poster dir: %o', err) if (err) return console.log('error creating poster dir: %o', err)
const posterFileName = torrent.infoHash + extension const posterFileName = torrent.infoHash + extension
const posterFilePath = path.join(config.POSTER_PATH, posterFileName) const posterFilePath = path.join(config.POSTER_PATH, posterFileName)
@@ -336,9 +337,11 @@ function getAudioMetadata (infoHash, index) {
const torrent = client.get(infoHash) const torrent = client.get(infoHash)
const file = torrent.files[index] const file = torrent.files[index]
musicmetadata(file.createReadStream(), function (err, info) { musicmetadata(file.createReadStream(), function (err, info) {
if (err) return if (err) return console.log('error getting audio metadata for ' + infoHash + ':' + index, err)
console.log('got audio metadata for %s: %o', file.name, info) const { artist, album, albumartist, title, year, track, disk, genre } = info
ipc.send('wt-audio-metadata', infoHash, index, info) const importantInfo = { artist, album, albumartist, title, year, track, disk, genre }
console.log('got audio metadata for %s: %o', file.name, importantInfo)
ipc.send('wt-audio-metadata', infoHash, index, importantInfo)
}) })
} }
@@ -350,6 +353,9 @@ function selectFiles (torrentOrInfoHash, selections) {
} else { } else {
torrent = torrentOrInfoHash torrent = torrentOrInfoHash
} }
if (!torrent) {
throw new Error('selectFiles: missing torrent ' + torrentOrInfoHash)
}
// Selections not specified? // Selections not specified?
// Load all files. We still need to replace the default whole-torrent // Load all files. We still need to replace the default whole-torrent
@@ -384,10 +390,24 @@ function selectFiles (torrentOrInfoHash, selections) {
// Throws an Error if we're not currently torrenting anything w/ that key // Throws an Error if we're not currently torrenting anything w/ that key
function getTorrent (torrentKey) { function getTorrent (torrentKey) {
const ret = client.torrents.find((x) => x.key === torrentKey) const ret = client.torrents.find((x) => x.key === torrentKey)
if (!ret) throw new Error('missing torrent key ' + torrentKey) if (!ret) throw new TorrentKeyNotFoundError(torrentKey)
return ret return ret
} }
function onError (err) { function onError (err) {
console.log(err) console.log(err)
} }
// TODO: remove this once the following bugs are fixed:
// https://bugs.chromium.org/p/chromium/issues/detail?id=490143
// https://github.com/electron/electron/issues/7212
window.testOfflineMode = function () {
console.log('Test, going OFFLINE')
client = window.client = new WebTorrent({
peerId: PEER_ID,
tracker: false,
dht: false,
webSeeds: false
})
listenToClientEvents()
}

View File

@@ -32,6 +32,7 @@
<p> <p>
Version <script>document.write(require('../package.json').version)</script> Version <script>document.write(require('../package.json').version)</script>
(<script>document.write(require('webtorrent/package.json').version)</script>) (<script>document.write(require('webtorrent/package.json').version)</script>)
(<script>document.write(process.arch === 'x64' ? '64-bit' : '32-bit')</script>)
</p> </p>
<p><script>document.write(require('../config').APP_COPYRIGHT)</script></p> <p><script>document.write(require('../config').APP_COPYRIGHT)</script></p>
</body> </body>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -309,15 +309,6 @@ i:not(.disabled):hover { /* Show they're clickable without pointer: cursor */
-webkit-filter: brightness(1.3); -webkit-filter: brightness(1.3);
} }
.button-round { /* Circular icon buttons, used on <i> tags */
width: 40px;
height: 40px;
border-radius: 20px;
font-size: 22px;
transition: all 0.1s ease-out;
text-align: center;
}
/* /*
* INPUTS * INPUTS
*/ */
@@ -347,22 +338,18 @@ textarea,
} }
.torrent:not(:last-child) { .torrent:not(:last-child) {
border-bottom: 1px solid rgb(20, 20, 20); border-bottom: 1px solid #282828;
} }
.torrent .metadata { .torrent .metadata {
position: absolute; position: absolute;
top: 25px; top: 20px;
left: 15px; left: 15px;
right: 15px; right: 15px;
width: calc(100% - 40px); width: calc(100% - 30px);
text-shadow: rgba(0, 0, 0, 0.5) 0 0 4px; text-shadow: rgba(0, 0, 0, 0.5) 0 0 4px;
} }
.torrent:hover .metadata {
width: calc(100% - 150px);
}
.torrent .metadata span:not(:last-child)::after { .torrent .metadata span:not(:last-child)::after {
content: ' • '; content: ' • ';
opacity: 0.7; opacity: 0.7;
@@ -370,79 +357,34 @@ textarea,
padding-right: 4px; padding-right: 4px;
} }
.torrent .buttons { .torrent:hover .metadata {
position: absolute; width: calc(100% - 120px);
top: 29px; }
right: 10px;
align-items: center; .torrent .torrent-controls {
display: none; display: none;
} }
.torrent:hover .buttons { .torrent:hover .torrent-controls {
display: flex; display: block;
} }
.torrent .buttons > * { .torrent .play {
margin-left: 6px; /* space buttons apart */ position: absolute;
top: 23px;
right: 45px;
font-size: 55px;
} }
.torrent .buttons .download { .torrent .delete {
background-color: #2233BB; position: absolute;
width: 28px; top: 38px;
height: 28px; right: 12px;
border-radius: 14px;
font-size: 18px;
padding-top: 6px;
} }
.torrent .buttons .download.downloading { .torrent .download {
color: #44dd44; vertical-align: -0.4em;
} margin-left: -2px;
.torrent .buttons .download.seeding {
color: #44dd44;
}
.torrent .buttons .play {
padding-top: 10px;
background-color: #F44336;
}
.torrent.timeout .play {
padding-top: 8px;
}
.torrent.requested .play,
.loading-spinner {
border-top: 6px solid rgba(255, 255, 255, 0.2);
border-right: 6px solid rgba(255, 255, 255, 0.2);
border-bottom: 6px solid rgba(255, 255, 255, 0.2);
border-left: 6px solid #ffffff;
border-radius: 50%;
color: transparent;
animation: load8 1.1s infinite linear;
}
@keyframes load8 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.torrent .buttons .play.resume-position {
position: relative;
-webkit-clip-path: circle(18px at center);
}
.torrent .buttons .delete {
opacity: 0.5;
}
.torrent .buttons .delete:hover {
opacity: 0.7;
} }
.torrent .buttons .radial-progress { .torrent .buttons .radial-progress {
@@ -450,23 +392,27 @@ textarea,
} }
.torrent .name { .torrent .name {
font-size: 18px; font-size: 20px;
font-weight: bold; font-weight: bold;
line-height: 1.5em; line-height: 1.5em;
margin-bottom: 6px;
} }
progress { .torrent hr {
width: 60px; position: absolute;
margin-right: 8px; bottom: 5px;
-webkit-appearance: none; left: calc(50% - 20px);
width: 40px;
height: 1px;
background: #ccc;
display: none;
margin: 0;
padding: 0;
border: none;
} }
progress::-webkit-progress-bar { .torrent:hover hr {
background-color: #888; display: block;
}
progress::-webkit-progress-value {
background-color: #eee;
} }
/* /*
@@ -690,14 +636,6 @@ body.drag .app::after {
cursor: none; cursor: none;
} }
/* TODO: find better way to handle this (that also
* keeps the header visible too).
*/
.app.hide-video-controls .player .controls:hover {
opacity: 1;
cursor: default;
}
/* invisible click target for scrubbing */ /* invisible click target for scrubbing */
.player .controls .scrub-bar { .player .controls .scrub-bar {
position: absolute; position: absolute;

View File

@@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>WebTorrent Desktop</title> <title>Main Window</title>
<link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="main.css">
</head> </head>
<body> <body>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>WebTorrent Desktop</title> <title>WebTorrent Hidden Window</title>
<style> <style>
body { body {
background-color: #282828; background-color: #282828;

Binary file not shown.

15
test/config.js Normal file
View File

@@ -0,0 +1,15 @@
const path = require('path')
const TEMP_DIR = process.platform === 'win32' ? 'C:\\Windows\\Temp' : '/tmp'
const TEST_DIR = path.join(TEMP_DIR, 'WebTorrentTest')
const TEST_DIR_DOWNLOAD = path.join(TEST_DIR, 'Downloads')
const TEST_DIR_DESKTOP = path.join(TEST_DIR, 'Desktop')
module.exports = {
TORRENT_FILES: [path.join(__dirname, 'resources', '1.torrent')],
SEED_FILES: [path.join(TEST_DIR_DESKTOP, 'tmp.jpg')],
SAVED_TORRENT_FILE: path.join(TEST_DIR_DESKTOP, 'saved.torrent'),
TEST_DIR,
TEST_DIR_DOWNLOAD,
TEST_DIR_DESKTOP
}

19
test/index.js Normal file
View File

@@ -0,0 +1,19 @@
const test = require('tape')
const setup = require('./setup')
test.onFinish(setup.deleteTestDataDir)
test('app runs', function (t) {
t.timeoutAfter(10e3)
setup.resetTestDataDir()
const app = setup.createApp()
setup.waitForLoad(app, t)
.then(() => setup.screenshotCreateOrCompare(app, t, 'app-basic'))
.then(() => setup.endTest(app, t),
(err) => setup.endTest(app, t, err || 'error'))
})
require('./test-torrent-list')
require('./test-add-torrent')
require('./test-video')
require('./test-audio')

15
test/mocks.js Normal file
View File

@@ -0,0 +1,15 @@
const electron = require('electron')
const config = require('./config')
console.log('Mocking electron.dialog.showOpenDialog...')
electron.dialog.showOpenDialog = function (win, opts, cb) {
const ret = /select.*torrent file/i.test(opts.title)
? config.TORRENT_FILES
: config.SEED_FILES
cb(ret)
}
console.log('Mocking electron.remote.dialog.showSaveDialog...')
electron.dialog.showSaveDialog = function (win, opts, cb) {
cb(config.SAVED_TORRENT_FILE)
}

BIN
test/resources/1.torrent Normal file

Binary file not shown.

Binary file not shown.

BIN
test/resources/m3.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1011 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 698 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 480 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 480 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 480 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 481 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 627 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 844 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1014 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 698 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1024 KiB

Some files were not shown because too many files have changed in this diff Show More