pull/152/head
Alex Kern 5 years ago
parent 5c3306b9c6
commit 0dc1b6fa04
No known key found for this signature in database
GPG Key ID: F3141D5EDF48F89F

@ -1,8 +1,9 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: { parserOptions: {
project: './tsconfig.json' project: './tsconfig.json',
}, },
extends: [ extends: [
'@strv/typescript', '@strv/typescript',

@ -0,0 +1,9 @@
'use strict';
module.exports = {
semi: false,
trailingComma: 'all',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
};

@ -0,0 +1,7 @@
import React from 'react';
const DownloadPage = () => {
return <div />
}
export default DownloadPage

@ -1,8 +1,7 @@
import alt from '../alt'; import alt from '../alt'
export default alt.createActions(class DownloadActions { export default alt.createActions(class DownloadActions {
constructor() { constructor() {
this.generateActions('requestDownload'); this.generateActions('requestDownload')
} }
}, })
)

@ -1,8 +1,7 @@
import alt from '../alt'; import alt from '../alt'
export default alt.createActions(class SupportActions { export default alt.createActions(class SupportActions {
constructor() { constructor() {
this.generateActions('isChrome', 'noSupport'); this.generateActions('isChrome', 'noSupport')
} }
}, })
)

@ -1,8 +1,7 @@
import alt from '../alt'; import alt from '../alt'
export default alt.createActions(class UploadActions { export default alt.createActions(class UploadActions {
constructor() { constructor() {
this.generateActions('uploadFile'); this.generateActions('uploadFile')
} }
}, })
)

@ -1,3 +1,3 @@
import Alt from 'alt'; import Alt from 'alt'
export default new Alt() export default new Alt()

@ -1,25 +1,25 @@
import "babel-polyfill"; import 'babel-polyfill'
import "./index.styl"; import './index.styl'
import React from "react"; import React from 'react'
import ReactRouter from "react-router"; import ReactRouter from 'react-router'
import webrtcSupport from 'webrtcsupport'; import webrtcSupport from 'webrtcsupport'
import routes from './routes'; import routes from './routes'
import alt from './alt'; import alt from './alt'
import SupportActions from "./actions/SupportActions"; import SupportActions from './actions/SupportActions'
const bootstrap = document.getElementById("bootstrap").innerHTML; const bootstrap = document.getElementById('bootstrap').innerHTML
alt.bootstrap(bootstrap); alt.bootstrap(bootstrap)
window.FilePizza = () => { window.FilePizza = () => {
ReactRouter.run(routes, ReactRouter.HistoryLocation, Handler => { ReactRouter.run(routes, ReactRouter.HistoryLocation, Handler => {
React.render(<Handler data={bootstrap} />, document); React.render(<Handler data={bootstrap} />, document)
}) })
if (!webrtcSupport.support) { if (!webrtcSupport.support) {
SupportActions.noSupport(); SupportActions.noSupport()
} }
const isChrome = navigator.userAgent.toLowerCase().includes('chrome') const isChrome = navigator.userAgent.toLowerCase().includes('chrome')
;if (isChrome) { if (isChrome) {
SupportActions.isChrome() SupportActions.isChrome()
} }
}; }

@ -1,32 +1,32 @@
import FrozenHead from "react-frozenhead"; import FrozenHead from 'react-frozenhead'
import React from "react"; import React from 'react'
import { RouteHandler } from 'react-router'; import { RouteHandler } from 'react-router'
import ga from 'react-google-analytics'; import ga from 'react-google-analytics'
import SupportStore from '../stores/SupportStore'; import SupportStore from '../stores/SupportStore'
import ErrorPage from "./ErrorPage"; import ErrorPage from './ErrorPage'
import Bootstrap from './Bootstrap'; import Bootstrap from './Bootstrap'
if (process.env.GA_ACCESS_TOKEN) { if (process.env.GA_ACCESS_TOKEN) {
ga("create", process.env.GA_ACCESS_TOKEN, "auto"); ga('create', process.env.GA_ACCESS_TOKEN, 'auto')
;;ga('send', 'pageview') ga('send', 'pageview')
} }
export default class App extends React.Component { export default class App extends React.Component {
constructor() { constructor() {
super(); super()
this.state = SupportStore.getState(); this.state = SupportStore.getState()
this._onChange = () => { this._onChange = () => {
this.setState(SupportStore.getState()); this.setState(SupportStore.getState())
} }
} }
componentDidMount() { componentDidMount() {
SupportStore.listen(this._onChange); SupportStore.listen(this._onChange)
} }
componentWillUnmount() { componentWillUnmount() {
SupportStore.unlisten(this._onChange); SupportStore.unlisten(this._onChange)
} }
render() { render() {
@ -72,19 +72,19 @@ export default class App extends React.Component {
</p> </p>
<p className="byline"> <p className="byline">
Cooked up by{" "} Cooked up by{' '}
<a href="http://kern.io" target="_blank"> <a href="http://kern.io" target="_blank">
Alex Kern Alex Kern
</a>{" "} </a>{' '}
&amp;{" "} &amp;{' '}
<a href="http://neeraj.io" target="_blank"> <a href="http://neeraj.io" target="_blank">
Neeraj Baid Neeraj Baid
</a>{" "} </a>{' '}
while eating <strong>Sliver</strong> @ UC Berkeley &middot;{" "} while eating <strong>Sliver</strong> @ UC Berkeley &middot;{' '}
<a href="https://github.com/kern/filepizza#faq" target="_blank"> <a href="https://github.com/kern/filepizza#faq" target="_blank">
FAQ FAQ
</a>{" "} </a>{' '}
&middot;{" "} &middot;{' '}
<a href="https://github.com/kern/filepizza" target="_blank"> <a href="https://github.com/kern/filepizza" target="_blank">
Fork us Fork us
</a> </a>
@ -94,6 +94,6 @@ export default class App extends React.Component {
{process.env.GA_ACCESS_TOKEN ? <ga.Initializer /> : <div></div>} {process.env.GA_ACCESS_TOKEN ? <ga.Initializer /> : <div></div>}
</body> </body>
</html> </html>
); )
} }
} }

@ -1,4 +1,4 @@
import React from 'react'; import React from 'react'
export default class Bootstrap extends React.Component { export default class Bootstrap extends React.Component {
render() { render() {

@ -1,4 +1,4 @@
import React from 'react'; import React from 'react'
export default class DownloadButton extends React.Component { export default class DownloadButton extends React.Component {
constructor() { constructor() {

@ -1,12 +1,12 @@
import React from "react"; import React from 'react'
import DownloadActions from '../actions/DownloadActions'; import DownloadActions from '../actions/DownloadActions'
import DownloadStore from '../stores/DownloadStore'; import DownloadStore from '../stores/DownloadStore'
import { formatSize } from "../util"; import { formatSize } from '../util'
import ChromeNotice from './ChromeNotice'; import ChromeNotice from './ChromeNotice'
import DownloadButton from "./DownloadButton"; import DownloadButton from './DownloadButton'
import ErrorPage from './ErrorPage'; import ErrorPage from './ErrorPage'
import ProgressBar from './ProgressBar'; import ProgressBar from './ProgressBar'
import Spinner from "./Spinner"; import Spinner from './Spinner'
export default class DownloadPage extends React.Component { export default class DownloadPage extends React.Component {
constructor() { constructor() {
@ -15,7 +15,7 @@ export default class DownloadPage extends React.Component {
this._onChange = () => { this._onChange = () => {
this.setState(DownloadStore.getState()) this.setState(DownloadStore.getState())
}; }
this.downloadFile = this.downloadFile.bind(this) this.downloadFile = this.downloadFile.bind(this)
} }

@ -1,4 +1,4 @@
import React from 'react'; import React from 'react'
export default class DropZone extends React.Component { export default class DropZone extends React.Component {
constructor() { constructor() {
@ -24,7 +24,7 @@ export default class DropZone extends React.Component {
onDragOver(e) { onDragOver(e) {
e.preventDefault() e.preventDefault()
e.dataTransfer.dropEffect = 'copy'; e.dataTransfer.dropEffect = 'copy'
} }
onDrop(e) { onDrop(e) {

@ -1,6 +1,6 @@
import React from "react"; import React from 'react'
import ErrorStore from "../stores/ErrorStore"; import ErrorStore from '../stores/ErrorStore'
import Spinner from './Spinner'; import Spinner from './Spinner'
export default class ErrorPage extends React.Component { export default class ErrorPage extends React.Component {
constructor() { constructor() {
@ -9,7 +9,7 @@ export default class ErrorPage extends React.Component {
this._onChange = () => { this._onChange = () => {
this.setState(ErrorStore.getState()) this.setState(ErrorStore.getState())
}; }
} }
componentDidMount() { componentDidMount() {

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react'
import QRCode from 'react-qr'; import QRCode from 'react-qr'
export default class Tempalink extends React.Component { export default class Tempalink extends React.Component {
constructor() { constructor() {
@ -12,9 +12,8 @@ export default class Tempalink extends React.Component {
} }
render() { render() {
const url = `${window.location.origin}/${this.props.token}`; const url = `${window.location.origin}/${this.props.token}`
const shortUrl const shortUrl = `${window.location.origin}/download/${this.props.shortToken}`
= window.location.origin + '/download/' + this.props.shortToken
return ( return (
<div className="tempalink"> <div className="tempalink">

@ -1,6 +1,6 @@
import Arrow from '@app/components/Arrow'; import Arrow from '@app/components/Arrow'
import React from 'react'; import React from 'react'
import UploadActions from '@app/actions/UploadActions'; import UploadActions from '@app/actions/UploadActions'
export default class UploadPage extends React.Component { export default class UploadPage extends React.Component {
constructor() { constructor() {
@ -9,7 +9,7 @@ export default class UploadPage extends React.Component {
} }
uploadFile(file) { uploadFile(file) {
UploadActions.uploadFile(file); UploadActions.uploadFile(file)
} }
render() { render() {

@ -1,51 +0,0 @@
const twilio = require("twilio");
var winston = require("winston");
if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN) {
const twilioSID = process.env.TWILIO_SID;
const twilioToken = process.env.TWILIO_TOKEN;
var client = twilio(twilioSID, twilioToken);
winston.info("Using Twilio TURN service");
} else {
var client = null;
}
let ICE_SERVERS = [
{
urls: "stun:stun.l.google.com:19302",
},
];
if (process.env.ICE_SERVERS) {
ICE_SERVERS = JSON.parse(process.env.ICE_SERVERS)
}
const CACHE_LIFETIME = 5 * 60 * 1000; // 5 minutes
let cachedPromise = null;
function clearCache() {
cachedPromise = null;
}
exports.getICEServers = function() {
if (client == null) {
return Promise.resolve(ICE_SERVERS)
}
if (cachedPromise) {
return cachedPromise
}
cachedPromise = new Promise((resolve, reject) => {
client.tokens.create({}, (err, token) => {
if (err) {
winston.error(err);
return resolve(DEFAULT_ICE_SERVERS);
}
winston.info("Retrieved ICE servers from Twilio");
;setTimeout(clearCache, CACHE_LIFETIME)
resolve(token.ice_servers);
})
});
return cachedPromise;
}

@ -0,0 +1,52 @@
const twilio = require('twilio')
const winston = require('winston')
if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN) {
const twilioSID = process.env.TWILIO_SID
const twilioToken = process.env.TWILIO_TOKEN
var client = twilio(twilioSID, twilioToken)
winston.info('Using Twilio TURN service')
} else {
var client = null
}
let ICE_SERVERS = [
{
urls: 'stun:stun.l.google.com:19302',
},
]
if (process.env.ICE_SERVERS) {
ICE_SERVERS = JSON.parse(process.env.ICE_SERVERS)
}
const CACHE_LIFETIME = 5 * 60 * 1000 // 5 minutes
let cachedPromise = null
function clearCache() {
cachedPromise = null
}
exports.getICEServers = function() {
if (client == null) {
return Promise.resolve(ICE_SERVERS)
}
if (cachedPromise) {
return cachedPromise
}
cachedPromise = new Promise((resolve, reject) => {
client.tokens.create({}, (err, token) => {
if (err) {
winston.error(err)
return resolve(DEFAULT_ICE_SERVERS)
}
winston.info('Retrieved ICE servers from Twilio')
setTimeout(clearCache, CACHE_LIFETIME)
resolve(token.ice_servers)
})
})
return cachedPromise
}

@ -2,7 +2,7 @@
try { try {
require('../newrelic') require('../newrelic')
;require('newrelic'); require('newrelic')
} catch (ex) { } catch (ex) {
// Don't load New Relic if the configuration file doesn't exist. // Don't load New Relic if the configuration file doesn't exist.
} }
@ -10,14 +10,15 @@ try {
process.on('unhandledRejection', (reason, p) => { process.on('unhandledRejection', (reason, p) => {
p.catch(err => { p.catch(err => {
console.error('Exiting due to unhandled rejection!') console.error('Exiting due to unhandled rejection!')
;;;console.error(err) console.error(err)
process.exit(1) process.exit(1)
}); })
}) })
process.on('uncaughtException', err => { process.on('uncaughtException', err => {
console.error('Exiting due to uncaught exception!') console.error('Exiting due to uncaught exception!')
;console.error(err.stack) console.error(err.stack)
process.exit(1) process.exit(1)
}); })
module.exports = require("./server");
module.exports = require('./server')

@ -1,7 +1,9 @@
const express = require("express"); const express = require('express')
const db = require("../db"); const db = require('../db')
let routes = (module.exports = new express.Router())
;function bootstrap(uploader, req, res, next) { const routes = module.exports = new express.Router()
function bootstrap(uploader, req, res, next) {
if (uploader) { if (uploader) {
res.locals.data = { res.locals.data = {
DownloadStore: { DownloadStore: {
@ -17,7 +19,7 @@ let routes = (module.exports = new express.Router())
next() next()
} else { } else {
const err = new Error('Not Found') const err = new Error('Not Found')
;err.status = 404 err.status = 404
next(err) next(err)
} }
} }
@ -25,8 +27,8 @@ let routes = (module.exports = new express.Router())
routes.get(/^\/([a-z]+\/[a-z]+\/[a-z]+\/[a-z]+)$/, (req, res, next) => { routes.get(/^\/([a-z]+\/[a-z]+\/[a-z]+\/[a-z]+)$/, (req, res, next) => {
const uploader = db.find(req.params[0]) const uploader = db.find(req.params[0])
return bootstrap(uploader, req, res, next) return bootstrap(uploader, req, res, next)
}); })
routes.get(/^\/download\/(\w+)$/, (req, res, next) => { routes.get(/^\/download\/(\w+)$/, (req, res, next) => {
const uploader = db.findShort(req.params[0]) const uploader = db.findShort(req.params[0])
return bootstrap(uploader, req, res, next) return bootstrap(uploader, req, res, next)
}); })

@ -1,10 +1,9 @@
module.exports = function (err, req, res, next) { module.exports = function (err, req, res, next) {
const status = err.status || 500; const status = err.status || 500
const message = err.message || ''; const message = err.message || ''
const stack const stack = process.env.NODE_ENV === 'production' ? null : err.stack || null
= process.env.NODE_ENV === 'production' ? null : err.stack || null
req.url = '/error'; req.url = '/error'
res.status(status) res.status(status)
res.locals.data = { res.locals.data = {
ErrorStore: { ErrorStore: {
@ -15,4 +14,4 @@ module.exports = function (err, req, res, next) {
} }
next() next()
}; }

@ -1,15 +1,17 @@
const path = require('path') const path = require('path')
;const BUNDLE_PATH = path.resolve(__dirname, '../../dist/bundle.js')
;if (process.env.NODE_ENV === 'production') { const BUNDLE_PATH = path.resolve(__dirname, '../../dist/bundle.js')
if (process.env.NODE_ENV === 'production') {
module.exports = function (req, res) { module.exports = function (req, res) {
res.sendFile(BUNDLE_PATH) res.sendFile(BUNDLE_PATH)
}; }
} else { } else {
const webpackMiddleware = require('webpack-dev-middleware') const webpackMiddleware = require('webpack-dev-middleware')
;const webpack = require('webpack') const webpack = require('webpack')
;const config = require('../../webpack.config.js') const config = require('../../webpack.config.js')
;config.output.filename = '/app.js';
config.output.path = '/'; config.output.filename = '/app.js'
config.output.path = '/'
module.exports = webpackMiddleware(webpack(config)) module.exports = webpackMiddleware(webpack(config))
} }

@ -1,8 +1,9 @@
const React = require('react') const React = require('react')
;let ReactRouter = require('react-router') const ReactRouter = require('react-router')
;let alt = require('../alt') const alt = require('../alt')
;let routes = require('../routes') const routes = require('../routes')
;function isNotFound(state) {
function isNotFound(state) {
for (const r of state.routes) { for (const r of state.routes) {
if (r.isNotFound) { if (r.isNotFound) {
return true return true
@ -16,14 +17,14 @@ module.exports = function (req, res) {
alt.bootstrap(JSON.stringify(res.locals.data || {})) alt.bootstrap(JSON.stringify(res.locals.data || {}))
ReactRouter.run(routes, req.url, (Handler, state) => { ReactRouter.run(routes, req.url, (Handler, state) => {
const html = React.renderToString(<Handler data={alt.takeSnapshot()} />); const html = React.renderToString(<Handler data={alt.takeSnapshot()} />)
alt.flush() alt.flush()
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html')
;;if (isNotFound(state)) { if (isNotFound(state)) {
res.status(404); res.status(404)
} }
res.write('<!DOCTYPE html>\n') res.write('<!DOCTYPE html>\n')
;;res.end(html) res.end(html)
}); })
} }

@ -1,4 +1,6 @@
const path = require("path"); const path = require('path')
const express = require("express"); const express = require('express')
let STATIC_PATH = path.resolve(__dirname, "../static");
module.exports = express.static(STATIC_PATH); const STATIC_PATH = path.resolve(__dirname, '../static')
module.exports = express.static(STATIC_PATH)

@ -1,9 +1,9 @@
import React from 'react'; import React from 'react'
import { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router'; import { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router'
import App from './components/App'; import App from './components/App'
import DownloadPage from './components/DownloadPage'; import DownloadPage from './components/DownloadPage'
import UploadPage from './components/UploadPage'; import UploadPage from './components/UploadPage'
import ErrorPage from './components/ErrorPage'; import ErrorPage from './components/ErrorPage'
export default ( export default (
<Route handler={App}> <Route handler={App}>

@ -1,98 +1,100 @@
const fs = require("fs"); const fs = require('fs')
const express = require("express"); const express = require('express')
var expressWinston = require("express-winston"); const expressWinston = require('express-winston')
var ice = require('./ice') const socketIO = require('socket.io')
;var socketIO = require('socket.io') const winston = require('winston')
;var winston = require('winston') const ice = require('./ice')
;const db = require('./db') const db = require('./db')
;process.on("unhandledRejection", (reason, p) => {
process.on('unhandledRejection', (reason, p) => {
p.catch(err => { p.catch(err => {
log.error("Exiting due to unhandled rejection!"); log.error('Exiting due to unhandled rejection!')
log.error(err); log.error(err)
process.exit(1); process.exit(1)
}) })
}); })
process.on("uncaughtException", err => { process.on('uncaughtException', (err) => {
log.error("Exiting due to uncaught exception!"); log.error('Exiting due to uncaught exception!')
log.error(err); log.error(err)
process.exit(1); process.exit(1)
}) })
const app = express(); const app = express()
let port let port
process.env.PORT || (process.env.NODE_ENV === "production" ? 80 : 3000); process.env.PORT || (process.env.NODE_ENV === 'production' ? 80 : 3000)
if (!process.env.QUIET) { if (!process.env.QUIET) {
app.use( app.use(
expressWinston.logger({ expressWinston.logger({
winstonInstance: winston, winstonInstance: winston,
expressFormat: true, expressFormat: true,
}) }))
);
} }
app.get("/app.js", require("./middleware/javascript")); app.get('/app.js', require('./middleware/javascript'))
app.use(require("./middleware/static")); app.use(require('./middleware/static'))
app.use([ app.use([
require("./middleware/bootstrap"), require('./middleware/bootstrap'),
require("./middleware/error"), require('./middleware/error'),
require("./middleware/react"), require('./middleware/react'),
]); ])
const TRACKERS = process.env.WEBTORRENT_TRACKERS const TRACKERS = process.env.WEBTORRENT_TRACKERS
? process.env.WEBTORRENT_TRACKERS.split(',').map(t => [t.trim()]) ? process.env.WEBTORRENT_TRACKERS.split(',').map(t => [t.trim()])
: [ : [
["wss://tracker.openwebtorrent.com"], ['wss://tracker.openwebtorrent.com'],
["wss://tracker.btorrent.xyz"], ['wss://tracker.btorrent.xyz'],
['wss://tracker.fastcast.nz'], ['wss://tracker.fastcast.nz'],
] ]
;function bootServer(server) {
const io = socketIO(server);
io.set("transports", ["polling"]);
io.on("connection", socket => { function bootServer(server) {
let upload = null; const io = socketIO(server)
io.set('transports', ['polling'])
socket.on("upload", (metadata, res) => { io.on('connection', (socket) => {
let upload = null
socket.on('upload', (metadata, res) => {
if (upload) { if (upload) {
return return
} }
db.create(socket).then(u => { db.create(socket).then(u => {
upload = u; upload = u
upload.fileName = metadata.fileName; upload.fileName = metadata.fileName
upload.fileSize = metadata.fileSize; upload.fileSize = metadata.fileSize
upload.fileType = metadata.fileType; upload.fileType = metadata.fileType
upload.infoHash = metadata.infoHash; upload.infoHash = metadata.infoHash
res({ token: upload.token, shortToken: upload.shortToken }); res({ token: upload.token, shortToken: upload.shortToken })
})
}) })
});
socket.on("trackerConfig", (_, res) => { socket.on('trackerConfig', (_, res) => {
ice.getICEServers().then(iceServers => { ice.getICEServers().then(iceServers => {
res({ rtcConfig: { iceServers }, announce: TRACKERS }); res({ rtcConfig: { iceServers }, announce: TRACKERS })
})
}) })
});
socket.on("disconnect", () => { socket.on('disconnect', () => {
db.remove(upload); db.remove(upload)
})
}) })
});
server.on("error", err => { server.on('error', (err) => {
winston.error(err.message); winston.error(err.message)
process.exit(1); process.exit(1)
}) })
server.listen(port, (err) => { server.listen(port, (err) => {
const host = server.address().address; const host = server.address().address
const port = server.address().port; const port = server.address().port
winston.info("FilePizza listening on %s:%s", host, port); winston.info('FilePizza listening on %s:%s', host, port)
}) })
} }
if (process.env.HTTPS_KEY && process.env.HTTPS_CERT) { if (process.env.HTTPS_KEY && process.env.HTTPS_CERT) {
// user-supplied HTTPS key/cert // user-supplied HTTPS key/cert
const https = require("https"); const https = require('https')
var server = https.createServer( var server = https.createServer(
{ {
key: fs.readFileSync(process.env.HTTPS_KEY), key: fs.readFileSync(process.env.HTTPS_KEY),
@ -103,7 +105,8 @@ if (process.env.HTTPS_KEY && process.env.HTTPS_CERT) {
bootServer(server) bootServer(server)
} else { } else {
// no HTTPS // no HTTPS
const http = require("http"); const http = require('http')
var server = http.Server(app) var server = http.Server(app)
bootServer(server) bootServer(server)
} }

@ -1,13 +1,13 @@
import socket from "filepizza-socket"; import socket from 'filepizza-socket'
import DownloadActions from "../actions/DownloadActions"; import DownloadActions from '../actions/DownloadActions'
import alt from "../alt"; import alt from '../alt'
import { getClient } from '../wt'; import { getClient } from '../wt'
const SPEED_REFRESH_TIME = 2000 const SPEED_REFRESH_TIME = 2000
function downloadBlobURL(name, blobURL) { function downloadBlobURL(name, blobURL) {
const a = document.createElement('a') const a = document.createElement('a')
;document.body.appendChild(a) document.body.appendChild(a)
a.download = name a.download = name
a.href = blobURL a.href = blobURL
a.click() a.click()
@ -18,15 +18,15 @@ export default alt.createStore(
constructor() { constructor() {
this.bindActions(DownloadActions) this.bindActions(DownloadActions)
this.fileName = ""; this.fileName = ''
this.fileSize = 0 this.fileSize = 0
this.fileType = ""; this.fileType = ''
this.infoHash = null this.infoHash = null
this.peers = 0; this.peers = 0
this.progress = 0; this.progress = 0
this.speedDown = 0; this.speedDown = 0
this.speedUp = 0; this.speedUp = 0
this.status = "uninitialized"; this.status = 'uninitialized'
this.token = null this.token = null
} }
@ -34,7 +34,7 @@ export default alt.createStore(
if (this.status !== 'ready') { if (this.status !== 'ready') {
return return
} }
this.status = 'requesting'; this.status = 'requesting'
getClient().then(client => { getClient().then(client => {
client.add( client.add(
@ -51,12 +51,12 @@ export default alt.createStore(
}) })
} }
torrent.on('upload', updateSpeed) torrent.on('upload', updateSpeed)
torrent.on("download", updateSpeed); torrent.on('download', updateSpeed)
setInterval(updateSpeed, SPEED_REFRESH_TIME); setInterval(updateSpeed, SPEED_REFRESH_TIME)
const file = torrent.files[0]; const file = torrent.files[0]
const stream = file.createReadStream(); const stream = file.createReadStream()
stream.on("data", (chunk) => { stream.on('data', (chunk) => {
if (this.status !== 'downloading') { if (this.status !== 'downloading') {
return return
} }
@ -68,15 +68,15 @@ export default alt.createStore(
throw err throw err
} }
downloadBlobURL(this.fileName, blobURL) downloadBlobURL(this.fileName, blobURL)
}); })
} else { } else {
this.setState({ progress: torrent.progress }) this.setState({ progress: torrent.progress })
} }
}) })
}, },
) )
}); })
} }
}, },
'DownloadStore' 'DownloadStore',
) )

@ -1,21 +1,21 @@
import SupportActions from '../actions/SupportActions'; import SupportActions from '../actions/SupportActions'
import alt from '../alt'; import alt from '../alt'
export default alt.createStore( export default alt.createStore(
class ErrorStore { class ErrorStore {
constructor() { constructor() {
this.bindActions(SupportActions) this.bindActions(SupportActions)
this.status = 404; this.status = 404
this.message = "Not Found"; this.message = 'Not Found'
this.stack = null this.stack = null
} }
onNoSupport() { onNoSupport() {
this.status = 400 this.status = 400
this.message = "No WebRTC Support. Please use Chrome or Firefox."; this.message = 'No WebRTC Support. Please use Chrome or Firefox.'
this.stack = null this.stack = null
} }
}, },
'ErrorStore' 'ErrorStore',
) )

@ -1,12 +1,12 @@
import SupportActions from '../actions/SupportActions'; import SupportActions from '../actions/SupportActions'
import alt from '../alt'; import alt from '../alt'
export default alt.createStore( export default alt.createStore(
class SupportStore { class SupportStore {
constructor() { constructor() {
this.bindActions(SupportActions) this.bindActions(SupportActions)
this.isSupported = true; this.isSupported = true
this.isChrome = false; this.isChrome = false
} }
onNoSupport() { onNoSupport() {
@ -17,5 +17,5 @@ export default alt.createStore(
this.isChrome = true this.isChrome = true
} }
}, },
'SupportStore' 'SupportStore',
) )

@ -1,31 +1,31 @@
import socket from 'filepizza-socket'; import socket from 'filepizza-socket'
import UploadActions from '../actions/UploadActions'; import UploadActions from '../actions/UploadActions'
import alt from '../alt'; import alt from '../alt'
import { getClient } from "../wt"; import { getClient } from '../wt'
const SPEED_REFRESH_TIME = 2000; const SPEED_REFRESH_TIME = 2000
export default alt.createStore( export default alt.createStore(
class UploadStore { class UploadStore {
constructor() { constructor() {
this.bindActions(UploadActions); this.bindActions(UploadActions)
this.fileName = ""; this.fileName = ''
this.fileSize = 0; this.fileSize = 0
this.fileType = ""; this.fileType = ''
this.infoHash = null; this.infoHash = null
this.peers = 0; this.peers = 0
this.speedUp = 0; this.speedUp = 0
this.status = "ready"; this.status = 'ready'
this.token = null; this.token = null
this.shortToken = null; this.shortToken = null
} }
onUploadFile(file) { onUploadFile(file) {
if (this.status !== "ready") { if (this.status !== 'ready') {
return; return
} }
this.status = "processing"; this.status = 'processing'
getClient().then(client => { getClient().then(client => {
client.seed(file, { announce: client.tracker.announce }, torrent => { client.seed(file, { announce: client.tracker.announce }, torrent => {
@ -33,15 +33,15 @@ export default alt.createStore(
this.setState({ this.setState({
speedUp: torrent.uploadSpeed, speedUp: torrent.uploadSpeed,
peers: torrent.numPeers, peers: torrent.numPeers,
}); })
} }
torrent.on("upload", updateSpeed); torrent.on('upload', updateSpeed)
torrent.on("download", updateSpeed); torrent.on('download', updateSpeed)
setInterval(updateSpeed, SPEED_REFRESH_TIME); setInterval(updateSpeed, SPEED_REFRESH_TIME)
socket.emit( socket.emit(
"upload", 'upload',
{ {
fileName: file.name, fileName: file.name,
fileSize: file.size, fileSize: file.size,
@ -50,19 +50,19 @@ export default alt.createStore(
}, },
(res) => { (res) => {
this.setState({ this.setState({
status: "uploading", status: 'uploading',
token: res.token, token: res.token,
shortToken: res.shortToken, shortToken: res.shortToken,
fileName: file.name, fileName: file.name,
fileSize: file.size, fileSize: file.size,
fileType: file.type, fileType: file.type,
infoHash: torrent.magnetURI, infoHash: torrent.magnetURI,
}); })
}, },
); )
})
}) })
});
} }
}, },
"UploadStore" 'UploadStore',
); )

@ -1,100 +0,0 @@
export default [
"alfalfa",
"almonds",
"anchovies",
"artichoke",
"avocado",
"bacon",
"basil",
"bayleaves",
"bbqchicken",
"beans",
"beef",
"beetroot",
"bluecheese",
"brie",
"broccoli",
"cajunchicken",
"camembert",
"capers",
"capicolla",
"cardamon",
"carrot",
"cauliflower",
"cheddar",
"chickenmasala",
"chickentikka",
"chili",
"chives",
"chorizo",
"cilantro",
"colby",
"coriander",
"crayfish",
"cumin",
"dill",
"duck",
"eggplant",
"fenugreek",
"feta",
"fungi",
"garlic",
"goatcheese",
"gorgonzola",
"gouda",
"ham",
"jalapeno",
"laurel",
"leeks",
"lettuce",
"limburger",
"lobster",
"manchego",
"marjoram",
"meatballs",
"melon",
"montereyjack",
"mozzarella",
"muenster",
"mushrooms",
"olives",
"onion",
"oregano",
"oysters",
"parsley",
"parmesan",
"peanuts",
"peas",
"pecans",
"pepperoni",
"peppers",
"pineapple",
"pinenuts",
"pistachios",
"prawn",
"prosciutto",
"provolone",
"ricotta",
"romano",
"roquefort",
"rosemary",
"salami",
"salmon",
"sausage",
"scallions",
"shallots",
"shrimp",
"snowpeas",
"spinach",
"squash",
"squid",
"sweetcorn",
"tomatoes",
"tuna",
"turkey",
"venison",
"walnuts",
"watercress",
"whitebait",
"zucchini",
]

@ -0,0 +1,100 @@
export default [
'alfalfa',
'almonds',
'anchovies',
'artichoke',
'avocado',
'bacon',
'basil',
'bayleaves',
'bbqchicken',
'beans',
'beef',
'beetroot',
'bluecheese',
'brie',
'broccoli',
'cajunchicken',
'camembert',
'capers',
'capicolla',
'cardamon',
'carrot',
'cauliflower',
'cheddar',
'chickenmasala',
'chickentikka',
'chili',
'chives',
'chorizo',
'cilantro',
'colby',
'coriander',
'crayfish',
'cumin',
'dill',
'duck',
'eggplant',
'fenugreek',
'feta',
'fungi',
'garlic',
'goatcheese',
'gorgonzola',
'gouda',
'ham',
'jalapeno',
'laurel',
'leeks',
'lettuce',
'limburger',
'lobster',
'manchego',
'marjoram',
'meatballs',
'melon',
'montereyjack',
'mozzarella',
'muenster',
'mushrooms',
'olives',
'onion',
'oregano',
'oysters',
'parsley',
'parmesan',
'peanuts',
'peas',
'pecans',
'pepperoni',
'peppers',
'pineapple',
'pinenuts',
'pistachios',
'prawn',
'prosciutto',
'provolone',
'ricotta',
'romano',
'roquefort',
'rosemary',
'salami',
'salmon',
'sausage',
'scallions',
'shallots',
'shrimp',
'snowpeas',
'spinach',
'squash',
'squid',
'sweetcorn',
'tomatoes',
'tuna',
'turkey',
'venison',
'walnuts',
'watercress',
'whitebait',
'zucchini',
]

@ -2,10 +2,10 @@
// http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript // http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
export function formatSize(bytes) { export function formatSize(bytes) {
if (bytes === 0) { if (bytes === 0) {
return '0 Bytes'; return '0 Bytes'
} }
const k = 1000 const k = 1000
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
;const i = Math.floor(Math.log(bytes) / Math.log(k)) const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${(bytes / Math.pow(k, i)).toPrecision(3)} ${sizes[i]}`; return `${(bytes / Math.pow(k, i)).toPrecision(3)} ${sizes[i]}`
} }

@ -1,4 +1,4 @@
import socket from 'filepizza-socket'; import socket from 'filepizza-socket'
export function getClient() { export function getClient() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -7,6 +7,6 @@ export function getClient() {
tracker: trackerConfig, tracker: trackerConfig,
}) })
resolve(client) resolve(client)
}); })
}) })
} }
Loading…
Cancel
Save