1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
| const KurentoClient = require('kurento-client') const http = require('http') const socketIO = require('socket.io') const util = require('util') const { kurentoClient: client, presentors, userSocketMap, viewers } = require('../global') const Video = require('../models').Video const config = require('../config')() const { getUserByToken, checkUserOnline, formatTime } = require('../utils') const moment = require('moment') const candidatesQueue = {}
const bindEvent = io => { io.on('connection', async function (socket) { var sessionId = socket.id var request = socket.request const self = await getUserByToken(socket.handshake.query.token).catch(err => { socket.emit('autherror') socket.disconnect(true) throw err }) const presentorId = socket.handshake.query.presentorId
const ip = request.headers['x-real-ip'] || request.socket.remoteAddress console.log('request ip:', ip) const getLocationPromise = new Promise(resolve => http.get(`http://ip-api.com/json/${ip}?lang=zh-CN`, resolve)).then(res => { return new Promise(resolve => { let data = '' res.on('data', chunk => { data += chunk return data }) res.on('end', () => { resolve(data) }) }) }).then(data => { const { status, country, regionName, city } = JSON.parse(data) if (status !== 'success') throw new Error(data) console.log(regionName + country + city) return `${regionName}${country}${city}` }).catch(_ => { return 'unknown' }) console.log(`socket ${sessionId} connected`)
socket.on('error', _ => { console.log('Connection ' + sessionId + ' error', _) !presentorId && stopPresentor(sessionId) presentorId && stopViewer() })
socket.on('close', function () { console.log('Connection ' + sessionId + ' closed') !presentorId && stopPresentor(sessionId) presentorId && stopViewer() }) socket.on('createPresentor', ({ sdpOffer, invite }) => { createPresentor(socket, sdpOffer, getLocationPromise).then(sdpAnswer => { socket.emit('startResponse', { sdpAnswer }) invite && inviteViewer(self, invite, socket.id) }).catch(error => { return socket.emit('error', { message: error.message }) }) })
socket.on('createViewer', message => { sessionId = socket.id createViewer(presentorId, sessionId, socket, message.sdpOffer).then(viewer => { const roomid = viewer.presentor.socket.id viewer.socket.join(roomid, () => { socket.to(roomid).emit('message', { type: 'viewer-entry', time: moment(new Date()).format('HH:mm:ss'), from: { nickname: self.nickname, avatar: self.avatar } }) }) }).catch(err => { console.log(`create viewer for ${presentorId} error`, err) }) })
socket.on('online', _ => { console.log(`${self.nickname} online`) userSocketMap[self.nickname] = socket }) socket.on('offline', _ => { console.log(`${self.nickname} offline`) userSocketMap[self.nickname] = null }) socket.on('acceptcall', ({ from }) => { const { nickname } = from console.log('acceptcall socket id', socket.id) const friendSocket = userSocketMap[nickname] friendSocket.emit('callaccepted', { to: self, linkId: socket.id }) }) socket.on('rejectcall', ({ from }) => { const friendSocket = userSocketMap[from.nickname] friendSocket.emit('callrejected', { to: self }) })
socket.on('stopPresentor', message => { stopPresentor(sessionId, getLocationPromise) })
socket.on('stopViewer', _ => { stopViewer(socket, self) })
socket.on('onIceCandidate', message => { onIceCandidate(sessionId, message.candidate, presentorId) })
socket.on('inviteViewer', ({ nickname }) => { userSocketMap[nickname].emit('call', { from: self }) }) }) }
function createPresentor (socket, sdpOffer, getLocationPromise) { const sessionId = socket.id if (!sessionId) { return Promise.reject(new Error('Cannot use undefined sessionId')) } console.log(`create presentor ${sessionId}`) return Promise.all([ util.promisify(client.create)('MediaPipeline'), getLocationPromise ]).then(([ pipeline, location ]) => { const { mediaProfile, path } = config.recordOptions const fileName = `${formatTime(new Date())}.mp4` const uri = `${path}/${fileName}` const recordOptions = { mediaProfile, uri }
return Promise.all([ util.promisify(pipeline.create)('WebRtcEndpoint'), util.promisify(pipeline.create)('RecorderEndpoint', recordOptions) ]).then(([ webRtcEndpoint, recorderEndpoint ]) => { webRtcEndpoint.on('OnIceCandidate', function (event) { const candidate = KurentoClient.getComplexType('IceCandidate')(event.candidate) socket.emit('iceCandidate', { candidate }) }) recorderEndpoint.on('Recording', function (error) { console.log('recording', error) presentors[sessionId].startTime = Math.round(Date.now() / 1000) presentors[sessionId].recorderPath = recordOptions.uri }) recorderEndpoint.on('Stopped', err => { console.log('record stoped', err) const endTime = Math.round(Date.now() / 1000) const { startTime } = presentors[sessionId] if (!startTime || endTime - startTime < 1) { console.log('record time to short') return }
getLocationPromise.then(async location => { Video.create({ location, uri: await recorderEndpoint.getUri(), comments: '', duration: endTime - startTime }).then(tableRow => { console.log('video save to database success', tableRow) return tableRow.id }) }) }) if (candidatesQueue[sessionId]) { while (candidatesQueue[sessionId].length) { const candidate = candidatesQueue[sessionId].shift() webRtcEndpoint.addIceCandidate(candidate) } } return Promise.all([ webRtcEndpoint.connect(recorderEndpoint), webRtcEndpoint.connect(webRtcEndpoint) ]).then(_ => { recorderEndpoint.record(function (error) { console.log('record start', error) }) return webRtcEndpoint.processOffer(sdpOffer) }).then(async sdpAnswer => { webRtcEndpoint.gatherCandidates(function (error) { if (error) { return Promise.reject(error) } }) presentors[sessionId] = { pipeline: pipeline, webRtcEndpoint: webRtcEndpoint, recorderEndpoint: recorderEndpoint, socket: socket, viewers: {} } return sdpAnswer }) }) }) }
function inviteViewer (inviter, nickname, linkId) { console.log('invite', nickname)
return checkUserOnline(nickname).then(_ => { userSocketMap[nickname].emit('call', { from: inviter, linkId }) }).catch(error => { console.log('invite error', error.message) userSocketMap[inviter.nickname].emit('callerror', { message: error.message }) }) }
function createViewer (presentorId, sessionId, socket, sdpOffer) { console.log(`create viewer for presentor ${presentorId} start`) if (!presentors[presentorId]) return Promise.reject(new Error('no presentor')) const { pipeline, webRtcEndpoint: presentor, viewers: presentorViewers } = presentors[presentorId] if (!pipeline) return Promise.reject(new Error('no presentor')) return util.promisify(pipeline.create)('WebRtcEndpoint').then(webRtcEndpoint => { if (candidatesQueue[sessionId]) { while (candidatesQueue[sessionId].length) { var candidate = candidatesQueue[sessionId].shift() webRtcEndpoint.addIceCandidate(candidate) } } webRtcEndpoint.on('OnIceCandidate', function (event) { var candidate = KurentoClient.getComplexType('IceCandidate')(event.candidate) socket.emit('iceCandidate', { candidate }) }) viewers[sessionId] = presentorViewers[sessionId] = { webRtcEndpoint: webRtcEndpoint, socket: socket, presentor: presentors[presentorId] } return webRtcEndpoint }).then(webRtcEndpoint => { return presentor.connect(webRtcEndpoint).then(_ => { return webRtcEndpoint.processOffer(sdpOffer) }).then(sdpAnswer => { socket.emit('startResponse', { sdpAnswer }) return webRtcEndpoint.gatherCandidates() }).then(_ => { return viewers[sessionId] }) }) } async function stopPresentor (sessionId, getLocationPromise) { if (presentors[sessionId]) { const { recorderEndpoint, pipeline, viewers, startTime, recorderPath } = presentors[sessionId] recorderEndpoint.stop(function (error) { console.log('stop record', error) const endTime = Math.round(Date.now() / 1000) if (!startTime || endTime - startTime < 1) { console.log('record time to short') return }
getLocationPromise.then(async location => { Video.create({ location, uri: recorderPath, comments: '', duration: endTime - startTime }).then(tableRow => { console.log('video save to database success', tableRow.id) return tableRow.id }) }) }) console.info('Releasing pipeline') pipeline.release() Object.values(viewers).forEach(viewer => { viewer.socket.emit('presentorgone') }) delete presentors[sessionId] delete candidatesQueue[sessionId] } }
function stopViewer (socket, self) { const sessionId = socket.id if (!viewers[sessionId]) return const roomid = viewers[sessionId].presentor.socket.id socket.to(roomid).emit('message', { type: 'viewer-leave', time: moment(new Date()).format('HH:mm:ss'), from: { nickname: self.nickname, avatar: self.avatar } }) socket.leave(roomid) socket.disconnect() delete viewers[sessionId].presentor.viewers[sessionId] delete viewers[sessionId] }
function onIceCandidate (sessionId, _candidate, presentorId) { var candidate = KurentoClient.getComplexType('IceCandidate')(_candidate) if (presentorId && presentors[presentorId] && presentors[presentorId].viewers[sessionId]) { console.log('sending viewer candidate') const webRtcEndpoint = presentors[presentorId].viewers[sessionId].webRtcEndpoint webRtcEndpoint.addIceCandidate(candidate) } else if (presentors[sessionId]) { console.info('Sending presentor candidate') var webRtcEndpoint = presentors[sessionId].webRtcEndpoint webRtcEndpoint.addIceCandidate(candidate) } else { console.info('Queueing candidate') if (!candidatesQueue[sessionId]) { candidatesQueue[sessionId] = [] } candidatesQueue[sessionId].push(candidate) } }
module.exports = function (server) { const io = socketIO(server, { path: '/socket.io/webrtc' }) bindEvent(io) }
|