You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var RTC;
  6. var RTCPeerConnection = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var roomUrl = null;
  10. function init() {
  11. RTC = setupRTC();
  12. if (RTC === null) {
  13. window.location.href = '/webrtcrequired.html';
  14. return;
  15. } else if (RTC.browser != 'chrome') {
  16. window.location.href = '/chromeonly.html';
  17. return;
  18. }
  19. RTCPeerconnection = RTC.peerconnection;
  20. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  21. /*
  22. connection.rawInput = function (data) { console.log('RECV: ' + data); };
  23. connection.rawOutput = function (data) { console.log('SEND: ' + data); };
  24. */
  25. connection.jingle.pc_constraints = RTC.pc_constraints;
  26. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  27. connection.connect(jid, document.getElementById('password').value, function (status) {
  28. if (status == Strophe.Status.CONNECTED) {
  29. console.log('connected');
  30. getUserMediaWithConstraints(['audio', 'video'], '360');
  31. document.getElementById('connect').disabled = true;
  32. } else {
  33. console.log('status', status);
  34. }
  35. });
  36. }
  37. function doJoin() {
  38. var roomnode = null;
  39. var path = window.location.pathname;
  40. var roomjid;
  41. if (path.length > 1) {
  42. roomnode = path.substr(1).toLowerCase();
  43. } else {
  44. roomnode = Math.random().toString(36).substr(2, 20);
  45. window.history.pushState('VideoChat', 'Room: ' + roomnode, window.location.pathname + roomnode);
  46. }
  47. roomjid = roomnode + '@' + config.hosts.muc;
  48. if (config.useNicks) {
  49. var nick = window.prompt('Your nickname (optional)');
  50. if (nick) {
  51. roomjid += '/' + nick;
  52. } else {
  53. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  54. }
  55. } else {
  56. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  57. }
  58. connection.emuc.doJoin(roomjid);
  59. }
  60. $(document).bind('mediaready.jingle', function (event, stream) {
  61. connection.jingle.localStream = stream;
  62. RTC.attachMediaStream($('#localVideo'), stream);
  63. document.getElementById('localVideo').muted = true;
  64. document.getElementById('localVideo').autoplay = true;
  65. document.getElementById('localVideo').volume = 0;
  66. document.getElementById('largeVideo').volume = 0;
  67. document.getElementById('largeVideo').src = document.getElementById('localVideo').src;
  68. doJoin();
  69. });
  70. $(document).bind('mediafailure.jingle', function () {
  71. // FIXME
  72. });
  73. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  74. function waitForRemoteVideo(selector, sid) {
  75. var sess = connection.jingle.sessions[sid];
  76. videoTracks = data.stream.getVideoTracks();
  77. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  78. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  79. $(document).trigger('callactive.jingle', [selector, sid]);
  80. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  81. } else {
  82. setTimeout(function () { waitForRemoteVideo(selector, sid); }, 100);
  83. }
  84. }
  85. var sess = connection.jingle.sessions[sid];
  86. var vid = document.createElement('video');
  87. var id = 'remoteVideo_' + sid + '_' + data.stream.id;
  88. vid.id = id;
  89. vid.autoplay = true;
  90. vid.oncontextmenu = function () { return false; };
  91. var remotes = document.getElementById('remoteVideos');
  92. remotes.appendChild(vid);
  93. var sel = $('#' + id);
  94. sel.hide();
  95. RTC.attachMediaStream(sel, data.stream);
  96. waitForRemoteVideo(sel, sid);
  97. data.stream.onended = function () {
  98. console.log('stream ended', this.id);
  99. var src = $('#' + id).attr('src');
  100. $('#' + id).remove();
  101. if (src === $('#largeVideo').attr('src')) {
  102. // this is currently displayed as large
  103. // pick the last visible video in the row
  104. // if nobody else is left, this picks the local video
  105. var pick = $('#remoteVideos :visible:last').get(0);
  106. // mute if localvideo
  107. document.getElementById('largeVideo').volume = pick.volume;
  108. document.getElementById('largeVideo').src = pick.src;
  109. }
  110. resizeThumbnails();
  111. };
  112. sel.click(
  113. function () {
  114. console.log('hover in', $(this).attr('src'));
  115. var newSrc = $(this).attr('src');
  116. if ($('#largeVideo').attr('src') != newSrc) {
  117. document.getElementById('largeVideo').volume = 1;
  118. $('#largeVideo').fadeOut(300, function () {
  119. $(this).attr('src', newSrc);
  120. $(this).fadeIn(300);
  121. });
  122. }
  123. }
  124. );
  125. });
  126. $(document).bind('callincoming.jingle', function (event, sid) {
  127. var sess = connection.jingle.sessions[sid];
  128. // TODO: check affiliation and/or role
  129. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  130. sess.sendAnswer();
  131. sess.accept();
  132. });
  133. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  134. console.log('call active');
  135. if (videoelem.attr('id').indexOf('mixedmslabel') == -1) {
  136. // ignore mixedmslabela0 and v0
  137. videoelem.show();
  138. resizeThumbnails();
  139. document.getElementById('largeVideo').volume = 1;
  140. $('#largeVideo').attr('src', videoelem.attr('src'));
  141. }
  142. });
  143. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  144. // FIXME
  145. });
  146. $(document).bind('joined.muc', function (event, jid, info) {
  147. console.log('onJoinComplete', info);
  148. updateRoomUrl(window.location.href);
  149. // Once we've joined the muc show the toolbar
  150. showToolbar();
  151. if (Object.keys(connection.emuc.members).length < 1) {
  152. focus = new ColibriFocus(connection, config.hosts.bridge);
  153. return;
  154. }
  155. });
  156. $(document).bind('entered.muc', function (event, jid, info) {
  157. console.log('entered', jid, info);
  158. console.log(focus);
  159. if (focus !== null) {
  160. // FIXME: this should prepare the video
  161. if (focus.confid === null) {
  162. console.log('make new conference with', jid);
  163. focus.makeConference(Object.keys(connection.emuc.members));
  164. } else {
  165. console.log('invite', jid, 'into conference');
  166. focus.addNewParticipant(jid);
  167. }
  168. }
  169. });
  170. $(document).bind('left.muc', function (event, jid) {
  171. console.log('left', jid);
  172. connection.jingle.terminateByJid(jid);
  173. // FIXME: this should actually hide the video already for a nicer UX
  174. if (Object.keys(connection.emuc.members).length === 0) {
  175. console.log('everyone left');
  176. if (focus !== null) {
  177. // FIXME: closing the connection is a hack to avoid some
  178. // problemswith reinit
  179. if (focus.peerconnection !== null) {
  180. focus.peerconnection.close();
  181. }
  182. focus = new ColibriFocus(connection, config.hosts.bridge);
  183. }
  184. }
  185. });
  186. function toggleVideo() {
  187. if (!(connection && connection.jingle.localStream)) return;
  188. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  189. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  190. }
  191. }
  192. function toggleAudio() {
  193. if (!(connection && connection.jingle.localStream)) return;
  194. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  195. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  196. }
  197. }
  198. function resizeLarge() {
  199. var availableHeight = window.innerHeight;
  200. var chatspaceWidth = $('#chatspace').width();
  201. var numvids = $('#remoteVideos>video:visible').length;
  202. if (numvids < 5)
  203. availableHeight -= 100; // min thumbnail height for up to 4 videos
  204. else
  205. availableHeight -= 50; // min thumbnail height for more than 5 videos
  206. availableHeight -= 79; // padding + link ontop
  207. var availableWidth = window.innerWidth - chatspaceWidth;
  208. var aspectRatio = 16.0 / 9.0;
  209. if (availableHeight < availableWidth / aspectRatio) {
  210. availableWidth = Math.floor(availableHeight * aspectRatio);
  211. }
  212. if (availableWidth < 0 || availableHeight < 0) return;
  213. $('#largeVideo').width(availableWidth);
  214. $('#largeVideo').height(availableWidth / aspectRatio);
  215. resizeThumbnails();
  216. }
  217. function resizeThumbnails() {
  218. // Calculate the available height, which is the inner window height minus 39px for the header
  219. // minus 4px for the delimiter lines on the top and bottom of the large video,
  220. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  221. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  222. var numvids = $('#remoteVideos>video:visible').length;
  223. // Remove the 1px borders arround videos.
  224. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids;
  225. var availableWidth = availableWinWidth / numvids;
  226. var aspectRatio = 16.0 / 9.0;
  227. var maxHeight = Math.min(160, availableHeight);
  228. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  229. if (availableHeight < availableWidth / aspectRatio) {
  230. availableWidth = Math.floor(availableHeight * aspectRatio);
  231. }
  232. // size videos so that while keeping AR and max height, we have a nice fit
  233. $('#remoteVideos').height(availableHeight + 36); // add the 2*18px border used for highlighting shadow.
  234. $('#remoteVideos>video:visible').width(availableWidth);
  235. $('#remoteVideos>video:visible').height(availableHeight);
  236. }
  237. $(document).ready(function () {
  238. $('#nickinput').keydown(function(event) {
  239. if (event.keyCode == 13) {
  240. event.preventDefault();
  241. var val = this.value;
  242. this.value = '';
  243. if (!nickname) {
  244. nickname = val;
  245. $('#nickname').css({visibility:"hidden"});
  246. $('#chatconversation').css({visibility:'visible'});
  247. $('#usermsg').css({visibility:'visible'});
  248. $('#usermsg').focus();
  249. return;
  250. }
  251. }
  252. });
  253. $('#usermsg').keydown(function(event) {
  254. if (event.keyCode == 13) {
  255. event.preventDefault();
  256. var message = this.value;
  257. $('#usermsg').val('').trigger('autosize.resize');
  258. this.focus();
  259. connection.emuc.sendMessage(message, nickname);
  260. }
  261. });
  262. $('#usermsg').autosize();
  263. resizeLarge();
  264. $(window).resize(function () {
  265. resizeLarge();
  266. });
  267. if (!$('#settings').is(':visible')) {
  268. console.log('init');
  269. init();
  270. } else {
  271. loginInfo.onsubmit = function (e) {
  272. if (e.preventDefault) e.preventDefault();
  273. $('#settings').hide();
  274. init();
  275. };
  276. }
  277. });
  278. $(window).bind('beforeunload', function () {
  279. if (connection && connection.connected) {
  280. // ensure signout
  281. $.ajax({
  282. type: 'POST',
  283. url: config.bosh,
  284. async: false,
  285. cache: false,
  286. contentType: 'application/xml',
  287. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  288. success: function (data) {
  289. console.log('signed out');
  290. console.log(data);
  291. },
  292. error: function (XMLHttpRequest, textStatus, errorThrown) {
  293. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  294. }
  295. });
  296. }
  297. });
  298. function updateChatConversation(nick, message)
  299. {
  300. var divClassName = '';
  301. if (nickname == nick)
  302. divClassName = "localuser";
  303. else
  304. divClassName = "remoteuser";
  305. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  306. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  307. }
  308. function buttonClick(id, classname) {
  309. $(id).toggleClass(classname); // add the class to the clicked element
  310. }
  311. function openLockDialog() {
  312. if (sharedKey)
  313. $.prompt("Are you sure you would like to remove your secret key?",
  314. {
  315. title: "Remove secrect key",
  316. persistent: false,
  317. buttons: { "Remove": true, "Cancel": false},
  318. defaultButton: 1,
  319. submit: function(e,v,m,f){
  320. if(v)
  321. {
  322. sharedKey = '';
  323. lockRoom();
  324. }
  325. }
  326. });
  327. else
  328. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  329. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  330. {
  331. persistent: false,
  332. buttons: { "Save": true , "Cancel": false},
  333. defaultButton: 1,
  334. loaded: function(event) {
  335. document.getElementById('lockKey').focus();
  336. },
  337. submit: function(e,v,m,f){
  338. if(v)
  339. {
  340. var lockKey = document.getElementById('lockKey');
  341. if (lockKey.value != null)
  342. {
  343. sharedKey = lockKey.value;
  344. lockRoom(true);
  345. }
  346. }
  347. }
  348. });
  349. }
  350. function openLinkDialog() {
  351. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  352. {
  353. title: "Share this link with everyone you want to invite",
  354. persistent: false,
  355. buttons: { "Cancel": false},
  356. loaded: function(event) {
  357. document.getElementById('inviteLinkRef').select();
  358. }
  359. });
  360. }
  361. function lockRoom(lock) {
  362. connection.emuc.lockRoom(sharedKey);
  363. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  364. }
  365. function openChat() {
  366. var chatspace = $('#chatspace');
  367. var videospace = $('#videospace');
  368. var chatspaceWidth = chatspace.width();
  369. if (chatspace.css("opacity") == 1) {
  370. chatspace.animate({opacity: 0}, "fast");
  371. chatspace.animate({width: 0}, "slow");
  372. videospace.animate({right: 0, width:"100%"}, "slow");
  373. }
  374. else {
  375. chatspace.animate({width:"20%"}, "slow");
  376. chatspace.animate({opacity: 1}, "slow");
  377. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  378. }
  379. // Request the focus in the nickname field or the chat input field.
  380. if ($('#nickinput').is(':visible'))
  381. $('#nickinput').focus();
  382. else
  383. $('#usermsg').focus();
  384. }
  385. function showToolbar() {
  386. $('#toolbar').css({visibility:"visible"});
  387. }
  388. function updateRoomUrl(newRoomUrl) {
  389. roomUrl = newRoomUrl;
  390. }