Use standard linter

This commit is contained in:
Jerko Steiner 2017-06-08 19:47:45 -04:00
parent eaf44d5239
commit b50eb79463
45 changed files with 1042 additions and 1085 deletions

View File

@ -2,5 +2,14 @@
"extends": ["standard", "standard-react"], "extends": ["standard", "standard-react"],
"rules": { "rules": {
"max-len": [2, 80, 4] "max-len": [2, 80, 4]
},
"globals": {
"expect": true,
"jest": true,
"jasmine": true,
"it": true,
"beforeEach": true,
"afterEach": true,
"describe": true
} }
} }

View File

@ -21,6 +21,11 @@ lint:
eslint src/ eslint src/
.PHONY: lint-fix
lint-fix:
eslint --fix src/
.PHONY: test .PHONY: test
test: test:

View File

@ -1 +1 @@
module.exports = []; module.exports = []

View File

@ -1,16 +1,14 @@
jest.unmock('../notify.js'); jest.unmock('../notify.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const notify = require('../notify.js'); const notify = require('../notify.js')
describe('notify', () => { describe('notify', () => {
beforeEach(() => dispatcher.dispatch.mockClear())
beforeEach(() => dispatcher.dispatch.mockClear());
describe('info', () => { describe('info', () => {
it('should dispatch info notification', () => { it('should dispatch info notification', () => {
notify.info('test: {0} {1}', 'arg1', 'arg2'); notify.info('test: {0} {1}', 'arg1', 'arg2')
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'notify', type: 'notify',
@ -18,15 +16,13 @@ describe('notify', () => {
message: 'test: arg1 arg2', message: 'test: arg1 arg2',
type: 'info' type: 'info'
} }
}]]); }]])
}); })
})
});
describe('warn', () => { describe('warn', () => {
it('should dispatch warning notification', () => { it('should dispatch warning notification', () => {
notify.warn('test: {0} {1}', 'arg1', 'arg2'); notify.warn('test: {0} {1}', 'arg1', 'arg2')
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'notify', type: 'notify',
@ -34,15 +30,13 @@ describe('notify', () => {
message: 'test: arg1 arg2', message: 'test: arg1 arg2',
type: 'warning' type: 'warning'
} }
}]]); }]])
}); })
})
});
describe('error', () => { describe('error', () => {
it('should dispatch error notification', () => { it('should dispatch error notification', () => {
notify.error('test: {0} {1}', 'arg1', 'arg2'); notify.error('test: {0} {1}', 'arg1', 'arg2')
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'notify', type: 'notify',
@ -50,16 +44,13 @@ describe('notify', () => {
message: 'test: arg1 arg2', message: 'test: arg1 arg2',
type: 'error' type: 'error'
} }
}]]); }]])
}); })
})
});
describe('alert', () => { describe('alert', () => {
it('should dispatch an alert', () => { it('should dispatch an alert', () => {
notify.alert('alert!', true)
notify.alert('alert!', true);
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'alert', type: 'alert',
@ -69,10 +60,7 @@ describe('notify', () => {
message: 'alert!', message: 'alert!',
type: 'warning' type: 'warning'
} }
}]]); }]])
})
}); })
})
});
});

View File

@ -1,30 +1,30 @@
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
function format (string, args) { function format (string, args) {
string = args string = args
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string); .reduce((string, arg, i) => string.replace('{' + i + '}', arg), string)
return string; return string
} }
function _notify (type, args) { function _notify (type, args) {
let string = args[0] || ''; let string = args[0] || ''
let message = format(string, Array.prototype.slice.call(args, 1)); let message = format(string, Array.prototype.slice.call(args, 1))
dispatcher.dispatch({ dispatcher.dispatch({
type: 'notify', type: 'notify',
notification: { type, message } notification: { type, message }
}); })
} }
function info () { function info () {
_notify('info', arguments); _notify('info', arguments)
} }
function warn () { function warn () {
_notify('warning', arguments); _notify('warning', arguments)
} }
function error () { function error () {
_notify('error', arguments); _notify('error', arguments)
} }
function alert (message, dismissable) { function alert (message, dismissable) {
@ -36,7 +36,7 @@ function alert(message, dismissable) {
message, message,
type: 'warning' type: 'warning'
} }
}); })
} }
module.exports = { alert, info, warn, error }; module.exports = { alert, info, warn, error }

View File

@ -0,0 +1,40 @@
function format (string, args) {
string = args
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string)
return string
}
function _notify (type, args) {
let string = args[0] || ''
let message = format(string, Array.prototype.slice.call(args, 1))
dispatcher.dispatch({
type: 'notify',
notification: { type, message }
})
}
function info () {
_notify('info', arguments)
}
function warn () {
_notify('warning', arguments)
}
function error () {
_notify('error', arguments)
}
function alert (message, dismissable) {
dispatcher.dispatch({
type: 'alert',
alert: {
action: dismissable ? 'Dismiss' : '',
dismissable: !!dismissable,
message,
type: 'warning'
}
})
}
module.exports = { alert, info, warn, error }

View File

@ -1,2 +1,2 @@
'use strict'; 'use strict'
module.exports = object => window.URL.createObjectURL(object); module.exports = object => window.URL.createObjectURL(object)

View File

@ -1,17 +1,17 @@
'use strict'; 'use strict'
const navigator = require('../browser/navigator.js'); const navigator = require('../browser/navigator.js')
const Promise = require('bluebird'); const Promise = require('bluebird')
function getUserMedia (constraints) { function getUserMedia (constraints) {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
return navigator.mediaDevices.getUserMedia(constraints); return navigator.mediaDevices.getUserMedia(constraints)
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia; const getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
if (!getMedia) reject(new Error('Browser unsupported')); if (!getMedia) reject(new Error('Browser unsupported'))
getMedia.call(navigator, constraints, resolve, reject); getMedia.call(navigator, constraints, resolve, reject)
}); })
} }
module.exports = getUserMedia; module.exports = getUserMedia

View File

@ -1,2 +1,2 @@
'use strict'; 'use strict'
module.exports = window.navigator; module.exports = window.navigator

View File

@ -1,15 +1,15 @@
const debug = require('debug')('peer-calls:video'); const debug = require('debug')('peer-calls:video')
function play () { function play () {
let videos = window.document.querySelectorAll('video'); let videos = window.document.querySelectorAll('video')
Array.prototype.forEach.call(videos, (video, index) => { Array.prototype.forEach.call(videos, (video, index) => {
debug('playing video: %s', index); debug('playing video: %s', index)
try { try {
video.play(); video.play()
} catch (e) { } catch (e) {
debug('error playing video: %s', e.name); debug('error playing video: %s', e.name)
} }
}); })
} }
module.exports = { play }; module.exports = { play }

View File

@ -1,53 +1,53 @@
const Promise = require('bluebird'); const Promise = require('bluebird')
const debug = require('debug')('peer-calls:call'); const debug = require('debug')('peer-calls:call')
const dispatcher = require('./dispatcher/dispatcher.js'); const dispatcher = require('./dispatcher/dispatcher.js')
const getUserMedia = require('./browser/getUserMedia.js'); const getUserMedia = require('./browser/getUserMedia.js')
const play = require('./browser/video.js').play; const play = require('./browser/video.js').play
const notify = require('./action/notify.js'); const notify = require('./action/notify.js')
const handshake = require('./peer/handshake.js'); const handshake = require('./peer/handshake.js')
const socket = require('./socket.js'); const socket = require('./socket.js')
dispatcher.register(action => { dispatcher.register(action => {
if (action.type === 'play') play(); if (action.type === 'play') play()
}); })
function init () { function init () {
const callId = window.document.getElementById('callId').value; const callId = window.document.getElementById('callId').value
Promise.all([connect(), getCameraStream()]) Promise.all([connect(), getCameraStream()])
.spread((_socket, stream) => { .spread((_socket, stream) => {
debug('initializing peer connection'); debug('initializing peer connection')
handshake.init(_socket, callId, stream); handshake.init(_socket, callId, stream)
}); })
} }
function connect () { function connect () {
return new Promise(resolve => { return new Promise(resolve => {
socket.once('connect', () => { socket.once('connect', () => {
notify.warn('Connected to server socket'); notify.warn('Connected to server socket')
debug('socket connected'); debug('socket connected')
resolve(socket); resolve(socket)
}); })
socket.on('disconnect', () => { socket.on('disconnect', () => {
notify.error('Server socket disconnected'); notify.error('Server socket disconnected')
}); })
}); })
} }
function getCameraStream () { function getCameraStream () {
return getUserMedia({ video: true, audio: true }) return getUserMedia({ video: true, audio: true })
.then(stream => { .then(stream => {
debug('got our media stream:', stream); debug('got our media stream:', stream)
dispatcher.dispatch({ dispatcher.dispatch({
type: 'add-stream', type: 'add-stream',
userId: '_me_', userId: '_me_',
stream stream
}); })
return stream; return stream
}) })
.catch(() => { .catch(() => {
notify.alert('Could not get access to microphone & camera'); notify.alert('Could not get access to microphone & camera')
}); })
} }
module.exports = { init }; module.exports = { init }

View File

@ -1,74 +1,71 @@
jest.unmock('../alert.js'); jest.unmock('../alert.js')
const React = require('react'); const React = require('react')
const ReactDOM = require('react-dom'); const ReactDOM = require('react-dom')
const TestUtils = require('react-addons-test-utils'); const TestUtils = require('react-addons-test-utils')
const Alert = require('../alert.js'); const Alert = require('../alert.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const alertStore = require('../../store/alertStore.js'); const alertStore = require('../../store/alertStore.js')
describe('alert', () => { describe('alert', () => {
beforeEach(() => { beforeEach(() => {
alertStore.getAlert.mockClear(); alertStore.getAlert.mockClear()
}); })
function render () { function render () {
let component = TestUtils.renderIntoDocument(<div><Alert /></div>); let component = TestUtils.renderIntoDocument(<div><Alert /></div>)
return ReactDOM.findDOMNode(component); return ReactDOM.findDOMNode(component)
} }
describe('render', () => { describe('render', () => {
it('should do nothing when no alert', () => { it('should do nothing when no alert', () => {
let node = render(); let node = render()
expect(node.querySelector('.alert.hidden')).toBeTruthy(); expect(node.querySelector('.alert.hidden')).toBeTruthy()
}); })
it('should render alert', () => { it('should render alert', () => {
alertStore.getAlert.mockReturnValue({ alertStore.getAlert.mockReturnValue({
message: 'example', message: 'example',
type: 'warning' type: 'warning'
}); })
let node = render(); let node = render()
expect(node.querySelector('.alert.warning')).toBeTruthy(); expect(node.querySelector('.alert.warning')).toBeTruthy()
expect(node.querySelector('.alert span').textContent).toMatch(/example/); expect(node.querySelector('.alert span').textContent).toMatch(/example/)
expect(node.querySelector('.alert button')).toBeNull(); expect(node.querySelector('.alert button')).toBeNull()
}); })
it('should render dismissable alert', () => { it('should render dismissable alert', () => {
alertStore.getAlert.mockReturnValue({ alertStore.getAlert.mockReturnValue({
message: 'example', message: 'example',
type: 'warning', type: 'warning',
dismissable: true dismissable: true
}); })
let node = render(); let node = render()
expect(node.querySelector('.alert.warning')).toBeTruthy(); expect(node.querySelector('.alert.warning')).toBeTruthy()
expect(node.querySelector('.alert span').textContent).toMatch(/example/); expect(node.querySelector('.alert span').textContent).toMatch(/example/)
expect(node.querySelector('.alert button')).toBeTruthy(); expect(node.querySelector('.alert button')).toBeTruthy()
}); })
it('should dispatch dismiss alert on dismiss clicked', () => { it('should dispatch dismiss alert on dismiss clicked', () => {
let alert = { let alert = {
message: 'example', message: 'example',
type: 'warning', type: 'warning',
dismissable: true dismissable: true
}; }
alertStore.getAlert.mockReturnValue(alert); alertStore.getAlert.mockReturnValue(alert)
let node = render(); let node = render()
TestUtils.Simulate.click(node.querySelector('.alert button')); TestUtils.Simulate.click(node.querySelector('.alert button'))
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'alert-dismiss', type: 'alert-dismiss',
alert alert
}]]); }]])
}); })
}); })
})
});

View File

@ -1,62 +1,60 @@
jest.unmock('../app.js'); jest.unmock('../app.js')
jest.unmock('underscore'); jest.unmock('underscore')
const React = require('react'); const React = require('react')
const ReactDOM = require('react-dom'); const ReactDOM = require('react-dom')
const TestUtils = require('react-addons-test-utils'); const TestUtils = require('react-addons-test-utils')
require('../alert.js').mockImplementation(() => <div />); require('../alert.js').mockImplementation(() => <div />)
require('../notifications.js').mockImplementation(() => <div />); require('../notifications.js').mockImplementation(() => <div />)
const App = require('../app.js'); const App = require('../app.js')
const activeStore = require('../../store/activeStore.js'); const activeStore = require('../../store/activeStore.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const streamStore = require('../../store/streamStore.js'); const streamStore = require('../../store/streamStore.js')
describe('app', () => { describe('app', () => {
beforeEach(() => { beforeEach(() => {
dispatcher.dispatch.mockClear(); dispatcher.dispatch.mockClear()
}); })
function render (active) { function render (active) {
streamStore.getStreams.mockReturnValue({ streamStore.getStreams.mockReturnValue({
user1: { stream: 1 }, user1: { stream: 1 },
user2: { stream: 2 } user2: { stream: 2 }
}); })
let component = TestUtils.renderIntoDocument(<div><App /></div>); let component = TestUtils.renderIntoDocument(<div><App /></div>)
return ReactDOM.findDOMNode(component).children[0]; return ReactDOM.findDOMNode(component).children[0]
} }
it('should render div.app', () => { it('should render div.app', () => {
let node = render(); let node = render()
expect(node.tagName).toBe('DIV'); expect(node.tagName).toBe('DIV')
expect(node.className).toBe('app'); expect(node.className).toBe('app')
}); })
it('should have rendered two videos', () => { it('should have rendered two videos', () => {
let node = render(); let node = render()
expect(node.querySelectorAll('video').length).toBe(2); expect(node.querySelectorAll('video').length).toBe(2)
}); })
it('should mark .active video', () => { it('should mark .active video', () => {
activeStore.getActive.mockReturnValue('user1'); activeStore.getActive.mockReturnValue('user1')
activeStore.isActive.mockImplementation(test => test === 'user1'); activeStore.isActive.mockImplementation(test => test === 'user1')
let node = render(); let node = render()
expect(node.querySelectorAll('.video-container').length).toBe(2); expect(node.querySelectorAll('.video-container').length).toBe(2)
expect(node.querySelectorAll('.video-container.active').length).toBe(1); expect(node.querySelectorAll('.video-container.active').length).toBe(1)
}); })
it('should dispatch mark-active on video click', () => { it('should dispatch mark-active on video click', () => {
let node = render(); let node = render()
TestUtils.Simulate.click(node.querySelectorAll('video')[1]); TestUtils.Simulate.click(node.querySelectorAll('video')[1])
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'mark-active', type: 'mark-active',
userId: 'user2' userId: 'user2'
}]]); }]])
}); })
})
});

View File

@ -1,31 +1,29 @@
jest.unmock('../notifications.js'); jest.unmock('../notifications.js')
const React = require('react'); const React = require('react')
const ReactDOM = require('react-dom'); const ReactDOM = require('react-dom')
const TestUtils = require('react-addons-test-utils'); const TestUtils = require('react-addons-test-utils')
const Notifications = require('../notifications.js'); const Notifications = require('../notifications.js')
const notificationsStore = require('../../store/notificationsStore.js'); const notificationsStore = require('../../store/notificationsStore.js')
describe('alert', () => { describe('alert', () => {
beforeEach(() => { beforeEach(() => {
notificationsStore.getNotifications.mockClear(); notificationsStore.getNotifications.mockClear()
notificationsStore.getNotifications.mockReturnValue([]); notificationsStore.getNotifications.mockReturnValue([])
}); })
function render (component) { function render (component) {
let rendered = TestUtils.renderIntoDocument(<div>{component}</div>); let rendered = TestUtils.renderIntoDocument(<div>{component}</div>)
return ReactDOM.findDOMNode(rendered); return ReactDOM.findDOMNode(rendered)
} }
describe('render', () => { describe('render', () => {
it('should render notifications placeholder', () => { it('should render notifications placeholder', () => {
let node = render(<Notifications />); let node = render(<Notifications />)
expect(node.querySelector('.notifications')).toBeTruthy(); expect(node.querySelector('.notifications')).toBeTruthy()
expect(node.querySelector('.notifications .notification')).toBeFalsy(); expect(node.querySelector('.notifications .notification')).toBeFalsy()
}); })
it('should render notifications', () => { it('should render notifications', () => {
notificationsStore.getNotifications.mockReturnValue([{ notificationsStore.getNotifications.mockReturnValue([{
@ -36,24 +34,23 @@ describe('alert', () => {
_id: 2, _id: 2,
message: 'message 2', message: 'message 2',
type: 'error' type: 'error'
}]); }])
let node = render(<Notifications />); let node = render(<Notifications />)
expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 10 ]]); expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 10 ]])
let c = node.querySelector('.notifications'); let c = node.querySelector('.notifications')
expect(c).toBeTruthy(); expect(c).toBeTruthy()
expect(c.querySelectorAll('.notification').length).toBe(2); expect(c.querySelectorAll('.notification').length).toBe(2)
expect(c.querySelector('.notification.warning').textContent) expect(c.querySelector('.notification.warning').textContent)
.toEqual('message 1'); .toEqual('message 1')
expect(c.querySelector('.notification.error').textContent) expect(c.querySelector('.notification.error').textContent)
.toEqual('message 2'); .toEqual('message 2')
}); })
it('should render max X notifications', () => { it('should render max X notifications', () => {
render(<Notifications max={1} />); render(<Notifications max={1} />)
expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 1 ]]); expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 1 ]])
}); })
}); })
})
});

View File

@ -1,21 +1,21 @@
const React = require('react'); const React = require('react')
const alertStore = require('../store/alertStore.js'); const alertStore = require('../store/alertStore.js')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
function alert () { function alert () {
let alert = alertStore.getAlert(); let alert = alertStore.getAlert()
if (!alert) return <div className="alert hidden"><span>&nbsp;</span></div>; if (!alert) return <div className='alert hidden'><span>&nbsp;</span></div>
let button; let button
function dismiss () { function dismiss () {
dispatcher.dispatch({ dispatcher.dispatch({
type: 'alert-dismiss', type: 'alert-dismiss',
alert alert
}); })
} }
if (alert.dismissable) { if (alert.dismissable) {
button = <button onClick={dismiss}>{alert.action}</button>; button = <button onClick={dismiss}>{alert.action}</button>
} }
return ( return (
@ -23,8 +23,7 @@ function alert() {
<span>{alert.message}</span> <span>{alert.message}</span>
{button} {button}
</div> </div>
); )
} }
module.exports = alert; module.exports = alert

View File

@ -1,37 +1,37 @@
const Alert = require('./alert.js'); const Alert = require('./alert.js')
const Input = require('./input.js'); const Input = require('./input.js')
const Notifications = require('./notifications.js'); const Notifications = require('./notifications.js')
const React = require('react'); const React = require('react')
const _ = require('underscore'); const _ = require('underscore')
const activeStore = require('../store/activeStore.js'); const activeStore = require('../store/activeStore.js')
const debug = require('debug')('peer-calls:app'); const debug = require('debug')('peer-calls:app')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const streamStore = require('../store/streamStore.js'); const streamStore = require('../store/streamStore.js')
function app () { function app () {
let streams = streamStore.getStreams(); let streams = streamStore.getStreams()
function play (event) { function play (event) {
try { try {
event.target.play(); event.target.play()
} catch (e) { } catch (e) {
debug('error starting video: %s', e.name); debug('error starting video: %s', e.name)
} }
} }
let videos = _.map(streams, (stream, userId) => { let videos = _.map(streams, (stream, userId) => {
let url = stream.url; let url = stream.url
function markActive (event) { function markActive (event) {
play(event); play(event)
dispatcher.dispatch({ dispatcher.dispatch({
type: 'mark-active', type: 'mark-active',
userId: activeStore.isActive(userId) ? undefined : userId userId: activeStore.isActive(userId) ? undefined : userId
}); })
} }
let className = 'video-container'; let className = 'video-container'
className += activeStore.isActive(userId) ? ' active' : ''; className += activeStore.isActive(userId) ? ' active' : ''
return ( return (
<div className={className} key={userId}> <div className={className} key={userId}>
@ -42,17 +42,17 @@ function app() {
src={url} src={url}
/> />
</div> </div>
); )
}); })
return (<div className="app"> return (<div className='app'>
<Alert /> <Alert />
<Notifications /> <Notifications />
<Input /> <Input />
<div className="videos"> <div className='videos'>
{videos} {videos}
</div> </div>
</div>); </div>)
} }
module.exports = app; module.exports = app

View File

@ -1,39 +1,39 @@
const React = require('react'); const React = require('react')
const peers = require('../peer/peers.js'); const peers = require('../peer/peers.js')
const notify = require('../action/notify.js'); const notify = require('../action/notify.js')
const Input = React.createClass({ const Input = React.createClass({
getInitialState () { getInitialState () {
return { return {
visible: false, visible: false,
message: '' message: ''
}; }
}, },
handleChange (e) { handleChange (e) {
this.setState({ this.setState({
message: e.target.value message: e.target.value
}); })
}, },
handleSubmit (e) { handleSubmit (e) {
e.preventDefault(); e.preventDefault()
const { message } = this.state; const { message } = this.state
peers.message(message); peers.message(message)
notify.info('You: ' + message); notify.info('You: ' + message)
this.setState({ message: '' }); this.setState({ message: '' })
}, },
render () { render () {
const { message } = this.state; const { message } = this.state
return ( return (
<form className="input" onSubmit={this.handleSubmit}> <form className='input' onSubmit={this.handleSubmit}>
<input <input
onChange={this.handleChange} onChange={this.handleChange}
placeholder="Enter your message..." placeholder='Enter your message...'
type="text" type='text'
value={message} value={message}
/> />
</form> </form>
); )
} }
}); })
module.exports = Input; module.exports = Input

View File

@ -1,30 +1,29 @@
const React = require('react'); const React = require('react')
const Transition = require('react-addons-css-transition-group'); const Transition = require('react-addons-css-transition-group')
const notificationsStore = require('../store/notificationsStore.js'); const notificationsStore = require('../store/notificationsStore.js')
function notifications (props) { function notifications (props) {
let notifs = notificationsStore.getNotifications(props.max || 10); let notifs = notificationsStore.getNotifications(props.max || 10)
let notificationElements = notifs.map(notif => { let notificationElements = notifs.map(notif => {
return ( return (
<div className={notif.type + ' notification'} key={notif._id}> <div className={notif.type + ' notification'} key={notif._id}>
{notif.message} {notif.message}
</div> </div>
); )
}); })
return ( return (
<div className="notifications"> <div className='notifications'>
<Transition <Transition
transitionEnterTimeout={200} transitionEnterTimeout={200}
transitionLeaveTimeout={100} transitionLeaveTimeout={100}
transitionName="fade" transitionName='fade'
> >
{notificationElements} {notificationElements}
</Transition> </Transition>
</div> </div>
); )
} }
module.exports = notifications; module.exports = notifications

View File

@ -1,36 +1,34 @@
const iceServers = require('./iceServers.js'); const iceServers = require('./iceServers.js')
function noop () {} function noop () {}
function checkTURNServer (turnConfig, timeout) { function checkTURNServer (turnConfig, timeout) {
console.log('checking turn server', turnConfig)
console.log('checking turn server', turnConfig);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
setTimeout(function () { setTimeout(function () {
if (promiseResolved) return; if (promiseResolved) return
resolve(false); resolve(false)
promiseResolved = true; promiseResolved = true
}, timeout || 5000); }, timeout || 5000)
const promiseResolved = false; const promiseResolved = false
const PeerConnection = window.RTCPeerConnection || const PeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection || window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection; window.webkitRTCPeerConnection
const pc = new PeerConnection({ iceServers: [turnConfig] }); const pc = new PeerConnection({ iceServers: [turnConfig] })
// create a bogus data channel // create a bogus data channel
pc.createDataChannel(''); pc.createDataChannel('')
pc.createOffer(function (sdp) { pc.createOffer(function (sdp) {
// sometimes sdp contains the ice candidates... // sometimes sdp contains the ice candidates...
if (sdp.sdp.indexOf('typ relay') > -1) { if (sdp.sdp.indexOf('typ relay') > -1) {
promiseResolved = true; promiseResolved = true
resolve(true); resolve(true)
} }
pc.setLocalDescription(sdp, noop, noop); pc.setLocalDescription(sdp, noop, noop)
}, noop); }, noop)
pc.onicecandidate = function (ice) { pc.onicecandidate = function (ice) {
if (promiseResolved || if (promiseResolved ||
@ -38,14 +36,14 @@ function checkTURNServer(turnConfig, timeout) {
!ice.candidate || !ice.candidate ||
!ice.candidate.candidate || !ice.candidate.candidate ||
!(ice.candidate.candidate.indexOf('typ relay') > -1)) { !(ice.candidate.candidate.indexOf('typ relay') > -1)) {
return; return
} }
promiseResolved = true; promiseResolved = true
resolve(true); resolve(true)
}; }
}); })
} }
checkTURNServer(iceServers[0], 10000) checkTURNServer(iceServers[0], 10000)
.then(console.log.bind(console)) .then(console.log.bind(console))
.catch(console.error.bind(console)); .catch(console.error.bind(console))

View File

@ -1,5 +1,5 @@
const Dispatcher = require('flux').Dispatcher; const Dispatcher = require('flux').Dispatcher
const dispatcher = new Dispatcher(); const dispatcher = new Dispatcher()
module.exports = dispatcher; module.exports = dispatcher

View File

@ -1,3 +1,3 @@
module.exports = JSON.parse( module.exports = JSON.parse(
window.document.getElementById('iceServers').value window.document.getElementById('iceServers').value
); )

View File

@ -1,26 +1,26 @@
'use strict'; 'use strict'
const App = require('./components/app.js'); const App = require('./components/app.js')
const React = require('react'); const React = require('react')
const ReactDom = require('react-dom'); const ReactDom = require('react-dom')
const activeStore = require('./store/activeStore.js'); const activeStore = require('./store/activeStore.js')
const alertStore = require('./store/alertStore.js'); const alertStore = require('./store/alertStore.js')
const call = require('./call.js'); const call = require('./call.js')
const debug = require('debug')('peer-calls:index'); const debug = require('debug')('peer-calls:index')
const notificationsStore = require('./store/notificationsStore.js'); const notificationsStore = require('./store/notificationsStore.js')
const play = require('./browser/video.js').play; const play = require('./browser/video.js').play
const streamStore = require('./store/streamStore.js'); const streamStore = require('./store/streamStore.js')
function render () { function render () {
debug('rendering'); debug('rendering')
ReactDom.render(<App />, document.querySelector('#container')); ReactDom.render(<App />, document.querySelector('#container'))
play(); play()
} }
activeStore.addListener(render); activeStore.addListener(render)
alertStore.addListener(render); alertStore.addListener(render)
notificationsStore.addListener(render); notificationsStore.addListener(render)
streamStore.addListener(render); streamStore.addListener(render)
render(); render()
call.init(); call.init()

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict'
const Peer = require('simple-peer'); const Peer = require('simple-peer')
function init (opts) { function init (opts) {
return Peer(opts); return Peer(opts)
} }
module.exports = { init }; module.exports = { init }

View File

@ -1,176 +1,159 @@
jest.unmock('../handshake.js'); jest.unmock('../handshake.js')
jest.unmock('../peers.js'); jest.unmock('../peers.js')
jest.unmock('events'); jest.unmock('events')
jest.unmock('underscore'); jest.unmock('underscore')
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const Peer = require('../Peer.js'); const Peer = require('../Peer.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const handshake = require('../handshake.js'); const handshake = require('../handshake.js')
const peers = require('../peers.js'); const peers = require('../peers.js')
describe('handshake', () => { describe('handshake', () => {
let socket, peerInstances
let socket, peerInstances;
beforeEach(() => { beforeEach(() => {
socket = new EventEmitter(); socket = new EventEmitter()
socket.id = 'a'; socket.id = 'a'
peerInstances = []; peerInstances = []
Peer.init = jest.genMockFunction().mockImplementation(() => { Peer.init = jest.genMockFunction().mockImplementation(() => {
let peer = new EventEmitter(); let peer = new EventEmitter()
peer.destroy = jest.genMockFunction(); peer.destroy = jest.genMockFunction()
peer.signal = jest.genMockFunction(); peer.signal = jest.genMockFunction()
peerInstances.push(peer); peerInstances.push(peer)
return peer; return peer
}); })
dispatcher.dispatch.mockClear(); dispatcher.dispatch.mockClear()
}); })
afterEach(() => peers.clear()); afterEach(() => peers.clear())
describe('socket events', () => { describe('socket events', () => {
describe('users', () => { describe('users', () => {
it('add a peer for each new user and destroy peers for missing', () => { it('add a peer for each new user and destroy peers for missing', () => {
handshake.init(socket, 'bla'); handshake.init(socket, 'bla')
// given // given
let payload = { let payload = {
users: [{ id: 'a'}, { id: 'b' }], users: [{ id: 'a'}, { id: 'b' }],
initiator: 'a', initiator: 'a'
}; }
socket.emit('users', payload); socket.emit('users', payload)
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
// when // when
payload = { payload = {
users: [{ id: 'a'}, { id: 'c' }], users: [{ id: 'a'}, { id: 'c' }],
initiator: 'c', initiator: 'c'
}; }
socket.emit('users', payload); socket.emit('users', payload)
// then // then
expect(peerInstances.length).toBe(2); expect(peerInstances.length).toBe(2)
expect(peerInstances[0].destroy.mock.calls.length).toBe(1); expect(peerInstances[0].destroy.mock.calls.length).toBe(1)
expect(peerInstances[1].destroy.mock.calls.length).toBe(0); expect(peerInstances[1].destroy.mock.calls.length).toBe(0)
}); })
})
});
describe('signal', () => { describe('signal', () => {
let data; let data
beforeEach(() => { beforeEach(() => {
data = {}; data = {}
handshake.init(socket, 'bla'); handshake.init(socket, 'bla')
socket.emit('users', { socket.emit('users', {
initiator: 'a', initiator: 'a',
users: [{ id: 'a' }, { id: 'b' }] users: [{ id: 'a' }, { id: 'b' }]
}); })
}); })
it('should forward signal to peer', () => { it('should forward signal to peer', () => {
socket.emit('signal', { socket.emit('signal', {
userId: 'b', userId: 'b',
data data
}); })
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
expect(peerInstances[0].signal.mock.calls.length).toBe(1); expect(peerInstances[0].signal.mock.calls.length).toBe(1)
}); })
it('does nothing if no peer', () => { it('does nothing if no peer', () => {
socket.emit('signal', { socket.emit('signal', {
userId: 'a', userId: 'a',
data data
}); })
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
expect(peerInstances[0].signal.mock.calls.length).toBe(0); expect(peerInstances[0].signal.mock.calls.length).toBe(0)
}); })
})
}); })
});
describe('peer events', () => { describe('peer events', () => {
let peer
let peer;
beforeEach(() => { beforeEach(() => {
let ready = false; let ready = false
socket.once('ready', () => { ready = true; }); socket.once('ready', () => { ready = true })
handshake.init(socket, 'bla'); handshake.init(socket, 'bla')
socket.emit('users', { socket.emit('users', {
initiator: 'a', initiator: 'a',
users: [{ id: 'a' }, { id: 'b'}] users: [{ id: 'a' }, { id: 'b'}]
}); })
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
peer = peerInstances[0]; peer = peerInstances[0]
expect(ready).toBeDefined(); expect(ready).toBeDefined()
}); })
describe('error', () => { describe('error', () => {
it('destroys peer', () => { it('destroys peer', () => {
peer.emit('error', new Error('bla')); peer.emit('error', new Error('bla'))
expect(peer.destroy.mock.calls.length).toBe(1); expect(peer.destroy.mock.calls.length).toBe(1)
}); })
})
});
describe('signal', () => { describe('signal', () => {
it('emits socket signal with user id', done => { it('emits socket signal with user id', done => {
let signal = { bla: 'bla' }; let signal = { bla: 'bla' }
socket.once('signal', payload => { socket.once('signal', payload => {
expect(payload.userId).toEqual('b'); expect(payload.userId).toEqual('b')
expect(payload.signal).toBe(signal); expect(payload.signal).toBe(signal)
done(); done()
}); })
peer.emit('signal', signal); peer.emit('signal', signal)
}); })
})
});
describe('stream', () => { describe('stream', () => {
it('adds a stream to streamStore', () => { it('adds a stream to streamStore', () => {
expect(dispatcher.dispatch.mock.calls.length).toBe(0); expect(dispatcher.dispatch.mock.calls.length).toBe(0)
let stream = {}; let stream = {}
peer.emit('stream', stream); peer.emit('stream', stream)
expect(dispatcher.dispatch.mock.calls.length).toBe(1); expect(dispatcher.dispatch.mock.calls.length).toBe(1)
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'add-stream', type: 'add-stream',
userId: 'b', userId: 'b',
stream stream
}]]); }]])
}); })
})
});
describe('close', () => { describe('close', () => {
it('removes stream from streamStore', () => { it('removes stream from streamStore', () => {
peer.emit('close'); peer.emit('close')
expect(dispatcher.dispatch.mock.calls.length).toBe(1); expect(dispatcher.dispatch.mock.calls.length).toBe(1)
expect(dispatcher.dispatch.mock.calls).toEqual([[{ expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'remove-stream', type: 'remove-stream',
userId: 'b' userId: 'b'
}]]); }]])
}); })
})
}); })
})
});
});

View File

@ -1,165 +1,149 @@
jest.unmock('../peers.js'); jest.unmock('../peers.js')
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const Peer = require('../Peer.js'); const Peer = require('../Peer.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const notify = require('../../action/notify.js'); const notify = require('../../action/notify.js')
const peers = require('../peers.js'); const peers = require('../peers.js')
describe('peers', () => { describe('peers', () => {
function createSocket () { function createSocket () {
let socket = new EventEmitter(); let socket = new EventEmitter()
socket.id = 'user1'; socket.id = 'user1'
return socket; return socket
} }
let socket, stream, peerInstances, user; let socket, stream, peerInstances, user
beforeEach(() => { beforeEach(() => {
dispatcher.dispatch.mockClear(); dispatcher.dispatch.mockClear()
notify.warn.mockClear(); notify.warn.mockClear()
user = { id: 'user2' }; user = { id: 'user2' }
socket = createSocket(); socket = createSocket()
peerInstances = []; peerInstances = []
stream = { stream: true }; stream = { stream: true }
Peer.init = jest.genMockFunction().mockImplementation(() => { Peer.init = jest.genMockFunction().mockImplementation(() => {
let peer = new EventEmitter(); let peer = new EventEmitter()
peer.destroy = jest.genMockFunction(); peer.destroy = jest.genMockFunction()
peer.signal = jest.genMockFunction(); peer.signal = jest.genMockFunction()
peerInstances.push(peer); peerInstances.push(peer)
return peer; return peer
}); })
}); })
afterEach(() => peers.clear()); afterEach(() => peers.clear())
describe('create', () => { describe('create', () => {
it('creates a new peer', () => { it('creates a new peer', () => {
peers.create({ socket, user, initiator: 'user2', stream }); peers.create({ socket, user, initiator: 'user2', stream })
expect(notify.warn.mock.calls).toEqual([[ 'Connecting to peer...' ]]); expect(notify.warn.mock.calls).toEqual([[ 'Connecting to peer...' ]])
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
expect(Peer.init.mock.calls.length).toBe(1); expect(Peer.init.mock.calls.length).toBe(1)
expect(Peer.init.mock.calls[0][0].initiator).toBe(false); expect(Peer.init.mock.calls[0][0].initiator).toBe(false)
expect(Peer.init.mock.calls[0][0].stream).toBe(stream); expect(Peer.init.mock.calls[0][0].stream).toBe(stream)
}); })
it('sets initiator correctly', () => { it('sets initiator correctly', () => {
peers.create({ socket, user, initiator: 'user1', stream }); peers.create({ socket, user, initiator: 'user1', stream })
expect(peerInstances.length).toBe(1); expect(peerInstances.length).toBe(1)
expect(Peer.init.mock.calls.length).toBe(1); expect(Peer.init.mock.calls.length).toBe(1)
expect(Peer.init.mock.calls[0][0].initiator).toBe(true); expect(Peer.init.mock.calls[0][0].initiator).toBe(true)
expect(Peer.init.mock.calls[0][0].stream).toBe(stream); expect(Peer.init.mock.calls[0][0].stream).toBe(stream)
}); })
it('destroys old peer before creating new one', () => { it('destroys old peer before creating new one', () => {
peers.create({ socket, user, initiator: 'user2', stream }); peers.create({ socket, user, initiator: 'user2', stream })
peers.create({ socket, user, initiator: 'user2', stream }); peers.create({ socket, user, initiator: 'user2', stream })
expect(peerInstances.length).toBe(2); expect(peerInstances.length).toBe(2)
expect(Peer.init.mock.calls.length).toBe(2); expect(Peer.init.mock.calls.length).toBe(2)
expect(peerInstances[0].destroy.mock.calls.length).toBe(1); expect(peerInstances[0].destroy.mock.calls.length).toBe(1)
expect(peerInstances[1].destroy.mock.calls.length).toBe(0); expect(peerInstances[1].destroy.mock.calls.length).toBe(0)
}); })
})
});
describe('events', () => { describe('events', () => {
let peer
let peer;
beforeEach(() => { beforeEach(() => {
peers.create({ socket, user, initiator: 'user1', stream }); peers.create({ socket, user, initiator: 'user1', stream })
notify.warn.mockClear(); notify.warn.mockClear()
peer = peerInstances[0]; peer = peerInstances[0]
}); })
describe('connect', () => { describe('connect', () => {
beforeEach(() => peer.emit('connect'))
beforeEach(() => peer.emit('connect'));
it('sends a notification', () => { it('sends a notification', () => {
expect(notify.warn.mock.calls).toEqual([[ expect(notify.warn.mock.calls).toEqual([[
'Peer connection established' 'Peer connection established'
]]); ]])
}); })
it('dispatches "play" action', () => { it('dispatches "play" action', () => {
expect(dispatcher.dispatch.mock.calls).toEqual([[{ type: 'play' }]]); expect(dispatcher.dispatch.mock.calls).toEqual([[{ type: 'play' }]])
}); })
})
}); })
});
describe('get', () => { describe('get', () => {
it('returns undefined when not found', () => { it('returns undefined when not found', () => {
expect(peers.get(user.id)).not.toBeDefined(); expect(peers.get(user.id)).not.toBeDefined()
}); })
it('returns Peer instance when found', () => { it('returns Peer instance when found', () => {
peers.create({ socket, user, initiator: 'user2', stream }); peers.create({ socket, user, initiator: 'user2', stream })
expect(peers.get(user.id)).toBe(peerInstances[0]); expect(peers.get(user.id)).toBe(peerInstances[0])
}); })
})
});
describe('getIds', () => { describe('getIds', () => {
it('returns ids of all peers', () => { it('returns ids of all peers', () => {
peers.create({ peers.create({
socket, user: {id: 'user2' }, initiator: 'user2', stream socket, user: {id: 'user2' }, initiator: 'user2', stream
}); })
peers.create({ peers.create({
socket, user: {id: 'user3' }, initiator: 'user3', stream socket, user: {id: 'user3' }, initiator: 'user3', stream
}); })
expect(peers.getIds()).toEqual([ 'user2', 'user3' ]); expect(peers.getIds()).toEqual([ 'user2', 'user3' ])
}); })
})
});
describe('destroy', () => { describe('destroy', () => {
it('destroys a peer and removes it', () => { it('destroys a peer and removes it', () => {
peers.create({ socket, user, initiator: 'user2', stream }); peers.create({ socket, user, initiator: 'user2', stream })
peers.destroy(user.id); peers.destroy(user.id)
expect(peerInstances[0].destroy.mock.calls.length).toEqual(1); expect(peerInstances[0].destroy.mock.calls.length).toEqual(1)
}); })
it('throws no error when peer missing', () => { it('throws no error when peer missing', () => {
peers.destroy('bla123'); peers.destroy('bla123')
}); })
})
});
describe('clear', () => { describe('clear', () => {
it('destroys all peers and removes them', () => { it('destroys all peers and removes them', () => {
peers.create({ peers.create({
socket, user: {id: 'user2' }, initiator: 'user2', stream socket, user: {id: 'user2' }, initiator: 'user2', stream
}); })
peers.create({ peers.create({
socket, user: {id: 'user3' }, initiator: 'user3', stream socket, user: {id: 'user3' }, initiator: 'user3', stream
}); })
peers.clear(); peers.clear()
expect(peerInstances[0].destroy.mock.calls.length).toEqual(1); expect(peerInstances[0].destroy.mock.calls.length).toEqual(1)
expect(peerInstances[1].destroy.mock.calls.length).toEqual(1); expect(peerInstances[1].destroy.mock.calls.length).toEqual(1)
expect(peers.getIds()).toEqual([]); expect(peers.getIds()).toEqual([])
}); })
})
}); })
});

View File

@ -1,43 +1,42 @@
'use strict'; 'use strict'
const _ = require('underscore'); const _ = require('underscore')
const debug = require('debug')('peer-calls:peer'); const debug = require('debug')('peer-calls:peer')
const notify = require('../action/notify.js'); const notify = require('../action/notify.js')
const peers = require('./peers.js'); const peers = require('./peers.js')
function init (socket, roomName, stream) { function init (socket, roomName, stream) {
function createPeer (user, initiator) { function createPeer (user, initiator) {
return peers.create({ socket, user, initiator, stream }); return peers.create({ socket, user, initiator, stream })
} }
socket.on('signal', payload => { socket.on('signal', payload => {
let peer = peers.get(payload.userId); let peer = peers.get(payload.userId)
let signal = payload.signal; let signal = payload.signal
// debug('socket signal, userId: %s, signal: %o', payload.userId, signal); // debug('socket signal, userId: %s, signal: %o', payload.userId, signal);
if (!peer) return debug('user: %s, no peer found', payload.userId); if (!peer) return debug('user: %s, no peer found', payload.userId)
peer.signal(signal); peer.signal(signal)
}); })
socket.on('users', payload => { socket.on('users', payload => {
let { initiator, users } = payload; let { initiator, users } = payload
debug('socket users: %o', users); debug('socket users: %o', users)
notify.info('Connected users: {0}', users.length); notify.info('Connected users: {0}', users.length)
users users
.filter(user => !peers.get(user.id) && user.id !== socket.id) .filter(user => !peers.get(user.id) && user.id !== socket.id)
.forEach(user => createPeer(user, initiator)); .forEach(user => createPeer(user, initiator))
let newUsersMap = _.indexBy(users, 'id'); let newUsersMap = _.indexBy(users, 'id')
peers.getIds() peers.getIds()
.filter(id => !newUsersMap[id]) .filter(id => !newUsersMap[id])
.forEach(peers.destroy); .forEach(peers.destroy)
}); })
debug('socket.id: %s', socket.id); debug('socket.id: %s', socket.id)
debug('emit ready for room: %s', roomName); debug('emit ready for room: %s', roomName)
notify.info('Ready for connections'); notify.info('Ready for connections')
socket.emit('ready', roomName); socket.emit('ready', roomName)
} }
module.exports = { init }; module.exports = { init }

View File

@ -1,11 +1,11 @@
const _ = require('underscore'); const _ = require('underscore')
const Peer = require('./Peer.js'); const Peer = require('./Peer.js')
const debug = require('debug')('peer-calls:peer'); const debug = require('debug')('peer-calls:peer')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const iceServers = require('../iceServers.js'); const iceServers = require('../iceServers.js')
const notify = require('../action/notify.js'); const notify = require('../action/notify.js')
let peers = {}; let peers = {}
/** /**
* @param {Socket} socket * @param {Socket} socket
@ -15,93 +15,93 @@ let peers = {};
* @param {MediaStream} [stream] * @param {MediaStream} [stream]
*/ */
function create ({ socket, user, initiator, stream }) { function create ({ socket, user, initiator, stream }) {
debug('create peer: %s, stream:', user.id, stream); debug('create peer: %s, stream:', user.id, stream)
notify.warn('Connecting to peer...'); notify.warn('Connecting to peer...')
if (peers[user.id]) { if (peers[user.id]) {
notify.info('Cleaning up old connection...'); notify.info('Cleaning up old connection...')
destroy(user.id); destroy(user.id)
} }
let peer = peers[user.id] = Peer.init({ let peer = peers[user.id] = Peer.init({
initiator: socket.id === initiator, initiator: socket.id === initiator,
stream, stream,
config: { iceServers } config: { iceServers }
}); })
peer.once('error', err => { peer.once('error', err => {
debug('peer: %s, error %s', user.id, err.stack); debug('peer: %s, error %s', user.id, err.stack)
notify.error('A peer connection error occurred'); notify.error('A peer connection error occurred')
destroy(user.id); destroy(user.id)
}); })
peer.on('signal', signal => { peer.on('signal', signal => {
debug('peer: %s, signal: %o', user.id, signal); debug('peer: %s, signal: %o', user.id, signal)
let payload = { userId: user.id, signal }; let payload = { userId: user.id, signal }
socket.emit('signal', payload); socket.emit('signal', payload)
}); })
peer.once('connect', () => { peer.once('connect', () => {
debug('peer: %s, connect', user.id); debug('peer: %s, connect', user.id)
notify.warn('Peer connection established'); notify.warn('Peer connection established')
dispatcher.dispatch({ type: 'play' }); dispatcher.dispatch({ type: 'play' })
}); })
peer.on('stream', stream => { peer.on('stream', stream => {
debug('peer: %s, stream', user.id); debug('peer: %s, stream', user.id)
dispatcher.dispatch({ dispatcher.dispatch({
type: 'add-stream', type: 'add-stream',
userId: user.id, userId: user.id,
stream stream
}); })
}); })
peer.on('data', object => { peer.on('data', object => {
object = JSON.parse(new window.TextDecoder('utf-8').decode(object)); object = JSON.parse(new window.TextDecoder('utf-8').decode(object))
debug('peer: %s, message: %o', user.id, object); debug('peer: %s, message: %o', user.id, object)
notify.info('' + user.id + ': ' + object.message); notify.info('' + user.id + ': ' + object.message)
}); })
peer.once('close', () => { peer.once('close', () => {
debug('peer: %s, close', user.id); debug('peer: %s, close', user.id)
notify.error('Peer connection closed'); notify.error('Peer connection closed')
dispatcher.dispatch({ dispatcher.dispatch({
type: 'remove-stream', type: 'remove-stream',
userId: user.id userId: user.id
}); })
// make sure some other peer with different id didn't take place between // make sure some other peer with different id didn't take place between
// calling `destroy()` and `close` event // calling `destroy()` and `close` event
if (peers[user.id] === peer) delete peers[user.id]; if (peers[user.id] === peer) delete peers[user.id]
}); })
} }
function get (userId) { function get (userId) {
return peers[userId]; return peers[userId]
} }
function getIds () { function getIds () {
return _.map(peers, (peer, id) => id); return _.map(peers, (peer, id) => id)
} }
function clear () { function clear () {
debug('clear'); debug('clear')
_.each(peers, (_, userId) => destroy(userId)); _.each(peers, (_, userId) => destroy(userId))
peers = {}; peers = {}
} }
function destroy (userId) { function destroy (userId) {
debug('destroy peer: %s', userId); debug('destroy peer: %s', userId)
let peer = peers[userId]; let peer = peers[userId]
if (!peer) return debug('peer: %s peer not found', userId); if (!peer) return debug('peer: %s peer not found', userId)
peer.destroy(); peer.destroy()
delete peers[userId]; delete peers[userId]
} }
function message (message) { function message (message) {
message = JSON.stringify({ message }); message = JSON.stringify({ message })
_.each(peers, peer => peer.send(message)); _.each(peers, peer => peer.send(message))
} }
module.exports = { create, get, getIds, destroy, clear, message }; module.exports = { create, get, getIds, destroy, clear, message }

View File

@ -1,5 +1,5 @@
let SocketIOClient = require('socket.io-client'); let SocketIOClient = require('socket.io-client')
let socket = new SocketIOClient(); let socket = new SocketIOClient()
module.exports = socket; module.exports = socket

View File

@ -1,34 +1,30 @@
jest.unmock('../activeStore.js'); jest.unmock('../activeStore.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const activeStore = require('../activeStore.js'); const activeStore = require('../activeStore.js')
describe('activeStore', () => { describe('activeStore', () => {
let handleAction = dispatcher.register.mock.calls[0][0]
let handleAction = dispatcher.register.mock.calls[0][0]; let onChange = jest.genMockFunction()
let onChange = jest.genMockFunction();
beforeEach(() => { beforeEach(() => {
onChange.mockClear(); onChange.mockClear()
activeStore.addListener(onChange); activeStore.addListener(onChange)
}); })
afterEach(() => activeStore.removeListener(onChange)); afterEach(() => activeStore.removeListener(onChange))
describe('mark-active', () => { describe('mark-active', () => {
it('should mark id as active', () => { it('should mark id as active', () => {
expect(activeStore.getActive()).not.toBeDefined(); expect(activeStore.getActive()).not.toBeDefined()
expect(activeStore.isActive('user1')).toBe(false); expect(activeStore.isActive('user1')).toBe(false)
expect(onChange.mock.calls.length).toBe(0); expect(onChange.mock.calls.length).toBe(0)
handleAction({ type: 'mark-active', userId: 'user1' }); handleAction({ type: 'mark-active', userId: 'user1' })
expect(activeStore.getActive()).toBe('user1'); expect(activeStore.getActive()).toBe('user1')
expect(activeStore.isActive('user1')).toBe(true); expect(activeStore.isActive('user1')).toBe(true)
expect(onChange.mock.calls.length).toBe(1); expect(onChange.mock.calls.length).toBe(1)
}); })
})
}); })
});

View File

@ -1,70 +1,62 @@
jest.unmock('../alertStore.js'); jest.unmock('../alertStore.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const alertStore = require('../alertStore.js'); const alertStore = require('../alertStore.js')
describe('alertStore', () => { describe('alertStore', () => {
let handleAction, onChange
let handleAction, onChange;
beforeEach(() => { beforeEach(() => {
handleAction = dispatcher.register.mock.calls[0][0]; handleAction = dispatcher.register.mock.calls[0][0]
handleAction({ type: 'alert-clear' }); handleAction({ type: 'alert-clear' })
onChange = jest.genMockFunction(); onChange = jest.genMockFunction()
alertStore.addListener(onChange); alertStore.addListener(onChange)
}); })
afterEach(() => { afterEach(() => {
alertStore.removeListener(onChange); alertStore.removeListener(onChange)
}); })
describe('alert', () => { describe('alert', () => {
it('should add alerts to end of queue and dispatch change', () => { it('should add alerts to end of queue and dispatch change', () => {
let alert1 = { message: 'example alert 1' }; let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }; let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 }); handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 }); handleAction({ type: 'alert', alert: alert2 })
expect(onChange.mock.calls.length).toBe(2); expect(onChange.mock.calls.length).toBe(2)
expect(alertStore.getAlerts()).toEqual([ alert1, alert2 ]); expect(alertStore.getAlerts()).toEqual([ alert1, alert2 ])
expect(alertStore.getAlert()).toBe(alert1); expect(alertStore.getAlert()).toBe(alert1)
}); })
})
});
describe('alert-dismiss', () => { describe('alert-dismiss', () => {
it('should remove alert and dispatch change', () => { it('should remove alert and dispatch change', () => {
let alert1 = { message: 'example alert 1' }; let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }; let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 }); handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 }); handleAction({ type: 'alert', alert: alert2 })
handleAction({ type: 'alert-dismiss', alert: alert1 }); handleAction({ type: 'alert-dismiss', alert: alert1 })
expect(onChange.mock.calls.length).toBe(3); expect(onChange.mock.calls.length).toBe(3)
expect(alertStore.getAlerts()).toEqual([ alert2 ]); expect(alertStore.getAlerts()).toEqual([ alert2 ])
expect(alertStore.getAlert()).toBe(alert2); expect(alertStore.getAlert()).toBe(alert2)
}); })
})
});
describe('alert-clear', () => { describe('alert-clear', () => {
it('should remove all alerts', () => { it('should remove all alerts', () => {
let alert1 = { message: 'example alert 1' }; let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }; let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 }); handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 }); handleAction({ type: 'alert', alert: alert2 })
handleAction({ type: 'alert-clear' }); handleAction({ type: 'alert-clear' })
expect(onChange.mock.calls.length).toBe(3); expect(onChange.mock.calls.length).toBe(3)
expect(alertStore.getAlerts()).toEqual([]); expect(alertStore.getAlerts()).toEqual([])
expect(alertStore.getAlert()).not.toBeDefined(); expect(alertStore.getAlert()).not.toBeDefined()
}); })
})
}); })
});

View File

@ -1,67 +1,61 @@
jest.unmock('../notificationsStore.js'); jest.unmock('../notificationsStore.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const store = require('../notificationsStore.js'); const store = require('../notificationsStore.js')
describe('store', () => { describe('store', () => {
let handleAction, onChange
let handleAction, onChange;
beforeEach(() => { beforeEach(() => {
dispatcher.dispatch.mockClear(); dispatcher.dispatch.mockClear()
handleAction = dispatcher.register.mock.calls[0][0]; handleAction = dispatcher.register.mock.calls[0][0]
handleAction({ type: 'notify-clear' }); handleAction({ type: 'notify-clear' })
onChange = jest.genMockFunction(); onChange = jest.genMockFunction()
store.addListener(onChange); store.addListener(onChange)
}); })
describe('notify', () => { describe('notify', () => {
it('should add notification and dispatch change', () => { it('should add notification and dispatch change', () => {
let notif1 = { message: 'example notif 1' }; let notif1 = { message: 'example notif 1' }
let notif2 = { message: 'example notif 2' }; let notif2 = { message: 'example notif 2' }
handleAction({ type: 'notify', notification: notif1 }); handleAction({ type: 'notify', notification: notif1 })
handleAction({ type: 'notify', notification: notif2 }); handleAction({ type: 'notify', notification: notif2 })
expect(onChange.mock.calls.length).toBe(2); expect(onChange.mock.calls.length).toBe(2)
expect(store.getNotifications()).toEqual([ notif1, notif2 ]); expect(store.getNotifications()).toEqual([ notif1, notif2 ])
expect(store.getNotifications(1)).toEqual([ notif2 ]); expect(store.getNotifications(1)).toEqual([ notif2 ])
expect(store.getNotifications(3)).toEqual([ notif1, notif2 ]); expect(store.getNotifications(3)).toEqual([ notif1, notif2 ])
}); })
it('should add timeout for autoremoval', () => { it('should add timeout for autoremoval', () => {
let notif1 = { message: 'example notif 1' }; let notif1 = { message: 'example notif 1' }
handleAction({ type: 'notify', notification: notif1 }); handleAction({ type: 'notify', notification: notif1 })
expect(onChange.mock.calls.length).toBe(1); expect(onChange.mock.calls.length).toBe(1)
expect(store.getNotifications()).toEqual([ notif1 ]); expect(store.getNotifications()).toEqual([ notif1 ])
jest.runAllTimers(); jest.runAllTimers()
expect(onChange.mock.calls.length).toBe(2); expect(onChange.mock.calls.length).toBe(2)
expect(store.getNotifications()).toEqual([]); expect(store.getNotifications()).toEqual([])
}); })
})
});
describe('notify-dismiss', () => { describe('notify-dismiss', () => {
it('should remove notif and dispatch change', () => { it('should remove notif and dispatch change', () => {
let notif1 = { message: 'example notif 1' }; let notif1 = { message: 'example notif 1' }
let notif2 = { message: 'example notif 2' }; let notif2 = { message: 'example notif 2' }
handleAction({ type: 'notify', notification: notif1 }); handleAction({ type: 'notify', notification: notif1 })
handleAction({ type: 'notify', notification: notif2 }); handleAction({ type: 'notify', notification: notif2 })
handleAction({ type: 'notify-dismiss', notification: notif1 }); handleAction({ type: 'notify-dismiss', notification: notif1 })
expect(onChange.mock.calls.length).toBe(3); expect(onChange.mock.calls.length).toBe(3)
expect(store.getNotifications()).toEqual([ notif2 ]); expect(store.getNotifications()).toEqual([ notif2 ])
expect(store.getNotifications(2)).toEqual([ notif2 ]); expect(store.getNotifications(2)).toEqual([ notif2 ])
}); })
})
}); })
});

View File

@ -1,58 +1,56 @@
jest.unmock('../streamStore.js'); jest.unmock('../streamStore.js')
const createObjectUrl = require('../../browser/createObjectURL.js'); const createObjectUrl = require('../../browser/createObjectURL.js')
const dispatcher = require('../../dispatcher/dispatcher.js'); const dispatcher = require('../../dispatcher/dispatcher.js')
const streamStore = require('../streamStore.js'); const streamStore = require('../streamStore.js')
describe('streamStore', () => { describe('streamStore', () => {
let handleAction = dispatcher.register.mock.calls[0][0]
let handleAction = dispatcher.register.mock.calls[0][0]; let onChange = jest.genMockFunction()
let onChange = jest.genMockFunction();
beforeEach(() => { beforeEach(() => {
onChange.mockClear(); onChange.mockClear()
streamStore.addListener(onChange); streamStore.addListener(onChange)
}); })
afterEach(() => streamStore.removeListener(onChange)); afterEach(() => streamStore.removeListener(onChange))
describe('add-stream and remove-stream', () => { describe('add-stream and remove-stream', () => {
it('should add a stream', () => { it('should add a stream', () => {
let stream = {}; let stream = {}
createObjectUrl.mockImplementation(str => { createObjectUrl.mockImplementation(str => {
if (str === stream) return 'url1'; if (str === stream) return 'url1'
}); })
handleAction({ type: 'add-stream', userId: 'user1', stream }); handleAction({ type: 'add-stream', userId: 'user1', stream })
expect(streamStore.getStream('user1')).toEqual({ expect(streamStore.getStream('user1')).toEqual({
stream, stream,
url: 'url1' url: 'url1'
}); })
expect(onChange.mock.calls.length).toEqual(1); expect(onChange.mock.calls.length).toEqual(1)
}); })
it('should add a stream multiple times', () => { it('should add a stream multiple times', () => {
let stream1 = {}; let stream1 = {}
let stream2 = {}; let stream2 = {}
createObjectUrl.mockImplementation(stream => { createObjectUrl.mockImplementation(stream => {
if (stream === stream1) return 'url1'; if (stream === stream1) return 'url1'
if (stream === stream2) return 'url2'; if (stream === stream2) return 'url2'
}); })
handleAction({ type: 'add-stream', userId: 'user1', stream: stream1 }); handleAction({ type: 'add-stream', userId: 'user1', stream: stream1 })
handleAction({ type: 'add-stream', userId: 'user2', stream: stream2 }); handleAction({ type: 'add-stream', userId: 'user2', stream: stream2 })
expect(streamStore.getStream('user1')).toEqual({ expect(streamStore.getStream('user1')).toEqual({
stream: stream1, stream: stream1,
url: 'url1' url: 'url1'
}); })
expect(streamStore.getStream('user2')).toEqual({ expect(streamStore.getStream('user2')).toEqual({
stream: stream2, stream: stream2,
url: 'url2' url: 'url2'
}); })
expect(streamStore.getStreams()).toEqual({ expect(streamStore.getStreams()).toEqual({
user1: { user1: {
stream: stream1, stream: stream1,
@ -62,20 +60,18 @@ describe('streamStore', () => {
stream: stream2, stream: stream2,
url: 'url2' url: 'url2'
} }
}); })
expect(onChange.mock.calls.length).toEqual(2); expect(onChange.mock.calls.length).toEqual(2)
}); })
it('should remove a stream', () => { it('should remove a stream', () => {
let stream = {}; let stream = {}
handleAction({ type: 'add-stream', userId: 'user1', stream }); handleAction({ type: 'add-stream', userId: 'user1', stream })
handleAction({ type: 'remove-stream', userId: 'user1' }); handleAction({ type: 'remove-stream', userId: 'user1' })
expect(streamStore.getStream('user1')).not.toBeDefined(); expect(streamStore.getStream('user1')).not.toBeDefined()
expect(onChange.mock.calls.length).toEqual(2); expect(onChange.mock.calls.length).toEqual(2)
}); })
})
}); })
});

View File

@ -1,37 +1,37 @@
'use strict'; 'use strict'
const EventEmitter = require('events'); const EventEmitter = require('events')
const debug = require('debug')('peer-calls:activeStore'); const debug = require('debug')('peer-calls:activeStore')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const emitter = new EventEmitter(); const emitter = new EventEmitter()
const addListener = cb => emitter.on('change', cb); const addListener = cb => emitter.on('change', cb)
const removeListener = cb => emitter.removeListener('change', cb); const removeListener = cb => emitter.removeListener('change', cb)
let active; let active
const handlers = { const handlers = {
'add-stream': ({ userId }) => { 'add-stream': ({ userId }) => {
active = userId; active = userId
}, },
'mark-active': ({ userId }) => { 'mark-active': ({ userId }) => {
debug('mark-active, userId: %s', userId); debug('mark-active, userId: %s', userId)
active = userId; active = userId
}
} }
};
const dispatcherIndex = dispatcher.register(action => { const dispatcherIndex = dispatcher.register(action => {
let handle = handlers[action.type]; let handle = handlers[action.type]
if (!handle) return; if (!handle) return
handle(action); handle(action)
emitter.emit('change'); emitter.emit('change')
}); })
function getActive () { function getActive () {
return active; return active
} }
function isActive (test) { function isActive (test) {
return active === test; return active === test
} }
module.exports = { module.exports = {
@ -40,4 +40,4 @@ module.exports = {
removeListener, removeListener,
getActive, getActive,
isActive isActive
}; }

View File

@ -1,44 +1,44 @@
const EventEmitter = require('events'); const EventEmitter = require('events')
const debug = require('debug')('peer-calls:alertStore'); const debug = require('debug')('peer-calls:alertStore')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const emitter = new EventEmitter(); const emitter = new EventEmitter()
const addListener = cb => emitter.on('change', cb); const addListener = cb => emitter.on('change', cb)
const removeListener = cb => emitter.removeListener('change', cb); const removeListener = cb => emitter.removeListener('change', cb)
let alerts = []; let alerts = []
const handlers = { const handlers = {
alert: ({ alert }) => { alert: ({ alert }) => {
debug('alert: %s', alert.message); debug('alert: %s', alert.message)
alerts.push(alert); alerts.push(alert)
}, },
'alert-dismiss': ({ alert }) => { 'alert-dismiss': ({ alert }) => {
debug('alert-dismiss: %s', alert.message); debug('alert-dismiss: %s', alert.message)
let index = alerts.indexOf(alert); let index = alerts.indexOf(alert)
debug('index: %s', index); debug('index: %s', index)
if (index < 0) return; if (index < 0) return
alerts.splice(index, 1); alerts.splice(index, 1)
}, },
'alert-clear': () => { 'alert-clear': () => {
debug('alert-clear'); debug('alert-clear')
alerts = []; alerts = []
}
} }
};
const dispatcherIndex = dispatcher.register(action => { const dispatcherIndex = dispatcher.register(action => {
let handle = handlers[action.type]; let handle = handlers[action.type]
if (!handle) return; if (!handle) return
handle(action); handle(action)
emitter.emit('change'); emitter.emit('change')
}); })
function getAlert () { function getAlert () {
return alerts[0]; return alerts[0]
} }
function getAlerts () { function getAlerts () {
return alerts; return alerts
} }
module.exports = { module.exports = {
@ -46,5 +46,5 @@ module.exports = {
addListener, addListener,
removeListener, removeListener,
getAlert, getAlert,
getAlerts, getAlerts
}; }

View File

@ -1,5 +1,5 @@
function getCallId () { function getCallId () {
return window.document.getElementById('callId').value; return window.document.getElementById('callId').value
} }
module.exports = { getCallId }; module.exports = { getCallId }

View File

@ -1,60 +1,60 @@
const EventEmitter = require('events'); const EventEmitter = require('events')
const debug = require('debug')('peer-calls:alertStore'); const debug = require('debug')('peer-calls:alertStore')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const emitter = new EventEmitter(); const emitter = new EventEmitter()
const addListener = cb => emitter.on('change', cb); const addListener = cb => emitter.on('change', cb)
const removeListener = cb => emitter.removeListener('change', cb); const removeListener = cb => emitter.removeListener('change', cb)
let index = 0; let index = 0
let notifications = []; let notifications = []
function dismiss (notification) { function dismiss (notification) {
let index = notifications.indexOf(notification); let index = notifications.indexOf(notification)
if (index < 0) return; if (index < 0) return
notifications.splice(index, 1); notifications.splice(index, 1)
clearTimeout(notification._timeout); clearTimeout(notification._timeout)
delete notification._timeout; delete notification._timeout
} }
function emitChange () { function emitChange () {
emitter.emit('change'); emitter.emit('change')
} }
const handlers = { const handlers = {
notify: ({ notification }) => { notify: ({ notification }) => {
index++; index++
debug('notify', notification.message); debug('notify', notification.message)
notification._id = index; notification._id = index
notifications.push(notification); notifications.push(notification)
notification._timeout = setTimeout(() => { notification._timeout = setTimeout(() => {
debug('notify-dismiss timeout: %s', notification.message); debug('notify-dismiss timeout: %s', notification.message)
dismiss(notification); dismiss(notification)
emitChange(); emitChange()
}, 10000); }, 10000)
}, },
'notify-dismiss': ({ notification }) => { 'notify-dismiss': ({ notification }) => {
debug('notify-dismiss: %s', notification.message); debug('notify-dismiss: %s', notification.message)
dismiss(notification); dismiss(notification)
}, },
'notify-clear': () => { 'notify-clear': () => {
debug('notify-clear'); debug('notify-clear')
notifications = []; notifications = []
}
} }
};
const dispatcherIndex = dispatcher.register(action => { const dispatcherIndex = dispatcher.register(action => {
let handle = handlers[action.type]; let handle = handlers[action.type]
if (!handle) return; if (!handle) return
handle(action); handle(action)
emitChange(); emitChange()
}); })
function getNotifications (max) { function getNotifications (max) {
if (!max) max = notifications.length; if (!max) max = notifications.length
let start = notifications.length - max; let start = notifications.length - max
if (start < 0) start = 0; if (start < 0) start = 0
return notifications.slice(start, notifications.length); return notifications.slice(start, notifications.length)
} }
module.exports = { module.exports = {
@ -62,4 +62,4 @@ module.exports = {
addListener, addListener,
removeListener, removeListener,
getNotifications getNotifications
}; }

View File

@ -1,42 +1,42 @@
'use strict'; 'use strict'
const EventEmitter = require('events'); const EventEmitter = require('events')
const createObjectURL = require('../browser/createObjectURL'); const createObjectURL = require('../browser/createObjectURL')
const debug = require('debug')('peer-calls:streamStore'); const debug = require('debug')('peer-calls:streamStore')
const dispatcher = require('../dispatcher/dispatcher.js'); const dispatcher = require('../dispatcher/dispatcher.js')
const emitter = new EventEmitter(); const emitter = new EventEmitter()
const addListener = cb => emitter.on('change', cb); const addListener = cb => emitter.on('change', cb)
const removeListener = cb => emitter.removeListener('change', cb); const removeListener = cb => emitter.removeListener('change', cb)
const streams = {}; const streams = {}
const handlers = { const handlers = {
'add-stream': ({ userId, stream }) => { 'add-stream': ({ userId, stream }) => {
debug('add-stream, user: %s', userId); debug('add-stream, user: %s', userId)
streams[userId] = { streams[userId] = {
stream, stream,
url: createObjectURL(stream) url: createObjectURL(stream)
}; }
}, },
'remove-stream': ({ userId }) => { 'remove-stream': ({ userId }) => {
debug('remove-stream, user: %s', userId); debug('remove-stream, user: %s', userId)
delete streams[userId]; delete streams[userId]
}
} }
};
const dispatcherIndex = dispatcher.register(action => { const dispatcherIndex = dispatcher.register(action => {
let handle = handlers[action.type]; let handle = handlers[action.type]
if (!handle) return; if (!handle) return
handle(action); handle(action)
emitter.emit('change'); emitter.emit('change')
}); })
function getStream (userId) { function getStream (userId) {
return streams[userId]; return streams[userId]
} }
function getStreams () { function getStreams () {
return streams; return streams
} }
module.exports = { module.exports = {
@ -45,4 +45,4 @@ module.exports = {
removeListener, removeListener,
getStream, getStream,
getStreams getStreams
}; }

View File

@ -1,17 +1,17 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict'
if (!process.env.DEBUG) { if (!process.env.DEBUG) {
process.env.DEBUG = 'peer-calls:*'; process.env.DEBUG = 'peer-calls:*'
} }
const app = require('./server/app.js'); const app = require('./server/app.js')
const os = require('os'); const os = require('os')
let port = process.env.PORT || 3000; let port = process.env.PORT || 3000
let ifaces = os.networkInterfaces(); let ifaces = os.networkInterfaces()
app.http.listen(port, function () { app.http.listen(port, function () {
Object.keys(ifaces).forEach(ifname => Object.keys(ifaces).forEach(ifname =>
ifaces[ifname].forEach(iface => ifaces[ifname].forEach(iface =>
console.log('listening on', iface.address, 'and port', port))); console.log('listening on', iface.address, 'and port', port)))
}); })

View File

@ -1,27 +1,26 @@
'use strict'; 'use strict'
jest.unmock('../socket.js'); jest.unmock('../socket.js')
jest.unmock('events'); jest.unmock('events')
jest.unmock('underscore'); jest.unmock('underscore')
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const handleSocket = require('../socket.js'); const handleSocket = require('../socket.js')
describe('socket', () => { describe('socket', () => {
let socket, io, rooms
let socket, io, rooms;
beforeEach(() => { beforeEach(() => {
socket = new EventEmitter(); socket = new EventEmitter()
socket.id = 'socket0'; socket.id = 'socket0'
socket.join = jest.genMockFunction(); socket.join = jest.genMockFunction()
socket.leave = jest.genMockFunction(); socket.leave = jest.genMockFunction()
rooms = {}; rooms = {}
io = {}; io = {}
io.in = io.to = jest.genMockFunction().mockImplementation(room => { io.in = io.to = jest.genMockFunction().mockImplementation(room => {
return (rooms[room] = rooms[room] || { return (rooms[room] = rooms[room] || {
emit: jest.genMockFunction() emit: jest.genMockFunction()
}); })
}); })
io.sockets = { io.sockets = {
adapter: { adapter: {
@ -41,73 +40,66 @@ describe('socket', () => {
} }
} }
} }
}; }
socket.leave = jest.genMockFunction(); socket.leave = jest.genMockFunction()
socket.join = jest.genMockFunction(); socket.join = jest.genMockFunction()
}); })
it('should be a function', () => { it('should be a function', () => {
expect(typeof handleSocket).toBe('function'); expect(typeof handleSocket).toBe('function')
}); })
describe('socket events', () => { describe('socket events', () => {
beforeEach(() => handleSocket(socket, io))
beforeEach(() => handleSocket(socket, io));
describe('signal', () => { describe('signal', () => {
it('should broadcast signal to specific user', () => { it('should broadcast signal to specific user', () => {
let signal = { type: 'signal' }; let signal = { type: 'signal' }
socket.emit('signal', { userId: 'a', signal }); socket.emit('signal', { userId: 'a', signal })
expect(io.to.mock.calls).toEqual([[ 'a' ]]); expect(io.to.mock.calls).toEqual([[ 'a' ]])
expect(io.to('a').emit.mock.calls).toEqual([[ expect(io.to('a').emit.mock.calls).toEqual([[
'signal', { 'signal', {
userId: 'socket0', userId: 'socket0',
signal signal
} }
]]); ]])
}); })
})
});
describe('ready', () => { describe('ready', () => {
it('should call socket.leave if socket.room', () => { it('should call socket.leave if socket.room', () => {
socket.room = 'room1'; socket.room = 'room1'
socket.emit('ready', 'room2'); socket.emit('ready', 'room2')
expect(socket.leave.mock.calls).toEqual([[ 'room1' ]]); expect(socket.leave.mock.calls).toEqual([[ 'room1' ]])
expect(socket.join.mock.calls).toEqual([[ 'room2' ]]); expect(socket.join.mock.calls).toEqual([[ 'room2' ]])
}); })
it('should call socket.join to room', () => { it('should call socket.join to room', () => {
socket.emit('ready', 'room3'); socket.emit('ready', 'room3')
expect(socket.join.mock.calls).toEqual([[ 'room3' ]]); expect(socket.join.mock.calls).toEqual([[ 'room3' ]])
}); })
it('should emit users', () => { it('should emit users', () => {
socket.emit('ready', 'room3'); socket.emit('ready', 'room3')
expect(io.to.mock.calls).toEqual([[ 'room3' ]]); expect(io.to.mock.calls).toEqual([[ 'room3' ]])
expect(io.to('room3').emit.mock.calls).toEqual([[ expect(io.to('room3').emit.mock.calls).toEqual([[
'users', { 'users', {
initiator: 'socket0', initiator: 'socket0',
users: [{ users: [{
id: 'socket0', id: 'socket0'
}, { }, {
id: 'socket1', id: 'socket1'
}, { }, {
id: 'socket2' id: 'socket2'
}] }]
} }
]]); ]])
}); })
})
}); })
})
});
});

View File

@ -1,21 +1,17 @@
jest.unmock('../turn.js'); jest.unmock('../turn.js')
const turn = require('../turn.js'); const turn = require('../turn.js')
describe('turn', () => { describe('turn', () => {
describe('getCredentials', () => { describe('getCredentials', () => {
it('returns username & credential', () => { it('returns username & credential', () => {
const auth = turn.getCredentials('a', 'b'); const auth = turn.getCredentials('a', 'b')
expect(auth).toEqual(jasmine.any(Object)); expect(auth).toEqual(jasmine.any(Object))
expect(auth.username).toEqual(jasmine.any(String)); expect(auth.username).toEqual(jasmine.any(String))
expect(auth.credential).toEqual(jasmine.any(String)); expect(auth.credential).toEqual(jasmine.any(String))
}); })
})
});
describe('processServers', () => { describe('processServers', () => {
const servers = [{ const servers = [{
url: 'server1', url: 'server1',
urls: 'server1', urls: 'server1',
@ -27,27 +23,24 @@ describe('turn', () => {
username: 'c', username: 'c',
secret: 'd', secret: 'd',
auth: 'secret' auth: 'secret'
}]; }]
it('does not expose secret', () => { it('does not expose secret', () => {
const s = turn.processServers(servers); const s = turn.processServers(servers)
expect(s.length).toBe(2); expect(s.length).toBe(2)
expect(s[0]).toBe(servers[0]); expect(s[0]).toBe(servers[0])
expect(s[1]).toEqual({ expect(s[1]).toEqual({
url: 'server2', url: 'server2',
urls: 'server2', urls: 'server2',
username: jasmine.any(String), username: jasmine.any(String),
credential: jasmine.any(String) credential: jasmine.any(String)
}); })
expect(s[1].username).toMatch(/^[0-9]+:c$/); expect(s[1].username).toMatch(/^[0-9]+:c$/)
}); })
it('throws error when unknown auth type', () => { it('throws error when unknown auth type', () => {
expect(() => turn.processServers([{ auth: 'bla' }])) expect(() => turn.processServers([{ auth: 'bla' }]))
.toThrowError(/not implemented/); .toThrowError(/not implemented/)
}); })
})
}); })
});

View File

@ -1,45 +1,45 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict'
const express = require('express'); const express = require('express')
const handleSocket = require('./socket.js'); const handleSocket = require('./socket.js')
const os = require('os'); const os = require('os')
const path = require('path'); const path = require('path')
// Require in express.Router Middleware. // Require in express.Router Middleware.
const callRouter = require('./routes/call'); const callRouter = require('./routes/call')
const siteRouter = require('./routes/index'); const siteRouter = require('./routes/index')
const app = express(); const app = express()
const http = require('http').Server(app); const http = require('http').Server(app)
const io = require('socket.io')(http); const io = require('socket.io')(http)
app.set('view engine', 'jade'); app.set('view engine', 'jade')
app.set('views', path.join(__dirname, '../views')); app.set('views', path.join(__dirname, '../views'))
app.use('/res', express.static(path.join(__dirname, '../res'))); app.use('/res', express.static(path.join(__dirname, '../res')))
if (__dirname.indexOf('/dist/') >= 0 || __dirname.indexOf('\\dist\\') >= 0) { if (__dirname.indexOf('/dist/') >= 0 || __dirname.indexOf('\\dist\\') >= 0) {
app.use('/js', express.static(path.join(__dirname, '../client'))); app.use('/js', express.static(path.join(__dirname, '../client')))
app.use('/css', express.static(path.join(__dirname, '../css'))); app.use('/css', express.static(path.join(__dirname, '../css')))
} else { } else {
const browserify = require('browserify-middleware'); const browserify = require('browserify-middleware')
const less = require('less-middleware'); const less = require('less-middleware')
browserify.settings({ browserify.settings({
transform: ['babelify'] transform: ['babelify']
}); })
const tempDir = path.join(os.tmpDir(), 'node-peer-calls-cache'); const tempDir = path.join(os.tmpDir(), 'node-peer-calls-cache')
app.use('/js', browserify(path.join(__dirname, '../client'))); app.use('/js', browserify(path.join(__dirname, '../client')))
app.use('/css', less(path.join(__dirname, '../less'), { dest: tempDir})); app.use('/css', less(path.join(__dirname, '../less'), { dest: tempDir}))
app.use('/css', express.static(tempDir)); app.use('/css', express.static(tempDir))
app.use('/css/fonts', express.static( app.use('/css/fonts', express.static(
path.join(__dirname, '../less/fonts'))); path.join(__dirname, '../less/fonts')))
} }
// using Express.Router Middleware // using Express.Router Middleware
app.use('/call', callRouter); app.use('/call', callRouter)
app.use('/', siteRouter); app.use('/', siteRouter)
io.on('connection', socket => handleSocket(socket, io)); io.on('connection', socket => handleSocket(socket, io))
module.exports = { http, app }; module.exports = { http, app }

View File

@ -1,24 +1,24 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict'
const config = require('config'); const config = require('config')
const turn = require('../turn.js'); const turn = require('../turn.js')
const router = require('express').Router(); const router = require('express').Router()
const uuid = require('uuid'); const uuid = require('uuid')
const cfgIceServers = config.get('iceServers'); const cfgIceServers = config.get('iceServers')
router.get('/', (req, res) => { router.get('/', (req, res) => {
let prefix = 'call/'; let prefix = 'call/'
if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = ''; if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = ''
res.redirect(prefix + uuid.v4()); res.redirect(prefix + uuid.v4())
}); })
router.get('/:callId', (req, res) => { router.get('/:callId', (req, res) => {
const iceServers = turn.processServers(cfgIceServers); const iceServers = turn.processServers(cfgIceServers)
res.render('call', { res.render('call', {
callId: encodeURIComponent(req.params.callId), callId: encodeURIComponent(req.params.callId),
iceServers iceServers
}); })
}); })
module.exports = router; module.exports = router

View File

@ -1,9 +1,9 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict'
const router = require('express').Router(); const router = require('express').Router()
router.get('/', (req, res) => { router.get('/', (req, res) => {
res.render('index'); res.render('index')
}); })
module.exports = router; module.exports = router

View File

@ -1,36 +1,34 @@
'use strict'; 'use strict'
const debug = require('debug')('peer-calls:socket'); const debug = require('debug')('peer-calls:socket')
const _ = require('underscore'); const _ = require('underscore')
module.exports = function (socket, io) { module.exports = function (socket, io) {
socket.on('signal', payload => { socket.on('signal', payload => {
// debug('signal: %s, payload: %o', socket.id, payload); // debug('signal: %s, payload: %o', socket.id, payload);
io.to(payload.userId).emit('signal', { io.to(payload.userId).emit('signal', {
userId: socket.id, userId: socket.id,
signal: payload.signal signal: payload.signal
}); })
}); })
socket.on('ready', roomName => { socket.on('ready', roomName => {
debug('ready: %s, room: %s', socket.id, roomName); debug('ready: %s, room: %s', socket.id, roomName)
if (socket.room) socket.leave(socket.room); if (socket.room) socket.leave(socket.room)
socket.room = roomName; socket.room = roomName
socket.join(roomName); socket.join(roomName)
socket.room = roomName; socket.room = roomName
let users = getUsers(roomName); let users = getUsers(roomName)
debug('ready: %s, room: %s, users: %o', socket.id, roomName, users); debug('ready: %s, room: %s, users: %o', socket.id, roomName, users)
io.to(roomName).emit('users', { io.to(roomName).emit('users', {
initiator: socket.id, initiator: socket.id,
users users
}); })
}); })
function getUsers (roomName) { function getUsers (roomName) {
return _.map(io.sockets.adapter.rooms[roomName].sockets, (_, id) => { return _.map(io.sockets.adapter.rooms[roomName].sockets, (_, id) => {
return { id }; return { id }
}); })
}
} }
};

View File

@ -1,35 +1,35 @@
'use strict'; 'use strict'
const crypto = require('crypto'); const crypto = require('crypto')
function getCredentials (name, secret) { function getCredentials (name, secret) {
// this credential would be valid for the next 24 hours // this credential would be valid for the next 24 hours
const timestamp = parseInt(Date.now() / 1000, 10) + 24 * 3600; const timestamp = parseInt(Date.now() / 1000, 10) + 24 * 3600
const username = [timestamp, name].join(':'); const username = [timestamp, name].join(':')
const hmac = crypto.createHmac('sha1', secret); const hmac = crypto.createHmac('sha1', secret)
hmac.setEncoding('base64'); hmac.setEncoding('base64')
hmac.write(username); hmac.write(username)
hmac.end(); hmac.end()
const credential = hmac.read(); const credential = hmac.read()
return { username, credential }; return { username, credential }
} }
function processServers (iceServers) { function processServers (iceServers) {
return iceServers.map(server => { return iceServers.map(server => {
switch (server.auth) { switch (server.auth) {
case undefined: case undefined:
return server; return server
case 'secret': case 'secret':
const cred = getCredentials(server.username, server.secret); const cred = getCredentials(server.username, server.secret)
return { return {
url: server.url, url: server.url,
urls: server.urls, urls: server.urls,
username: cred.username, username: cred.username,
credential: cred.credential credential: cred.credential
};
default:
throw new Error('Authentication type not implemented: ' + server.auth);
} }
}); default:
throw new Error('Authentication type not implemented: ' + server.auth)
}
})
} }
module.exports = { getCredentials, processServers }; module.exports = { getCredentials, processServers }