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"],
"rules": {
"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/
.PHONY: lint-fix
lint-fix:
eslint --fix src/
.PHONY: 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 notify = require('../notify.js');
const dispatcher = require('../../dispatcher/dispatcher.js')
const notify = require('../notify.js')
describe('notify', () => {
beforeEach(() => dispatcher.dispatch.mockClear());
beforeEach(() => dispatcher.dispatch.mockClear())
describe('info', () => {
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([[{
type: 'notify',
@ -18,15 +16,13 @@ describe('notify', () => {
message: 'test: arg1 arg2',
type: 'info'
}
}]]);
});
});
}]])
})
})
describe('warn', () => {
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([[{
type: 'notify',
@ -34,15 +30,13 @@ describe('notify', () => {
message: 'test: arg1 arg2',
type: 'warning'
}
}]]);
});
});
}]])
})
})
describe('error', () => {
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([[{
type: 'notify',
@ -50,16 +44,13 @@ describe('notify', () => {
message: 'test: arg1 arg2',
type: 'error'
}
}]]);
});
});
}]])
})
})
describe('alert', () => {
it('should dispatch an alert', () => {
notify.alert('alert!', true);
notify.alert('alert!', true)
expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'alert',
@ -69,10 +60,7 @@ describe('notify', () => {
message: 'alert!',
type: 'warning'
}
}]]);
});
});
});
}]])
})
})
})

View File

@ -1,33 +1,33 @@
const dispatcher = require('../dispatcher/dispatcher.js');
const dispatcher = require('../dispatcher/dispatcher.js')
function format(string, args) {
function format (string, args) {
string = args
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string);
return string;
.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));
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 info () {
_notify('info', arguments)
}
function warn() {
_notify('warning', arguments);
function warn () {
_notify('warning', arguments)
}
function error() {
_notify('error', arguments);
function error () {
_notify('error', arguments)
}
function alert(message, dismissable) {
function alert (message, dismissable) {
dispatcher.dispatch({
type: 'alert',
alert: {
@ -36,7 +36,7 @@ function alert(message, dismissable) {
message,
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';
module.exports = object => window.URL.createObjectURL(object);
'use strict'
module.exports = object => window.URL.createObjectURL(object)

View File

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

View File

@ -1,2 +1,2 @@
'use strict';
module.exports = window.navigator;
'use strict'
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() {
let videos = window.document.querySelectorAll('video');
function play () {
let videos = window.document.querySelectorAll('video')
Array.prototype.forEach.call(videos, (video, index) => {
debug('playing video: %s', index);
debug('playing video: %s', index)
try {
video.play();
video.play()
} 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 debug = require('debug')('peer-calls:call');
const dispatcher = require('./dispatcher/dispatcher.js');
const getUserMedia = require('./browser/getUserMedia.js');
const play = require('./browser/video.js').play;
const notify = require('./action/notify.js');
const handshake = require('./peer/handshake.js');
const socket = require('./socket.js');
const Promise = require('bluebird')
const debug = require('debug')('peer-calls:call')
const dispatcher = require('./dispatcher/dispatcher.js')
const getUserMedia = require('./browser/getUserMedia.js')
const play = require('./browser/video.js').play
const notify = require('./action/notify.js')
const handshake = require('./peer/handshake.js')
const socket = require('./socket.js')
dispatcher.register(action => {
if (action.type === 'play') play();
});
if (action.type === 'play') play()
})
function init() {
const callId = window.document.getElementById('callId').value;
function init () {
const callId = window.document.getElementById('callId').value
Promise.all([connect(), getCameraStream()])
.spread((_socket, stream) => {
debug('initializing peer connection');
handshake.init(_socket, callId, stream);
});
debug('initializing peer connection')
handshake.init(_socket, callId, stream)
})
}
function connect() {
function connect () {
return new Promise(resolve => {
socket.once('connect', () => {
notify.warn('Connected to server socket');
debug('socket connected');
resolve(socket);
});
notify.warn('Connected to server socket')
debug('socket connected')
resolve(socket)
})
socket.on('disconnect', () => {
notify.error('Server socket disconnected');
});
});
notify.error('Server socket disconnected')
})
})
}
function getCameraStream() {
function getCameraStream () {
return getUserMedia({ video: true, audio: true })
.then(stream => {
debug('got our media stream:', stream);
debug('got our media stream:', stream)
dispatcher.dispatch({
type: 'add-stream',
userId: '_me_',
stream
});
return stream;
})
return stream
})
.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 ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
const React = require('react')
const ReactDOM = require('react-dom')
const TestUtils = require('react-addons-test-utils')
const Alert = require('../alert.js');
const dispatcher = require('../../dispatcher/dispatcher.js');
const alertStore = require('../../store/alertStore.js');
const Alert = require('../alert.js')
const dispatcher = require('../../dispatcher/dispatcher.js')
const alertStore = require('../../store/alertStore.js')
describe('alert', () => {
beforeEach(() => {
alertStore.getAlert.mockClear();
});
alertStore.getAlert.mockClear()
})
function render() {
let component = TestUtils.renderIntoDocument(<div><Alert /></div>);
return ReactDOM.findDOMNode(component);
function render () {
let component = TestUtils.renderIntoDocument(<div><Alert /></div>)
return ReactDOM.findDOMNode(component)
}
describe('render', () => {
it('should do nothing when no alert', () => {
let node = render();
expect(node.querySelector('.alert.hidden')).toBeTruthy();
});
let node = render()
expect(node.querySelector('.alert.hidden')).toBeTruthy()
})
it('should render alert', () => {
alertStore.getAlert.mockReturnValue({
message: 'example',
type: 'warning'
});
})
let node = render();
let node = render()
expect(node.querySelector('.alert.warning')).toBeTruthy();
expect(node.querySelector('.alert span').textContent).toMatch(/example/);
expect(node.querySelector('.alert button')).toBeNull();
});
expect(node.querySelector('.alert.warning')).toBeTruthy()
expect(node.querySelector('.alert span').textContent).toMatch(/example/)
expect(node.querySelector('.alert button')).toBeNull()
})
it('should render dismissable alert', () => {
alertStore.getAlert.mockReturnValue({
message: 'example',
type: 'warning',
dismissable: true
});
})
let node = render();
let node = render()
expect(node.querySelector('.alert.warning')).toBeTruthy();
expect(node.querySelector('.alert span').textContent).toMatch(/example/);
expect(node.querySelector('.alert button')).toBeTruthy();
});
expect(node.querySelector('.alert.warning')).toBeTruthy()
expect(node.querySelector('.alert span').textContent).toMatch(/example/)
expect(node.querySelector('.alert button')).toBeTruthy()
})
it('should dispatch dismiss alert on dismiss clicked', () => {
let alert = {
message: 'example',
type: 'warning',
dismissable: true
};
alertStore.getAlert.mockReturnValue(alert);
}
alertStore.getAlert.mockReturnValue(alert)
let node = render();
TestUtils.Simulate.click(node.querySelector('.alert button'));
let node = render()
TestUtils.Simulate.click(node.querySelector('.alert button'))
expect(dispatcher.dispatch.mock.calls).toEqual([[{
type: 'alert-dismiss',
alert
}]]);
});
});
});
}]])
})
})
})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,51 +1,49 @@
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) {
setTimeout(function () {
if (promiseResolved) return
resolve(false)
promiseResolved = true
}, timeout || 5000)
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (promiseResolved) return;
resolve(false);
promiseResolved = true;
}, timeout || 5000);
const promiseResolved = false;
const promiseResolved = false
const PeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
window.webkitRTCPeerConnection
const pc = new PeerConnection({ iceServers: [turnConfig] });
const pc = new PeerConnection({ iceServers: [turnConfig] })
// create a bogus data channel
pc.createDataChannel('');
pc.createOffer(function(sdp) {
pc.createDataChannel('')
pc.createOffer(function (sdp) {
// sometimes sdp contains the ice candidates...
if (sdp.sdp.indexOf('typ relay') > -1) {
promiseResolved = true;
resolve(true);
promiseResolved = true
resolve(true)
}
pc.setLocalDescription(sdp, noop, noop);
}, noop);
pc.setLocalDescription(sdp, noop, noop)
}, noop)
pc.onicecandidate = function(ice) {
pc.onicecandidate = function (ice) {
if (promiseResolved ||
!ice ||
!ice.candidate ||
!ice.candidate.candidate ||
!(ice.candidate.candidate.indexOf('typ relay') > -1)) {
return;
return
}
promiseResolved = true;
resolve(true);
};
});
promiseResolved = true
resolve(true)
}
})
}
checkTURNServer(iceServers[0], 10000)
.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(
window.document.getElementById('iceServers').value
);
)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,11 @@
const _ = require('underscore');
const Peer = require('./Peer.js');
const debug = require('debug')('peer-calls:peer');
const dispatcher = require('../dispatcher/dispatcher.js');
const iceServers = require('../iceServers.js');
const notify = require('../action/notify.js');
const _ = require('underscore')
const Peer = require('./Peer.js')
const debug = require('debug')('peer-calls:peer')
const dispatcher = require('../dispatcher/dispatcher.js')
const iceServers = require('../iceServers.js')
const notify = require('../action/notify.js')
let peers = {};
let peers = {}
/**
* @param {Socket} socket
@ -14,94 +14,94 @@ let peers = {};
* @param {Boolean} [initiator=false]
* @param {MediaStream} [stream]
*/
function create({ socket, user, initiator, stream }) {
debug('create peer: %s, stream:', user.id, stream);
notify.warn('Connecting to peer...');
function create ({ socket, user, initiator, stream }) {
debug('create peer: %s, stream:', user.id, stream)
notify.warn('Connecting to peer...')
if (peers[user.id]) {
notify.info('Cleaning up old connection...');
destroy(user.id);
notify.info('Cleaning up old connection...')
destroy(user.id)
}
let peer = peers[user.id] = Peer.init({
initiator: socket.id === initiator,
stream,
config: { iceServers }
});
})
peer.once('error', err => {
debug('peer: %s, error %s', user.id, err.stack);
notify.error('A peer connection error occurred');
destroy(user.id);
});
debug('peer: %s, error %s', user.id, err.stack)
notify.error('A peer connection error occurred')
destroy(user.id)
})
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 };
socket.emit('signal', payload);
});
let payload = { userId: user.id, signal }
socket.emit('signal', payload)
})
peer.once('connect', () => {
debug('peer: %s, connect', user.id);
notify.warn('Peer connection established');
dispatcher.dispatch({ type: 'play' });
});
debug('peer: %s, connect', user.id)
notify.warn('Peer connection established')
dispatcher.dispatch({ type: 'play' })
})
peer.on('stream', stream => {
debug('peer: %s, stream', user.id);
debug('peer: %s, stream', user.id)
dispatcher.dispatch({
type: 'add-stream',
userId: user.id,
stream
});
});
})
})
peer.on('data', object => {
object = JSON.parse(new window.TextDecoder('utf-8').decode(object));
debug('peer: %s, message: %o', user.id, object);
notify.info('' + user.id + ': ' + object.message);
});
object = JSON.parse(new window.TextDecoder('utf-8').decode(object))
debug('peer: %s, message: %o', user.id, object)
notify.info('' + user.id + ': ' + object.message)
})
peer.once('close', () => {
debug('peer: %s, close', user.id);
notify.error('Peer connection closed');
debug('peer: %s, close', user.id)
notify.error('Peer connection closed')
dispatcher.dispatch({
type: 'remove-stream',
userId: user.id
});
})
// make sure some other peer with different id didn't take place between
// 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) {
return peers[userId];
function get (userId) {
return peers[userId]
}
function getIds() {
return _.map(peers, (peer, id) => id);
function getIds () {
return _.map(peers, (peer, id) => id)
}
function clear() {
debug('clear');
_.each(peers, (_, userId) => destroy(userId));
peers = {};
function clear () {
debug('clear')
_.each(peers, (_, userId) => destroy(userId))
peers = {}
}
function destroy(userId) {
debug('destroy peer: %s', userId);
let peer = peers[userId];
if (!peer) return debug('peer: %s peer not found', userId);
peer.destroy();
delete peers[userId];
function destroy (userId) {
debug('destroy peer: %s', userId)
let peer = peers[userId]
if (!peer) return debug('peer: %s peer not found', userId)
peer.destroy()
delete peers[userId]
}
function message(message) {
message = JSON.stringify({ message });
_.each(peers, peer => peer.send(message));
function message (message) {
message = JSON.stringify({ 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 activeStore = require('../activeStore.js');
const dispatcher = require('../../dispatcher/dispatcher.js')
const activeStore = require('../activeStore.js')
describe('activeStore', () => {
let handleAction = dispatcher.register.mock.calls[0][0];
let onChange = jest.genMockFunction();
let handleAction = dispatcher.register.mock.calls[0][0]
let onChange = jest.genMockFunction()
beforeEach(() => {
onChange.mockClear();
activeStore.addListener(onChange);
});
afterEach(() => activeStore.removeListener(onChange));
onChange.mockClear()
activeStore.addListener(onChange)
})
afterEach(() => activeStore.removeListener(onChange))
describe('mark-active', () => {
it('should mark id as active', () => {
expect(activeStore.getActive()).not.toBeDefined();
expect(activeStore.isActive('user1')).toBe(false);
expect(onChange.mock.calls.length).toBe(0);
expect(activeStore.getActive()).not.toBeDefined()
expect(activeStore.isActive('user1')).toBe(false)
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.isActive('user1')).toBe(true);
expect(activeStore.getActive()).toBe('user1')
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 alertStore = require('../alertStore.js');
const dispatcher = require('../../dispatcher/dispatcher.js')
const alertStore = require('../alertStore.js')
describe('alertStore', () => {
let handleAction, onChange;
let handleAction, onChange
beforeEach(() => {
handleAction = dispatcher.register.mock.calls[0][0];
handleAction({ type: 'alert-clear' });
handleAction = dispatcher.register.mock.calls[0][0]
handleAction({ type: 'alert-clear' })
onChange = jest.genMockFunction();
alertStore.addListener(onChange);
});
onChange = jest.genMockFunction()
alertStore.addListener(onChange)
})
afterEach(() => {
alertStore.removeListener(onChange);
});
alertStore.removeListener(onChange)
})
describe('alert', () => {
it('should add alerts to end of queue and dispatch change', () => {
let alert1 = { message: 'example alert 1' };
let alert2 = { message: 'example alert 2' };
let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 });
handleAction({ type: 'alert', alert: alert2 });
handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 })
expect(onChange.mock.calls.length).toBe(2);
expect(alertStore.getAlerts()).toEqual([ alert1, alert2 ]);
expect(alertStore.getAlert()).toBe(alert1);
});
});
expect(onChange.mock.calls.length).toBe(2)
expect(alertStore.getAlerts()).toEqual([ alert1, alert2 ])
expect(alertStore.getAlert()).toBe(alert1)
})
})
describe('alert-dismiss', () => {
it('should remove alert and dispatch change', () => {
let alert1 = { message: 'example alert 1' };
let alert2 = { message: 'example alert 2' };
let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 });
handleAction({ type: 'alert', alert: alert2 });
handleAction({ type: 'alert-dismiss', alert: alert1 });
handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 })
handleAction({ type: 'alert-dismiss', alert: alert1 })
expect(onChange.mock.calls.length).toBe(3);
expect(alertStore.getAlerts()).toEqual([ alert2 ]);
expect(alertStore.getAlert()).toBe(alert2);
});
});
expect(onChange.mock.calls.length).toBe(3)
expect(alertStore.getAlerts()).toEqual([ alert2 ])
expect(alertStore.getAlert()).toBe(alert2)
})
})
describe('alert-clear', () => {
it('should remove all alerts', () => {
let alert1 = { message: 'example alert 1' };
let alert2 = { message: 'example alert 2' };
let alert1 = { message: 'example alert 1' }
let alert2 = { message: 'example alert 2' }
handleAction({ type: 'alert', alert: alert1 });
handleAction({ type: 'alert', alert: alert2 });
handleAction({ type: 'alert-clear' });
handleAction({ type: 'alert', alert: alert1 })
handleAction({ type: 'alert', alert: alert2 })
handleAction({ type: 'alert-clear' })
expect(onChange.mock.calls.length).toBe(3);
expect(alertStore.getAlerts()).toEqual([]);
expect(alertStore.getAlert()).not.toBeDefined();
});
});
});
expect(onChange.mock.calls.length).toBe(3)
expect(alertStore.getAlerts()).toEqual([])
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 store = require('../notificationsStore.js');
const dispatcher = require('../../dispatcher/dispatcher.js')
const store = require('../notificationsStore.js')
describe('store', () => {
let handleAction, onChange;
let handleAction, onChange
beforeEach(() => {
dispatcher.dispatch.mockClear();
handleAction = dispatcher.register.mock.calls[0][0];
dispatcher.dispatch.mockClear()
handleAction = dispatcher.register.mock.calls[0][0]
handleAction({ type: 'notify-clear' });
handleAction({ type: 'notify-clear' })
onChange = jest.genMockFunction();
store.addListener(onChange);
});
onChange = jest.genMockFunction()
store.addListener(onChange)
})
describe('notify', () => {
it('should add notification and dispatch change', () => {
let notif1 = { message: 'example notif 1' };
let notif2 = { message: 'example notif 2' };
let notif1 = { message: 'example notif 1' }
let notif2 = { message: 'example notif 2' }
handleAction({ type: 'notify', notification: notif1 });
handleAction({ type: 'notify', notification: notif2 });
handleAction({ type: 'notify', notification: notif1 })
handleAction({ type: 'notify', notification: notif2 })
expect(onChange.mock.calls.length).toBe(2);
expect(store.getNotifications()).toEqual([ notif1, notif2 ]);
expect(store.getNotifications(1)).toEqual([ notif2 ]);
expect(store.getNotifications(3)).toEqual([ notif1, notif2 ]);
});
expect(onChange.mock.calls.length).toBe(2)
expect(store.getNotifications()).toEqual([ notif1, notif2 ])
expect(store.getNotifications(1)).toEqual([ notif2 ])
expect(store.getNotifications(3)).toEqual([ notif1, notif2 ])
})
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(store.getNotifications()).toEqual([ notif1 ]);
expect(onChange.mock.calls.length).toBe(1)
expect(store.getNotifications()).toEqual([ notif1 ])
jest.runAllTimers();
jest.runAllTimers()
expect(onChange.mock.calls.length).toBe(2);
expect(store.getNotifications()).toEqual([]);
});
});
expect(onChange.mock.calls.length).toBe(2)
expect(store.getNotifications()).toEqual([])
})
})
describe('notify-dismiss', () => {
it('should remove notif and dispatch change', () => {
let notif1 = { message: 'example notif 1' };
let notif2 = { message: 'example notif 2' };
let notif1 = { message: 'example notif 1' }
let notif2 = { message: 'example notif 2' }
handleAction({ type: 'notify', notification: notif1 });
handleAction({ type: 'notify', notification: notif2 });
handleAction({ type: 'notify-dismiss', notification: notif1 });
handleAction({ type: 'notify', notification: notif1 })
handleAction({ type: 'notify', notification: notif2 })
handleAction({ type: 'notify-dismiss', notification: notif1 })
expect(onChange.mock.calls.length).toBe(3);
expect(store.getNotifications()).toEqual([ notif2 ]);
expect(store.getNotifications(2)).toEqual([ notif2 ]);
});
});
});
expect(onChange.mock.calls.length).toBe(3)
expect(store.getNotifications()).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 dispatcher = require('../../dispatcher/dispatcher.js');
const streamStore = require('../streamStore.js');
const createObjectUrl = require('../../browser/createObjectURL.js')
const dispatcher = require('../../dispatcher/dispatcher.js')
const streamStore = require('../streamStore.js')
describe('streamStore', () => {
let handleAction = dispatcher.register.mock.calls[0][0];
let onChange = jest.genMockFunction();
let handleAction = dispatcher.register.mock.calls[0][0]
let onChange = jest.genMockFunction()
beforeEach(() => {
onChange.mockClear();
streamStore.addListener(onChange);
});
afterEach(() => streamStore.removeListener(onChange));
onChange.mockClear()
streamStore.addListener(onChange)
})
afterEach(() => streamStore.removeListener(onChange))
describe('add-stream and remove-stream', () => {
it('should add a stream', () => {
let stream = {};
let stream = {}
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({
stream,
url: 'url1'
});
expect(onChange.mock.calls.length).toEqual(1);
});
})
expect(onChange.mock.calls.length).toEqual(1)
})
it('should add a stream multiple times', () => {
let stream1 = {};
let stream2 = {};
let stream1 = {}
let stream2 = {}
createObjectUrl.mockImplementation(stream => {
if (stream === stream1) return 'url1';
if (stream === stream2) return 'url2';
});
if (stream === stream1) return 'url1'
if (stream === stream2) return 'url2'
})
handleAction({ type: 'add-stream', userId: 'user1', stream: stream1 });
handleAction({ type: 'add-stream', userId: 'user2', stream: stream2 });
handleAction({ type: 'add-stream', userId: 'user1', stream: stream1 })
handleAction({ type: 'add-stream', userId: 'user2', stream: stream2 })
expect(streamStore.getStream('user1')).toEqual({
stream: stream1,
url: 'url1'
});
})
expect(streamStore.getStream('user2')).toEqual({
stream: stream2,
url: 'url2'
});
})
expect(streamStore.getStreams()).toEqual({
user1: {
stream: stream1,
@ -62,20 +60,18 @@ describe('streamStore', () => {
stream: stream2,
url: 'url2'
}
});
expect(onChange.mock.calls.length).toEqual(2);
});
})
expect(onChange.mock.calls.length).toEqual(2)
})
it('should remove a stream', () => {
let stream = {};
let stream = {}
handleAction({ type: 'add-stream', userId: 'user1', stream });
handleAction({ type: 'remove-stream', userId: 'user1' });
handleAction({ type: 'add-stream', userId: 'user1', stream })
handleAction({ type: 'remove-stream', userId: 'user1' })
expect(streamStore.getStream('user1')).not.toBeDefined();
expect(onChange.mock.calls.length).toEqual(2);
});
});
});
expect(streamStore.getStream('user1')).not.toBeDefined()
expect(onChange.mock.calls.length).toEqual(2)
})
})
})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,17 +1,17 @@
#!/usr/bin/env node
'use strict';
'use strict'
if (!process.env.DEBUG) {
process.env.DEBUG = 'peer-calls:*';
process.env.DEBUG = 'peer-calls:*'
}
const app = require('./server/app.js');
const os = require('os');
const app = require('./server/app.js')
const os = require('os')
let port = process.env.PORT || 3000;
let ifaces = os.networkInterfaces();
let port = process.env.PORT || 3000
let ifaces = os.networkInterfaces()
app.http.listen(port, function() {
app.http.listen(port, function () {
Object.keys(ifaces).forEach(ifname =>
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';
jest.unmock('../socket.js');
jest.unmock('events');
jest.unmock('underscore');
'use strict'
jest.unmock('../socket.js')
jest.unmock('events')
jest.unmock('underscore')
const EventEmitter = require('events').EventEmitter;
const handleSocket = require('../socket.js');
const EventEmitter = require('events').EventEmitter
const handleSocket = require('../socket.js')
describe('socket', () => {
let socket, io, rooms;
let socket, io, rooms
beforeEach(() => {
socket = new EventEmitter();
socket.id = 'socket0';
socket.join = jest.genMockFunction();
socket.leave = jest.genMockFunction();
rooms = {};
socket = new EventEmitter()
socket.id = 'socket0'
socket.join = jest.genMockFunction()
socket.leave = jest.genMockFunction()
rooms = {}
io = {};
io = {}
io.in = io.to = jest.genMockFunction().mockImplementation(room => {
return (rooms[room] = rooms[room] || {
emit: jest.genMockFunction()
});
});
})
})
io.sockets = {
adapter: {
@ -41,73 +40,66 @@ describe('socket', () => {
}
}
}
};
}
socket.leave = jest.genMockFunction();
socket.join = jest.genMockFunction();
});
socket.leave = jest.genMockFunction()
socket.join = jest.genMockFunction()
})
it('should be a function', () => {
expect(typeof handleSocket).toBe('function');
});
expect(typeof handleSocket).toBe('function')
})
describe('socket events', () => {
beforeEach(() => handleSocket(socket, io));
beforeEach(() => handleSocket(socket, io))
describe('signal', () => {
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([[
'signal', {
userId: 'socket0',
signal
}
]]);
});
});
]])
})
})
describe('ready', () => {
it('should call socket.leave if socket.room', () => {
socket.room = 'room1';
socket.emit('ready', 'room2');
socket.room = 'room1'
socket.emit('ready', 'room2')
expect(socket.leave.mock.calls).toEqual([[ 'room1' ]]);
expect(socket.join.mock.calls).toEqual([[ 'room2' ]]);
});
expect(socket.leave.mock.calls).toEqual([[ 'room1' ]])
expect(socket.join.mock.calls).toEqual([[ 'room2' ]])
})
it('should call socket.join to room', () => {
socket.emit('ready', 'room3');
expect(socket.join.mock.calls).toEqual([[ 'room3' ]]);
});
socket.emit('ready', 'room3')
expect(socket.join.mock.calls).toEqual([[ 'room3' ]])
})
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([[
'users', {
initiator: 'socket0',
users: [{
id: 'socket0',
id: 'socket0'
}, {
id: 'socket1',
id: 'socket1'
}, {
id: 'socket2'
}]
}
]]);
});
});
});
});
]])
})
})
})
})

View File

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

View File

@ -1,45 +1,45 @@
#!/usr/bin/env node
'use strict';
const express = require('express');
const handleSocket = require('./socket.js');
const os = require('os');
const path = require('path');
'use strict'
const express = require('express')
const handleSocket = require('./socket.js')
const os = require('os')
const path = require('path')
// Require in express.Router Middleware.
const callRouter = require('./routes/call');
const siteRouter = require('./routes/index');
const callRouter = require('./routes/call')
const siteRouter = require('./routes/index')
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade')
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) {
app.use('/js', express.static(path.join(__dirname, '../client')));
app.use('/css', express.static(path.join(__dirname, '../css')));
app.use('/js', express.static(path.join(__dirname, '../client')))
app.use('/css', express.static(path.join(__dirname, '../css')))
} else {
const browserify = require('browserify-middleware');
const less = require('less-middleware');
const browserify = require('browserify-middleware')
const less = require('less-middleware')
browserify.settings({
transform: ['babelify']
});
})
const tempDir = path.join(os.tmpDir(), 'node-peer-calls-cache');
app.use('/js', browserify(path.join(__dirname, '../client')));
app.use('/css', less(path.join(__dirname, '../less'), { dest: tempDir}));
app.use('/css', express.static(tempDir));
const tempDir = path.join(os.tmpDir(), 'node-peer-calls-cache')
app.use('/js', browserify(path.join(__dirname, '../client')))
app.use('/css', less(path.join(__dirname, '../less'), { dest: tempDir}))
app.use('/css', express.static(tempDir))
app.use('/css/fonts', express.static(
path.join(__dirname, '../less/fonts')));
path.join(__dirname, '../less/fonts')))
}
// using Express.Router Middleware
app.use('/call', callRouter);
app.use('/', siteRouter);
app.use('/call', callRouter)
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
'use strict';
const config = require('config');
const turn = require('../turn.js');
const router = require('express').Router();
const uuid = require('uuid');
'use strict'
const config = require('config')
const turn = require('../turn.js')
const router = require('express').Router()
const uuid = require('uuid')
const cfgIceServers = config.get('iceServers');
const cfgIceServers = config.get('iceServers')
router.get('/', (req, res) => {
let prefix = 'call/';
if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = '';
res.redirect(prefix + uuid.v4());
});
let prefix = 'call/'
if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = ''
res.redirect(prefix + uuid.v4())
})
router.get('/:callId', (req, res) => {
const iceServers = turn.processServers(cfgIceServers);
const iceServers = turn.processServers(cfgIceServers)
res.render('call', {
callId: encodeURIComponent(req.params.callId),
iceServers
});
});
})
})
module.exports = router;
module.exports = router

View File

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

View File

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

View File

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