選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

app.js 16KB

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