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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. if (Object.keys(connection.emuc.members).length < 1) {
  150. focus = new ColibriFocus(connection, config.hosts.bridge);
  151. return;
  152. }
  153. });
  154. $(document).bind('entered.muc', function (event, jid, info) {
  155. console.log('entered', jid, info);
  156. console.log(focus);
  157. if (focus !== null) {
  158. // FIXME: this should prepare the video
  159. if (focus.confid === null) {
  160. console.log('make new conference with', jid);
  161. focus.makeConference(Object.keys(connection.emuc.members));
  162. } else {
  163. console.log('invite', jid, 'into conference');
  164. focus.addNewParticipant(jid);
  165. }
  166. }
  167. });
  168. $(document).bind('left.muc', function (event, jid) {
  169. console.log('left', jid);
  170. connection.jingle.terminateByJid(jid);
  171. // FIXME: this should actually hide the video already for a nicer UX
  172. if (Object.keys(connection.emuc.members).length === 0) {
  173. console.log('everyone left');
  174. if (focus !== null) {
  175. // FIXME: closing the connection is a hack to avoid some
  176. // problemswith reinit
  177. if (focus.peerconnection !== null) {
  178. focus.peerconnection.close();
  179. }
  180. focus = new ColibriFocus(connection, config.hosts.bridge);
  181. }
  182. }
  183. });
  184. function toggleVideo() {
  185. if (!(connection && connection.jingle.localStream)) return;
  186. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  187. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  188. }
  189. }
  190. function toggleAudio() {
  191. if (!(connection && connection.jingle.localStream)) return;
  192. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  193. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  194. }
  195. }
  196. function resizeLarge() {
  197. var availableHeight = window.innerHeight;
  198. var chatspaceWidth = $('#chatspace').width();
  199. var numvids = $('#remoteVideos>video:visible').length;
  200. if (numvids < 5)
  201. availableHeight -= 100; // min thumbnail height for up to 4 videos
  202. else
  203. availableHeight -= 50; // min thumbnail height for more than 5 videos
  204. availableHeight -= 79; // padding + link ontop
  205. var availableWidth = window.innerWidth - chatspaceWidth;
  206. var aspectRatio = 16.0 / 9.0;
  207. if (availableHeight < availableWidth / aspectRatio) {
  208. availableWidth = Math.floor(availableHeight * aspectRatio);
  209. }
  210. if (availableWidth < 0 || availableHeight < 0) return;
  211. $('#largeVideo').width(availableWidth);
  212. $('#largeVideo').height(availableWidth / aspectRatio);
  213. resizeThumbnails();
  214. }
  215. function resizeThumbnails() {
  216. // Calculate the available height, which is the inner window height minus 39px for the header
  217. // minus 4px for the delimiter lines on the top and bottom of the large video,
  218. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  219. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  220. var numvids = $('#remoteVideos>video:visible').length;
  221. // Remove the 1px borders arround videos.
  222. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids;
  223. var availableWidth = availableWinWidth / numvids;
  224. var aspectRatio = 16.0 / 9.0;
  225. var maxHeight = Math.min(160, availableHeight);
  226. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  227. if (availableHeight < availableWidth / aspectRatio) {
  228. availableWidth = Math.floor(availableHeight * aspectRatio);
  229. }
  230. // size videos so that while keeping AR and max height, we have a nice fit
  231. $('#remoteVideos').height(availableHeight + 36); // add the 2*18px border used for highlighting shadow.
  232. $('#remoteVideos>video:visible').width(availableWidth);
  233. $('#remoteVideos>video:visible').height(availableHeight);
  234. }
  235. $(document).ready(function () {
  236. $('#nickinput').keydown(function(event) {
  237. if (event.keyCode == 13) {
  238. event.preventDefault();
  239. var val = this.value;
  240. this.value = '';
  241. if (!nickname) {
  242. nickname = val;
  243. $('#nickname').css({visibility:"hidden"});
  244. $('#chatconversation').css({visibility:'visible'});
  245. $('#usermsg').css({visibility:'visible'});
  246. $('#usermsg').focus();
  247. return;
  248. }
  249. }
  250. });
  251. $('#usermsg').keydown(function(event) {
  252. if (event.keyCode == 13) {
  253. event.preventDefault();
  254. var message = this.value;
  255. $('#usermsg').val('').trigger('autosize.resize');
  256. this.focus();
  257. connection.emuc.sendMessage(message, nickname);
  258. }
  259. });
  260. $('#usermsg').autosize();
  261. resizeLarge();
  262. $(window).resize(function () {
  263. resizeLarge();
  264. });
  265. if (!$('#settings').is(':visible')) {
  266. console.log('init');
  267. init();
  268. } else {
  269. loginInfo.onsubmit = function (e) {
  270. if (e.preventDefault) e.preventDefault();
  271. $('#settings').hide();
  272. init();
  273. };
  274. }
  275. });
  276. $(window).bind('beforeunload', function () {
  277. if (connection && connection.connected) {
  278. // ensure signout
  279. $.ajax({
  280. type: 'POST',
  281. url: config.bosh,
  282. async: false,
  283. cache: false,
  284. contentType: 'application/xml',
  285. 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>",
  286. success: function (data) {
  287. console.log('signed out');
  288. console.log(data);
  289. },
  290. error: function (XMLHttpRequest, textStatus, errorThrown) {
  291. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  292. }
  293. });
  294. }
  295. });
  296. function updateChatConversation(nick, message)
  297. {
  298. var divClassName = '';
  299. if (nickname == nick)
  300. divClassName = "localuser";
  301. else
  302. divClassName = "remoteuser";
  303. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  304. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  305. }
  306. function buttonClick(id, classname) {
  307. $(id).toggleClass(classname); // add the class to the clicked element
  308. }
  309. function openLockDialog() {
  310. if (sharedKey)
  311. $.prompt("Are you sure you would like to remove your secret key?",
  312. {
  313. title: "Remove secrect key",
  314. persistent: false,
  315. buttons: { "Remove": true, "Cancel": false},
  316. defaultButton: 1,
  317. submit: function(e,v,m,f){
  318. if(v)
  319. {
  320. sharedKey = '';
  321. lockRoom();
  322. }
  323. }
  324. });
  325. else
  326. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  327. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  328. {
  329. persistent: false,
  330. buttons: { "Save": true , "Cancel": false},
  331. defaultButton: 1,
  332. loaded: function(event) {
  333. document.getElementById('lockKey').focus();
  334. },
  335. submit: function(e,v,m,f){
  336. if(v)
  337. {
  338. var lockKey = document.getElementById('lockKey');
  339. if (lockKey.value != null)
  340. {
  341. sharedKey = lockKey.value;
  342. lockRoom(true);
  343. }
  344. }
  345. }
  346. });
  347. }
  348. function openLinkDialog() {
  349. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  350. {
  351. title: "Share this link with everyone you want to invite",
  352. persistent: false,
  353. buttons: { "Cancel": false},
  354. loaded: function(event) {
  355. document.getElementById('inviteLinkRef').select();
  356. }
  357. });
  358. }
  359. function lockRoom(lock) {
  360. connection.emuc.lockRoom(sharedKey);
  361. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  362. }
  363. function openChat() {
  364. var chatspace = $('#chatspace');
  365. var videospace = $('#videospace');
  366. var chatspaceWidth = chatspace.width();
  367. if (chatspace.css("opacity") == 1) {
  368. chatspace.animate({opacity: 0}, "fast");
  369. chatspace.animate({width: 0}, "slow");
  370. videospace.animate({right: 0, width:"100%"}, "slow");
  371. }
  372. else {
  373. chatspace.animate({width:"20%"}, "slow");
  374. chatspace.animate({opacity: 1}, "slow");
  375. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  376. }
  377. // Request the focus in the nickname field or the chat input field.
  378. if ($('#nickinput').is(':visible'))
  379. $('#nickinput').focus();
  380. else
  381. $('#usermsg').focus();
  382. }
  383. function updateRoomUrl(newRoomUrl) {
  384. roomUrl = newRoomUrl;
  385. }