-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.html
More file actions
557 lines (513 loc) · 23.7 KB
/
index.html
File metadata and controls
557 lines (513 loc) · 23.7 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<!--
Copyright (c) 2013 SMB Phone Inc.
License: MIT
Author: Christoph Dorn <christoph@christophdorn.com> [github.com/cadorn]
-->
<html><head>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/css/base/jquery-ui.css">
<link rel="stylesheet" href="style.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.5/require.min.js"></script>
<script>
// Alias dependencies for our client.
require.config({
paths: {
'webrtc-shim': 'https://raw.github.com/openpeer/webrtc-shim/v0.1.1/webrtc-shim',
'rolodex': 'http://webrtc.hookflash.me/.openpeer-rolodex/client',
'rolodex-presence': 'http://webrtc.hookflash.me/.openpeer-rolodex-presence/client'
}
});
</script>
</head><body>
<a href="https://github.com/openpeer/webrtc-demo"><img src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png"></a>
<!--
############################################################
# Various UI views. Only one will show at a time.
############################################################
-->
<div id="loading" class="view">
<h1>Loading ...</h1>
</div>
<div id="login" class="view hidden">
<h1>Login</h1>
<button onClick="window.rolodex.loginService('facebook')">Facebook</button>
<button onClick="window.rolodex.loginService('linkedin')">LinkedIn</button>
<button onClick="window.rolodex.loginService('twitter')">Twitter</button>
<button onClick="window.rolodex.loginService('github')">Github</button>
</div>
<div id="contacts" class="view hidden">
<h1>Contacts</h1>
<button onClick="window.logout()">Logout</button>
<ul></ul>
<button onClick="window.refetch()">Refetch</button>
</div>
<div id="call" class="view hidden">
<h1>Calling <span></span></h1>
<div class="hidden">
<button onClick="window.hangup()">Hangup</button>
<div>Waiting for peer to connect ...</div>
<div class="hidden">
<div class="text">
<div id="messages"></div>
<input id="send" type="text"/>
</div>
<div class="video">
<video id="localVideo" autoplay="autoplay" muted="true"></video>
<video id="remoteVideo" autoplay="autoplay"></video>
</div>
</div>
</div>
<div id="call-accept-dialog" title="Accept Call ?" class="hidden">
<p>Do you want to accept a call from <span></span></p>
</div>
<div id="call-declined-dialog" title="Call was declined" class="hidden">
<p><span></span> declined your call.</p>
</div>
<div id="call-cancel-dialog" title="Calling" class="hidden">
<p>Trying to initiate call to <span></span></p>
</div>
<div id="call-hungup-dialog" title="Hangup" class="hidden">
<p><span></span> hung up the call</p>
</div>
</div>
<div id="logout" class="view hidden">
<h1>More recent login at another location</h1>
</div>
<script>
// Use RequireJS to load dependencies.
require([
'webrtc-shim',
'rolodex/client',
'rolodex-presence/client'
], function(WEBRTC_SHIM, ROLODEX, ROLODEX_PRESENCE) {
// The service ID for the currently logged in service.
var serviceId = null;
// Reference to a currently active WebRTC session.
var peerSession = null;
// ############################################################
// # Setup Rolodex connection.
// ############################################################
// Initialize the rolodex with presence and messaging (for signaling) features.
window.rolodex = new ROLODEX({
baseURL: 'http://webrtc.hookflash.me'
});
var rolodexPresence = new ROLODEX_PRESENCE({
baseURL: 'http://webrtc.hookflash.me',
rolodex: window.rolodex
});
// ############################################################
// # Respond to Rolodex Events.
// ############################################################
// If a [identity] service is logged in, render the contacts view.
window.rolodex.on('services.fetched', function(services) {
for (var _serviceId in services) {
if (services[_serviceId].loggedin) {
serviceId = _serviceId;
switchView('contacts');
// We only care about the first logged in service as we
// only support login to one service at a time.
return;
}
}
// No service is logged in.
switchView('login');
});
// Update the list of contacts in the contacts view.
function renderContactsList() {
// Get all peers that are currently online.
var onlineContacts = rolodexPresence.getOnlineContacts();
// Get all peers that have used the Rolodex before (as opposed to all contacts).
window.rolodex.getContacts('*', {
peerContact: /^peer:/
}).then(function(contacts) {
var ul = $('#contacts > UL');
// Clear the whole contact list.
ul.html('');
// Append each contact to the list.
for (var _serviceId in contacts) {
for (var _contactId in contacts[_serviceId]) {
var contact = contacts[_serviceId][_contactId];
var li = [];
// Keep track of `peerContact` ID (needed when 'Call' button is clicked).
li.push('<li contact="' + contact.peerContact + '">');
li.push('<img src="' + contact.photo + '"/>');
li.push(contact.fn || contact.nickname);
// Only include the 'Call' button if contact is online.
if (onlineContacts[contact.peerContact] === 'online') {
li.push('<button>Call</button>');
}
li.push('</li>');
$(li.join('')).appendTo(ul);
}
}
});
}
// Fires after contacts are fetched from server.
window.rolodex.on('contacts.fetched', renderContactsList);
// Contact connected to internet.
rolodexPresence.on('contact.online', renderContactsList);
// Contact lost internet connectivity.
rolodexPresence.on('contact.away', renderContactsList);
// Contact got internet connectivity back.
rolodexPresence.on('contact.back', renderContactsList);
// Contact has lost internet connectivity for more than 60 seconds.
rolodexPresence.on('contact.offline', renderContactsList);
// A signaling message arrived from a contact.
rolodexPresence.on('contact.message', function(peerContact, message) {
// A peer is requesting to start a session.
if (message.type === 'offer') {
setupPeerSession(peerContact, 'answer');
} else
// Handle signal for an existing session.
if (peerSession) {
peerSession.onSignal(message.type, message.data);
if (message.type === 'hangup') {
// Let user know that peer hung up the call.
$('#call-hungup-dialog').dialog({
dialogClass: 'call-hungup-dialog',
closeOnEscape: false,
resizable: false,
width: 600,
height: 165,
modal: true,
buttons: {
"Ok": function() {
$(this).dialog('close');
}
}
});
}
}
if (message.type === 'decline') {
// Let user know that call was declined.
$('#call-declined-dialog').dialog({
dialogClass: 'call-declined-dialog',
closeOnEscape: false,
resizable: false,
width: 600,
height: 165,
modal: true,
buttons: {
"Ok": function() {
$(this).dialog('close');
}
}
});
}
});
// Logout/lock UI as user logged in at a different location/browser page.
rolodexPresence.on("logout", function() {
if (peerSession) peerSession.end();
serviceId = null;
switchView('logout');
});
// ############################################################
// # Render Views.
// ############################################################
function closeDialogs(names) {
names.forEach(function(name) {
// Will throw if dialog has not yet been initialized.
try {
$('#call-' + name + '-dialog').dialog('close');
} catch(err) {}
});
}
// The default view.
var rendered = 'loading';
function switchView(view, contextId) {
// Ignore repeat calls
if (rendered === view) return;
// Show DIV for requested view
$('#' + rendered).addClass('hidden');
$('#' + view).removeClass('hidden');
rendered = view;
// View has changed.
// Deal with specific views.
if (view === 'contacts') {
// Declare functions called from view HTML.
window.refetch = function() {
// If contact added/removed on [identity] service this will sync changes to our client.
window.rolodex.refetchContacts(serviceId).then(function(data) {
if (data.error) {
alert(data.error.message);
}
});
}
window.logout = function() {
window.rolodex.logoutService(serviceId);
}
} else
if (view === 'call') {
closeDialogs([ 'declined', 'hungup' ]);
var peerContact = contextId;
// Obtain details for peer contact by ID.
rolodex.getContact(peerContact).then(function(contact) {
// Set name/nickname of contact in view HTML.
$('#call > H1 > SPAN').html(contact.fn || contact.nickname);
$('#call-accept-dialog > P > SPAN').html(contact.fn || contact.nickname);
$('#call-declined-dialog > P > SPAN').html(contact.fn || contact.nickname);
$('#call-cancel-dialog > P > SPAN').html(contact.fn || contact.nickname);
$('#call-hungup-dialog > P > SPAN').html(contact.fn || contact.nickname);
// Declare function called from view HTML.
window.hangup = function() {
peerSession.end();
}
});
}
}
// Handle click on 'Call' buttons to call a contact.
$('#contacts > UL').click(function(evt) {
// Ensure click was on BUTTON instead of LI.
var peerContact = $(evt.target).parent().attr('contact');
if (!peerContact) return;
// Initiate a call to contact.
setupPeerSession(peerContact, 'offer');
});
// Handle sending of text messages.
$('#send').keydown(function(key) {
if (key.keyCode !== 13) return; // 'Return' key
// Obtain the message to be sent from the input field.
var message = $(this).val();
// Send the message to the peer.
peerSession.sendMessage(message);
// Append message to our transcript and clear the input field.
var messagesNode = $('#messages');
$('<div class="sent">' + message + '</div>').appendTo(messagesNode);
messagesNode.animate({"scrollTop": messagesNode[0].scrollHeight}, 'fast');
$(this).val('');
// Ignore the `Return` key that was just pressed.
return false;
});
// ############################################################
// # Setup peer session using WebRTC.
// ############################################################
// @see http://www.html5rocks.com/en/tutorials/webrtc/basics/
function setupPeerSession(peerContact, mode) {
switchView('call', peerContact);
if (mode === 'offer') {
// Send offer signal to peer.
rolodexPresence.sendMessage(peerContact, {
type: 'offer'
});
// Give user a chance to cancel the offer.
$('#call-cancel-dialog').dialog({
dialogClass: 'call-cancel-dialog',
closeOnEscape: false,
resizable: false,
width: 600,
height: 165,
modal: true,
buttons: {
"Hangup": function() {
$(this).dialog('close');
peerSession.end();
}
}
});
} else
if (mode === 'answer') {
// Give user a chance to decline the offer.
$('#call-accept-dialog').dialog({
dialogClass: 'call-accept-dialog',
closeOnEscape: false,
resizable: false,
width: 600,
height: 165,
modal: true,
buttons: {
"Accept": function() {
$(this).dialog('close');
// Send accept signal to peer.
rolodexPresence.sendMessage(peerContact, {
type: 'accept'
});
init();
},
"Decline": function() {
$(this).dialog('close');
// Send decline signal to peer.
rolodexPresence.sendMessage(peerContact, {
type: 'decline'
});
peerSession.end();
}
}
});
}
// The webRTC peer connection.
var peerConnection = null;
// A WebRTC data channel for sending messages.
var peerChannel = null;
// Our local webcam & audio stream.
var localStream = null;
function fail(err) {
console.error(err, err.stack);
alert('Failure code: ' + err.code);
}
// Called with the session description obtained after creating
// an offer or answer on the peer connection.
function broadcastSessionDescription(sessionDescription) {
// Let our local peer connection know the session description we want to use.
peerConnection.setLocalDescription(sessionDescription);
// Also send the session description to the peer.
rolodexPresence.sendMessage(peerContact, {
type: 'session-description',
data: sessionDescription
});
}
// The answer can only be sent once `peerConnection.addStream` and
// `peerConnection.setRemoteDescription` has been called.
// We call this function after both of the above functions so on the
// second call we are ready to send the answer.
var sendAnswer_count = 0;
function sendAnswer() {
sendAnswer_count += 1;
if (sendAnswer_count != 2) return;
// Now that we have the session description from the offering peer
// and our local video & audio stream is attached we create
// an answer session description.
peerConnection.createAnswer(broadcastSessionDescription, fail);
}
// Called once we have a data channel object and media streams are connected.
function attachToPeerChannel() {
// We use the open and close events to determine when the connection is established.
peerChannel.onopen = function() {
// Show video & text messaging UI.
$('#call > DIV:nth-child(2) > DIV:nth-child(3)').show();
};
peerChannel.onclose = function() {
// Hide video & text messaging UI.
$('#call > DIV:nth-child(2) > DIV:nth-child(3)').hide();
};
peerChannel.onmessage = function(event) {
// Append message to our transcript.
var messagesNode = $('#messages');
// NOTE: You should sanitize `event.data` so peer cannot perform a script injection attack!
$('<div>' + event.data + '</div>').appendTo(messagesNode);
messagesNode.animate({"scrollTop": messagesNode[0].scrollHeight}, 'fast');
};
}
// Initialize a WebRTC connection.
function init() {
peerConnection = new WEBRTC_SHIM.PeerConnection(WEBRTC_SHIM.PeerConnConfig, {
optional: [ { RtpDataChannels: true } ]
});
// Send ICE candidates for NAT traversal negotiation to the other peer as
// they trickle in. This is faster than waiting for all ICE candidates as
// connection can be established as soon as one ICE candidate results in
// a successful connection.
peerConnection.onicecandidate = function(event) {
if (!event.candidate) {
// ICE candidate gathering complete which we ignore as we have been
// sending each candidate as it comes in.
return;
}
rolodexPresence.sendMessage(peerContact, {
type: 'candidate',
data: event.candidate
});
};
// When remote stream arrives, show it in the remote video element.
peerConnection.onaddstream = function (event) {
$('#remoteVideo').attr('src', WEBRTC_SHIM.URL.createObjectURL(event.stream));
};
// Setup data channel for text messaging.
if (mode === 'offer') {
try {
// NOTE: This must be called before creating an offer below in order to
// include the data channel in the connection negotiation.
peerChannel = peerConnection.createDataChannel('messaging', {
// Reliable (TCP-like) data channel is not yet supported.
reliable: false
});
} catch (err) {
fail(err);
}
} else
if (mode === 'answer') {
// When peer open data channel.
peerConnection.ondatachannel = function(event) {
peerChannel = event.channel;
attachToPeerChannel();
}
}
// Show call control UI.
$('#call > DIV:nth-child(2)').show();
// Request access to local webcam and microphone.
WEBRTC_SHIM.getUserMedia({
'audio': true,
'video': true
}, function (stream) {
localStream = stream;
// Show video stream in the local video element (audio gets attached as well).
$('#localVideo').attr('src', WEBRTC_SHIM.URL.createObjectURL(localStream));
// Attach local video & audio stream to connection to stream it to peer.
peerConnection.addStream(localStream);
// Use peer connection to obtain an offer session description.
if (mode === 'offer') {
peerConnection.createOffer(broadcastSessionDescription, fail);
attachToPeerChannel();
} else
if (mode === 'answer') {
sendAnswer();
}
}, fail);
}
// Assemble a helper object for easier integration with app.
peerSession = {
// A signal arrived from the peer.
onSignal: function(type, data) {
// Our offer was declined.
if (type === 'decline') {
if (peerSession) peerSession.end();
} else
// Our offer was accepted.
if (type === 'accept') {
closeDialogs([ 'cancel', 'hungup' ]);
init();
} else
// Peer sent ICE candidate.
if (type === 'candidate') {
peerConnection.addIceCandidate(new WEBRTC_SHIM.IceCandidate(data));
} else
// Peer sent session description.
if (type === 'session-description') {
peerConnection.setRemoteDescription(new WEBRTC_SHIM.SessionDescription(data));
if (mode === 'answer') {
sendAnswer();
}
} else
// Peer requested to end the session.
if (type === 'hangup') {
if (peerSession) peerSession.end();
}
},
// Send a text message to the peer.
sendMessage: function(message) {
peerChannel.send(message);
},
// User requested session to end.
end: function() {
peerSession = null;
// Hide call control UI.
$('#call > DIV:nth-child(2)').hide();
$('#remoteVideo').attr('src', '');
$('#localVideo').attr('src', '');
$('#messages').html('');
closeDialogs([ 'accept', 'cancel', 'hungup' ]);
switchView('contacts');
// Release access to local webcam and microphone.
if (localStream) localStream.stop();
// Close connection with peer.
if (peerConnection) peerConnection.close();
// Signal peer that we have ended the session.
rolodexPresence.sendMessage(peerContact, {
type: 'hangup'
});
}
};
}
});
</script>
</body></html>