Generate userIDs on server-side

We don't want to depend on:

1) socket.io generated IDs because they change on server reconnect
2) simple-peer generated IDs because they change for every peer
connection

We generate a single ID when the call web page is refreshed and use that
throughout the session (until page refresh).

We keep relations of user-id to socket-id on the server side in memory
and use that to get to the right socket. In the future this might be
replaced with Redis to allow multiple nodes.

If the server is restarted, but people have active calls, we want them
to keep using the active peer connections and only connect to new peers.

Ideally, we do not want to disturb the active peer connections, but peer
connections might be restarted because the in-memory store will not have
the information on for any peers in the room upon restart.
This commit is contained in:
Jerko Steiner 2020-03-13 13:33:51 +01:00
parent ba92214296
commit cd4979c3be
21 changed files with 210 additions and 98 deletions

View File

@ -42,4 +42,6 @@ export const valueOf = jest.fn()
export const callId = 'call1234' export const callId = 'call1234'
export const userId = 'user1234'
export const iceServers = [] export const iceServers = []

View File

@ -6,7 +6,7 @@ import * as CallActions from './CallActions'
import * as SocketActions from './SocketActions' import * as SocketActions from './SocketActions'
import * as constants from '../constants' import * as constants from '../constants'
import socket from '../socket' import socket from '../socket'
import { callId } from '../window' import { callId, userId } from '../window'
import { bindActionCreators, createStore, AnyAction, combineReducers, applyMiddleware } from 'redux' import { bindActionCreators, createStore, AnyAction, combineReducers, applyMiddleware } from 'redux'
import reducers from '../reducers' import reducers from '../reducers'
import { middlewares } from '../middlewares' import { middlewares } from '../middlewares'
@ -60,6 +60,7 @@ describe('CallActions', () => {
expect((SocketActions.handshake as jest.Mock).mock.calls).toEqual([[{ expect((SocketActions.handshake as jest.Mock).mock.calls).toEqual([[{
socket, socket,
roomName: callId, roomName: callId,
userId: userId,
}]]) }]])
}) })

View File

@ -1,6 +1,6 @@
import socket from '../socket' import socket from '../socket'
import { ThunkResult } from '../store' import { ThunkResult } from '../store'
import { callId } from '../window' import { callId, userId } from '../window'
import * as NotifyActions from './NotifyActions' import * as NotifyActions from './NotifyActions'
import * as SocketActions from './SocketActions' import * as SocketActions from './SocketActions'
@ -25,6 +25,7 @@ async (dispatch, getState) => {
dispatch(SocketActions.handshake({ dispatch(SocketActions.handshake({
socket, socket,
roomName: callId, roomName: callId,
userId,
})) }))
dispatch(initialize()) dispatch(initialize())
resolve() resolve()

View File

@ -12,7 +12,7 @@ import { PEERCALLS, PEER_EVENT_DATA, ME } from '../constants'
describe('PeerActions', () => { describe('PeerActions', () => {
function createSocket () { function createSocket () {
const socket = new EventEmitter() as unknown as ClientSocket const socket = new EventEmitter() as unknown as ClientSocket
socket.id = 'user1' socket.id = 'socket-id-user-1'
return socket return socket
} }
@ -30,7 +30,7 @@ describe('PeerActions', () => {
dispatch = store.dispatch dispatch = store.dispatch
getState = store.getState getState = store.getState
user = { id: 'user2' } user = { id: 'user1' }
socket = createSocket() socket = createSocket()
instances = (Peer as any).instances = []; instances = (Peer as any).instances = [];
(Peer as unknown as jest.Mock).mockClear() (Peer as unknown as jest.Mock).mockClear()
@ -40,7 +40,7 @@ describe('PeerActions', () => {
describe('create', () => { describe('create', () => {
it('creates a new peer', () => { it('creates a new peer', () => {
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })( PeerActions.createPeer({ socket, user, initiator: 'other-user', stream })(
dispatch, getState) dispatch, getState)
expect(instances.length).toBe(1) expect(instances.length).toBe(1)
@ -52,7 +52,7 @@ describe('PeerActions', () => {
it('sets initiator correctly', () => { it('sets initiator correctly', () => {
PeerActions PeerActions
.createPeer({ .createPeer({
socket, user, initiator: 'user1', stream, socket, user, initiator: user.id, stream,
})(dispatch, getState) })(dispatch, getState)
expect(instances.length).toBe(1) expect(instances.length).toBe(1)
@ -124,7 +124,7 @@ describe('PeerActions', () => {
const { list } = store.getState().messages const { list } = store.getState().messages
expect(list.length).toBeGreaterThan(0) expect(list.length).toBeGreaterThan(0)
expect(list[list.length - 1]).toEqual({ expect(list[list.length - 1]).toEqual({
userId: 'user2', userId: user.id,
timestamp: jasmine.any(String), timestamp: jasmine.any(String),
image: undefined, image: undefined,
message: 'test', message: 'test',

View File

@ -173,7 +173,7 @@ export function createPeer (options: CreatePeerOptions) {
} }
const peer = new Peer({ const peer = new Peer({
initiator: socket.id === initiator, initiator: userId === initiator,
config: { iceServers }, config: { iceServers },
// Allow the peer to receive video, even if it's not sending stream: // Allow the peer to receive video, even if it's not sending stream:
// https://github.com/feross/simple-peer/issues/95 // https://github.com/feross/simple-peer/issues/95

View File

@ -9,6 +9,7 @@ import { createStore, Store, GetState } from '../store'
import { ClientSocket } from '../socket' import { ClientSocket } from '../socket'
import { Dispatch } from 'redux' import { Dispatch } from 'redux'
import { MediaStream } from '../window' import { MediaStream } from '../window'
import { SocketEvent } from '../../shared'
describe('SocketActions', () => { describe('SocketActions', () => {
const roomName = 'bla' const roomName = 'bla'
@ -29,22 +30,39 @@ describe('SocketActions', () => {
instances = (Peer as any).instances = [] instances = (Peer as any).instances = []
}) })
const userA = {
socketId: 'socket-a',
userId: 'user-a',
}
const userId = userA.userId
const userB = {
socketId: 'socket-b',
userId: 'user-b',
}
const userC = {
socketId: 'socket-c',
userId: 'user-c',
}
describe('handshake', () => { describe('handshake', () => {
describe('users', () => { describe('users', () => {
beforeEach(() => { beforeEach(() => {
SocketActions.handshake({ socket, roomName })(dispatch, getState) SocketActions
.handshake({ socket, roomName, userId })(dispatch, getState)
const payload = { const payload = {
users: [{ id: 'a' }, { id: 'b' }], users: [userA, userB],
initiator: 'a', initiator: userA.userId,
} }
socket.emit('users', payload) socket.emit('users', payload)
expect(instances.length).toBe(1) expect(instances.length).toBe(1)
}) })
it('adds a peer for each new user and destroys peers for missing', () => { it('adds a peer for each new user and destroys missing peers', () => {
const payload = { const payload = {
users: [{ id: 'a' }, { id: 'c' }], users: [userA, userC],
initiator: 'c', initiator: userC.userId,
} }
socket.emit(constants.SOCKET_EVENT_USERS, payload) socket.emit(constants.SOCKET_EVENT_USERS, payload)
@ -59,16 +77,17 @@ describe('SocketActions', () => {
let data: Peer.SignalData let data: Peer.SignalData
beforeEach(() => { beforeEach(() => {
data = {} as any data = {} as any
SocketActions.handshake({ socket, roomName })(dispatch, getState) SocketActions
.handshake({ socket, roomName, userId })(dispatch, getState)
socket.emit('users', { socket.emit('users', {
initiator: 'a', initiator: userA.userId,
users: [{ id: 'a' }, { id: 'b' }], users: [userA, userB],
}) })
}) })
it('should forward signal to peer', () => { it('should forward signal to peer', () => {
socket.emit('signal', { socket.emit('signal', {
userId: 'b', userId: userB.userId,
signal: data, signal: data,
}) })
@ -94,11 +113,12 @@ describe('SocketActions', () => {
let ready = false let ready = false
socket.once('ready', () => { ready = true }) socket.once('ready', () => { ready = true })
SocketActions.handshake({ socket, roomName })(dispatch, getState) SocketActions
.handshake({ socket, roomName, userId })(dispatch, getState)
socket.emit('users', { socket.emit('users', {
initiator: 'a', initiator: userA.userId,
users: [{ id: 'a' }, { id: 'b' }], users: [userA, userB],
}) })
expect(instances.length).toBe(1) expect(instances.length).toBe(1)
peer = instances[0] peer = instances[0]
@ -117,8 +137,8 @@ describe('SocketActions', () => {
it('emits socket signal with user id', done => { it('emits socket signal with user id', done => {
const signal = { bla: 'bla' } const signal = { bla: 'bla' }
socket.once('signal', (payload: SocketActions.SignalOptions) => { socket.once('signal', (payload: SocketEvent['signal']) => {
expect(payload.userId).toEqual('b') expect(payload.userId).toEqual(userB.userId)
expect(payload.signal).toBe(signal) expect(payload.signal).toBe(signal)
done() done()
}) })
@ -139,8 +159,8 @@ describe('SocketActions', () => {
peer.emit(constants.PEER_EVENT_TRACK, stream.getTracks()[0], stream) peer.emit(constants.PEER_EVENT_TRACK, stream.getTracks()[0], stream)
expect(store.getState().streams).toEqual({ expect(store.getState().streams).toEqual({
b: { [userB.userId]: {
userId: 'b', userId: userB.userId,
streams: [{ streams: [{
stream, stream,
type: undefined, type: undefined,
@ -159,8 +179,8 @@ describe('SocketActions', () => {
// test stream with two tracks // test stream with two tracks
peer.emit(constants.PEER_EVENT_TRACK, track, stream) peer.emit(constants.PEER_EVENT_TRACK, track, stream)
expect(store.getState().streams).toEqual({ expect(store.getState().streams).toEqual({
b: { [userB.userId]: {
userId: 'b', userId: userB.userId,
streams: [{ streams: [{
stream, stream,
type: undefined, type: undefined,
@ -171,7 +191,7 @@ describe('SocketActions', () => {
}) })
it('removes stream & peer from store', () => { it('removes stream & peer from store', () => {
expect(store.getState().peers).toEqual({ b: peer }) expect(store.getState().peers).toEqual({ [userB.userId]: peer })
peer.emit('close') peer.emit('close')
expect(store.getState().streams).toEqual({}) expect(store.getState().streams).toEqual({})
expect(store.getState().peers).toEqual({}) expect(store.getState().peers).toEqual({})

View File

@ -3,9 +3,9 @@ import * as PeerActions from '../actions/PeerActions'
import * as constants from '../constants' import * as constants from '../constants'
import keyBy from 'lodash/keyBy' import keyBy from 'lodash/keyBy'
import _debug from 'debug' import _debug from 'debug'
import { SignalData } from 'simple-peer'
import { Dispatch, GetState } from '../store' import { Dispatch, GetState } from '../store'
import { ClientSocket } from '../socket' import { ClientSocket } from '../socket'
import { SocketEvent } from '../../shared'
const debug = _debug('peercalls') const debug = _debug('peercalls')
@ -15,24 +15,16 @@ export interface SocketHandlerOptions {
stream?: MediaStream stream?: MediaStream
dispatch: Dispatch dispatch: Dispatch
getState: GetState getState: GetState
}
export interface SignalOptions {
signal: SignalData
userId: string userId: string
} }
export interface UsersOptions {
initiator: string
users: Array<{ id: string }>
}
class SocketHandler { class SocketHandler {
socket: ClientSocket socket: ClientSocket
roomName: string roomName: string
stream?: MediaStream stream?: MediaStream
dispatch: Dispatch dispatch: Dispatch
getState: GetState getState: GetState
userId: string
constructor (options: SocketHandlerOptions) { constructor (options: SocketHandlerOptions) {
this.socket = options.socket this.socket = options.socket
@ -40,30 +32,36 @@ class SocketHandler {
this.stream = options.stream this.stream = options.stream
this.dispatch = options.dispatch this.dispatch = options.dispatch
this.getState = options.getState this.getState = options.getState
this.userId = options.userId
} }
handleSignal = ({ userId, signal }: SignalOptions) => { handleSignal = ({ userId, signal }: SocketEvent['signal']) => {
const { getState } = this const { getState } = this
const peer = getState().peers[userId] const peer = getState().peers[userId]
// debug('socket signal, userId: %s, signal: %o', userId, signal); // debug('socket signal, userId: %s, signal: %o', userId, signal);
if (!peer) return debug('user: %s, no peer found', userId) if (!peer) return debug('user: %s, no peer found', userId)
peer.signal(signal) peer.signal(signal)
} }
handleUsers = ({ initiator, users }: UsersOptions) => { handleUsers = ({ initiator, users }: SocketEvent['users']) => {
const { socket, stream, dispatch, getState } = this const { socket, stream, dispatch, getState } = this
debug('socket users: %o', users) debug('socket users: %o', users)
this.dispatch(NotifyActions.info('Connected users: {0}', users.length)) this.dispatch(NotifyActions.info('Connected users: {0}', users.length))
const { peers } = this.getState() const { peers } = this.getState()
users users
.filter(user => !peers[user.id] && user.id !== socket.id) .filter(
user =>
user.userId && !peers[user.userId] && user.userId !== this.userId)
.forEach(user => PeerActions.createPeer({ .forEach(user => PeerActions.createPeer({
socket, socket,
user, user: {
// users without id should be filtered out
id: user.userId!,
},
initiator, initiator,
stream, stream,
})(dispatch, getState)) })(dispatch, getState))
const newUsersMap = keyBy(users, 'id') const newUsersMap = keyBy(users, 'userId')
Object.keys(peers) Object.keys(peers)
.filter(id => !newUsersMap[id]) .filter(id => !newUsersMap[id])
.forEach(id => peers[id].destroy()) .forEach(id => peers[id].destroy())
@ -73,11 +71,12 @@ class SocketHandler {
export interface HandshakeOptions { export interface HandshakeOptions {
socket: ClientSocket socket: ClientSocket
roomName: string roomName: string
userId: string
stream?: MediaStream stream?: MediaStream
} }
export function handshake (options: HandshakeOptions) { export function handshake (options: HandshakeOptions) {
const { socket, roomName, stream } = options const { socket, roomName, stream, userId } = options
return (dispatch: Dispatch, getState: GetState) => { return (dispatch: Dispatch, getState: GetState) => {
const handler = new SocketHandler({ const handler = new SocketHandler({
@ -86,6 +85,7 @@ export function handshake (options: HandshakeOptions) {
stream, stream,
dispatch, dispatch,
getState, getState,
userId,
}) })
// remove listeneres to make seocket reusable // remove listeneres to make seocket reusable
@ -95,9 +95,12 @@ export function handshake (options: HandshakeOptions) {
socket.on(constants.SOCKET_EVENT_SIGNAL, handler.handleSignal) socket.on(constants.SOCKET_EVENT_SIGNAL, handler.handleSignal)
socket.on(constants.SOCKET_EVENT_USERS, handler.handleUsers) socket.on(constants.SOCKET_EVENT_USERS, handler.handleUsers)
debug('socket.id: %s', socket.id) debug('userId: %s', userId)
debug('emit ready for room: %s', roomName) debug('emit ready for room: %s', roomName)
dispatch(NotifyActions.info('Ready for connections')) dispatch(NotifyActions.info('Ready for connections'))
socket.emit('ready', roomName) socket.emit('ready', {
room: roomName,
userId,
})
} }
} }

View File

@ -36,13 +36,11 @@ export interface AppProps {
} }
export interface AppState { export interface AppState {
videos: Record<string, unknown>
chatVisible: boolean chatVisible: boolean
} }
export default class App extends React.PureComponent<AppProps, AppState> { export default class App extends React.PureComponent<AppProps, AppState> {
state: AppState = { state: AppState = {
videos: {},
chatVisible: false, chatVisible: false,
} }
handleShowChat = () => { handleShowChat = () => {
@ -92,8 +90,6 @@ export default class App extends React.PureComponent<AppProps, AppState> {
streams, streams,
} = this.props } = this.props
const { videos } = this.state
const chatVisibleClassName = classnames({ const chatVisibleClassName = classnames({
'chat-visible': this.state.chatVisible, 'chat-visible': this.state.chatVisible,
}) })
@ -140,7 +136,6 @@ export default class App extends React.PureComponent<AppProps, AppState> {
const key = localStreams.userId + '_' + i const key = localStreams.userId + '_' + i
return ( return (
<Video <Video
videos={videos}
key={key} key={key}
active={active === key} active={active === key}
onClick={toggleActive} onClick={toggleActive}
@ -168,7 +163,6 @@ export default class App extends React.PureComponent<AppProps, AppState> {
play={play} play={play}
stream={s} stream={s}
userId={key} userId={key}
videos={videos}
/> />
) )
}) })

View File

@ -25,7 +25,6 @@ describe('components/Video', () => {
render () { render () {
return <Video return <Video
ref={this.ref} ref={this.ref}
videos={this.props.videos}
active={this.props.active} active={this.props.active}
stream={this.state.stream || this.props.stream} stream={this.state.stream || this.props.stream}
onClick={this.props.onClick} onClick={this.props.onClick}
@ -38,7 +37,6 @@ describe('components/Video', () => {
} }
let component: VideoWrapper let component: VideoWrapper
let videos: Record<string, unknown> = {}
let video: Video let video: Video
let onClick: (userId: string) => void let onClick: (userId: string) => void
let mediaStream: MediaStream let mediaStream: MediaStream
@ -57,7 +55,6 @@ describe('components/Video', () => {
} }
async function render (args?: Partial<Flags>) { async function render (args?: Partial<Flags>) {
const flags: Flags = Object.assign({}, defaultFlags, args) const flags: Flags = Object.assign({}, defaultFlags, args)
videos = {}
onClick = jest.fn() onClick = jest.fn()
mediaStream = new MediaStream() mediaStream = new MediaStream()
const div = document.createElement('div') const div = document.createElement('div')
@ -70,7 +67,6 @@ describe('components/Video', () => {
ReactDOM.render( ReactDOM.render(
<VideoWrapper <VideoWrapper
ref={instance => resolve(instance!)} ref={instance => resolve(instance!)}
videos={videos}
active={flags.active} active={flags.active}
stream={stream} stream={stream}
onClick={onClick} onClick={onClick}

View File

@ -4,7 +4,7 @@ import socket from '../socket'
import { StreamWithURL } from '../reducers/streams' import { StreamWithURL } from '../reducers/streams'
export interface VideoProps { export interface VideoProps {
videos: Record<string, unknown> // videos: Record<string, unknown>
onClick: (userId: string) => void onClick: (userId: string) => void
active: boolean active: boolean
stream?: StreamWithURL stream?: StreamWithURL
@ -49,7 +49,7 @@ export default class Video extends React.PureComponent<VideoProps> {
this.componentDidUpdate() this.componentDidUpdate()
} }
componentDidUpdate () { componentDidUpdate () {
const { videos, stream } = this.props const { stream } = this.props
const video = this.videoRef.current! const video = this.videoRef.current!
const mediaStream = stream && stream.stream || null const mediaStream = stream && stream.stream || null
const url = stream && stream.url const url = stream && stream.url
@ -60,7 +60,6 @@ export default class Video extends React.PureComponent<VideoProps> {
} else if (video.src !== url) { } else if (video.src !== url) {
video.src = url || '' video.src = url || ''
} }
videos[socket.id] = video
} }
render () { render () {
const { active, mirrored, muted } = this.props const { active, mirrored, muted } = this.props

View File

@ -9,6 +9,7 @@ export const valueOf = (id: string) => {
export const baseUrl = valueOf('baseUrl') export const baseUrl = valueOf('baseUrl')
export const callId = valueOf('callId') export const callId = valueOf('callId')
export const userId = valueOf('userId')
export const iceServers = JSON.parse(valueOf('iceServers')!) export const iceServers = JSON.parse(valueOf('iceServers')!)
export const MediaStream = window.MediaStream export const MediaStream = window.MediaStream

View File

@ -10,6 +10,7 @@ import { config } from './config'
import handleSocket from './socket' import handleSocket from './socket'
import SocketIO from 'socket.io' import SocketIO from 'socket.io'
import request from 'supertest' import request from 'supertest'
import { MemoryStore } from './store'
const io = SocketIO() const io = SocketIO()
@ -61,7 +62,11 @@ describe('server/app', () => {
it('calls handleSocket with socket', () => { it('calls handleSocket with socket', () => {
const socket = { hi: 'me socket' } const socket = { hi: 'me socket' }
io.emit('connection', socket) io.emit('connection', socket)
expect((handleSocket as jest.Mock).mock.calls).toEqual([[ socket, io ]]) expect((handleSocket as jest.Mock).mock.calls).toEqual([[
socket,
io,
jasmine.any(MemoryStore),
]])
}) })
}) })

View File

@ -9,6 +9,7 @@ import SocketIO from 'socket.io'
import call from './routes/call' import call from './routes/call'
import index from './routes/index' import index from './routes/index'
import ejs from 'ejs' import ejs from 'ejs'
import { MemoryStore } from './store'
const debug = _debug('peercalls') const debug = _debug('peercalls')
const logRequest = _debug('peercalls:requests') const logRequest = _debug('peercalls:requests')
@ -48,6 +49,7 @@ router.use('/call', call)
router.use('/', index) router.use('/', index)
app.use(BASE_URL, router) app.use(BASE_URL, router)
io.on('connection', socket => handleSocket(socket, io)) const store = new MemoryStore()
io.on('connection', socket => handleSocket(socket, io, store))
export default server export default server

View File

@ -17,6 +17,7 @@ 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),
userId: v4(),
iceServers, iceServers,
}) })
}) })

View File

@ -1,7 +1,8 @@
import { EventEmitter } from 'events' import { EventEmitter } from 'events'
import { Socket } from 'socket.io' import { Socket } from 'socket.io'
import { TypedIO } from '../shared' import { TypedIO, ServerSocket } from '../shared'
import handleSocket from './socket' import handleSocket from './socket'
import { MemoryStore, Store } from './store'
describe('server/socket', () => { describe('server/socket', () => {
type SocketMock = Socket & { type SocketMock = Socket & {
@ -32,7 +33,23 @@ describe('server/socket', () => {
}) })
}) })
const sockets = {
socket0: {
id: 'socket0',
userId: 'socket0_userid',
},
socket1: {
id: 'socket1',
userId: 'socket1_userid',
},
socket2: {
id: 'socket2',
userId: 'socket2_userid',
},
}
io.sockets = { io.sockets = {
sockets: sockets as any,
adapter: { adapter: {
rooms: { rooms: {
room1: { room1: {
@ -43,9 +60,9 @@ describe('server/socket', () => {
} as any, } as any,
room3: { room3: {
sockets: { sockets: {
'socket0': true, socket0: true,
'socket1': true, socket1: true,
'socket2': true, socket2: true,
}, },
} as any, } as any,
}, },
@ -61,18 +78,24 @@ describe('server/socket', () => {
}) })
describe('socket events', () => { describe('socket events', () => {
beforeEach(() => handleSocket(socket, io)) let store: Store
beforeEach(() => {
store = new MemoryStore()
handleSocket(socket, io, store)
})
describe('signal', () => { describe('signal', () => {
it('should broadcast signal to specific user', () => { it('should broadcast signal to specific user', () => {
store.set('a', 'a-socket-id')
;(socket as ServerSocket) .userId = 'b'
const signal = { type: 'signal' } const 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-socket-id' ]])
expect((io.to('a').emit as jest.Mock).mock.calls).toEqual([[ expect((io.to('a-socket-id').emit as jest.Mock).mock.calls).toEqual([[
'signal', { 'signal', {
userId: 'socket0', userId: 'b',
signal, signal,
}, },
]]) ]])
@ -82,31 +105,43 @@ describe('server/socket', () => {
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', {
userId: 'socket0_userid',
room: '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', {
userId: 'socket0_userid',
room: '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', {
userId: 'socket0_userid',
room: 'room3',
})
expect(io.to.mock.calls).toEqual([[ 'room3' ]]) expect(io.to.mock.calls).toEqual([[ 'room3' ]])
expect((io.to('room3').emit as jest.Mock).mock.calls).toEqual([ expect((io.to('room3').emit as jest.Mock).mock.calls).toEqual([
[ [
'users', { 'users', {
initiator: 'socket0', initiator: 'socket0_userid',
users: [{ users: [{
id: 'socket0', socketId: 'socket0',
userId: 'socket0_userid',
}, { }, {
id: 'socket1', socketId: 'socket1',
userId: 'socket1_userid',
}, { }, {
id: 'socket2', socketId: 'socket2',
userId: 'socket2_userid',
}], }],
}, },
], ],

View File

@ -2,38 +2,59 @@
import _debug from 'debug' import _debug from 'debug'
import map from 'lodash/map' import map from 'lodash/map'
import { ServerSocket, TypedIO } from '../shared' import { ServerSocket, TypedIO } from '../shared'
import { Store } from './store'
const debug = _debug('peercalls:socket') const debug = _debug('peercalls:socket')
export default function handleSocket(socket: ServerSocket, io: TypedIO) { export default function handleSocket(
socket: ServerSocket,
io: TypedIO,
store: Store,
) {
socket.once('disconnect', () => {
if (socket.userId) {
store.remove(socket.userId)
}
})
socket.on('signal', payload => { socket.on('signal', payload => {
// debug('signal: %s, payload: %o', socket.id, payload) // debug('signal: %s, payload: %o', socket.userId, payload)
io.to(payload.userId).emit('signal', { const socketId = store.get(payload.userId)
userId: socket.id, if (socketId) {
io.to(socketId).emit('signal', {
userId: socket.userId,
signal: payload.signal, signal: payload.signal,
}) })
}
}) })
socket.on('ready', roomName => { socket.on('ready', payload => {
debug('ready: %s, room: %s', socket.id, roomName) const { userId, room } = payload
debug('ready: %s, room: %s', userId, room)
if (socket.room) socket.leave(socket.room) if (socket.room) socket.leave(socket.room)
socket.room = roomName socket.userId = userId
socket.join(roomName) store.set(userId, socket.id)
socket.room = roomName socket.room = room
socket.join(room)
socket.room = room
const users = getUsers(roomName) const users = getUsers(room)
debug('ready: %s, room: %s, users: %o', socket.id, roomName, users) debug('ready: %s, room: %s, users: %o', room, users)
io.to(roomName).emit('users', { io.to(room).emit('users', {
initiator: socket.id, initiator: userId,
users, users,
}) })
}) })
function getUsers (roomName: string) { function getUsers (room: string) {
return map(io.sockets.adapter.rooms[roomName].sockets, (_, id) => { return map(io.sockets.adapter.rooms[room].sockets, (_, socketId) => {
return { id } const userSocket = io.sockets.sockets[socketId] as ServerSocket
return {
socketId: socketId,
userId: userSocket.userId,
}
}) })
} }

View File

@ -0,0 +1,2 @@
export * from './store'
export * from './memory'

View File

@ -0,0 +1,17 @@
import { Store } from './store'
export class MemoryStore implements Store {
store: Record<string, string> = {}
get(key: string): string | undefined {
return this.store[key]
}
set(key: string, value: string) {
this.store[key] = value
}
remove(key: string) {
delete this.store[key]
}
}

View File

@ -0,0 +1,5 @@
export interface Store {
set(key: string, value: string): void
get(key: string): string | undefined
remove(key: string): void
}

View File

@ -2,7 +2,13 @@ import { TypedEmitter, TypedEmitterKeys } from './TypedEmitter'
import { SignalData } from 'simple-peer' import { SignalData } from 'simple-peer'
export interface User { export interface User {
id: string socketId: string
userId?: string
}
export interface Ready {
room: string
userId: string
} }
export interface SocketEvent { export interface SocketEvent {
@ -17,13 +23,13 @@ export interface SocketEvent {
} }
connect: undefined connect: undefined
disconnect: undefined disconnect: undefined
ready: string ready: Ready
} }
export type ServerSocket = export type ServerSocket =
Omit<SocketIO.Socket, TypedEmitterKeys> & Omit<SocketIO.Socket, TypedEmitterKeys> &
TypedEmitter<SocketEvent> & TypedEmitter<SocketEvent> &
{ room?: string } { userId?: string, room?: string }
export type TypedIO = SocketIO.Server & { export type TypedIO = SocketIO.Server & {
to(roomName: string): TypedEmitter<SocketEvent> to(roomName: string): TypedEmitter<SocketEvent>

View File

@ -8,6 +8,7 @@
<input type="hidden" id="baseUrl" value="<%= baseUrl %>"> <input type="hidden" id="baseUrl" value="<%= baseUrl %>">
<input type="hidden" id="callId" value="<%= callId %>"> <input type="hidden" id="callId" value="<%= callId %>">
<input type="hidden" id="iceServers" value='<%- JSON.stringify(iceServers) %>'> <input type="hidden" id="iceServers" value='<%- JSON.stringify(iceServers) %>'>
<input type="hidden" id="userId" value="<%= userId %>">
<div id="container"></div> <div id="container"></div>
<script src="<%= baseUrl + '/static/index.js' %>"></script> <script src="<%= baseUrl + '/static/index.js' %>"></script>