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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. var focus = null;
  6. var activecall = null;
  7. var RTC = null;
  8. var nickname = null;
  9. var sharedKey = '';
  10. var recordingToken ='';
  11. var roomUrl = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var mediaStreams = [];
  15. /**
  16. * The stats collector that process stats data and triggers updates to app.js.
  17. * @type {StatsCollector}
  18. */
  19. var statsCollector = null;
  20. /**
  21. * The stats collector for the local stream.
  22. * @type {LocalStatsCollector}
  23. */
  24. var localStatsCollector = null;
  25. /**
  26. * Indicates whether ssrc is camera video or desktop stream.
  27. * FIXME: remove those maps
  28. */
  29. var ssrc2videoType = {};
  30. var videoSrcToSsrc = {};
  31. /**
  32. * Currently focused video "src"(displayed in large video).
  33. * @type {String}
  34. */
  35. var focusedVideoSrc = null;
  36. var mutedAudios = {};
  37. var localVideoSrc = null;
  38. var flipXLocalVideo = true;
  39. var isFullScreen = false;
  40. var toolbarTimeout = null;
  41. var currentVideoWidth = null;
  42. var currentVideoHeight = null;
  43. /**
  44. * Method used to calculate large video size.
  45. * @type {function ()}
  46. */
  47. var getVideoSize;
  48. /**
  49. * Method used to get large video position.
  50. * @type {function ()}
  51. */
  52. var getVideoPosition;
  53. /* window.onbeforeunload = closePageWarning; */
  54. var sessionTerminated = false;
  55. function init() {
  56. RTC = setupRTC();
  57. if (RTC === null) {
  58. window.location.href = 'webrtcrequired.html';
  59. return;
  60. } else if (RTC.browser !== 'chrome') {
  61. window.location.href = 'chromeonly.html';
  62. return;
  63. }
  64. obtainAudioAndVideoPermissions(function (stream) {
  65. var audioStream = new webkitMediaStream(stream);
  66. var videoStream = new webkitMediaStream(stream);
  67. var videoTracks = stream.getVideoTracks();
  68. var audioTracks = stream.getAudioTracks();
  69. for (var i = 0; i < videoTracks.length; i++) {
  70. audioStream.removeTrack(videoTracks[i]);
  71. }
  72. VideoLayout.changeLocalAudio(audioStream);
  73. startLocalRtpStatsCollector(audioStream);
  74. for (i = 0; i < audioTracks.length; i++) {
  75. videoStream.removeTrack(audioTracks[i]);
  76. }
  77. VideoLayout.changeLocalVideo(videoStream, true);
  78. maybeDoJoin();
  79. });
  80. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  81. connect(jid);
  82. }
  83. function connect(jid, password) {
  84. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  85. if (nickname) {
  86. connection.emuc.addDisplayNameToPresence(nickname);
  87. }
  88. if (connection.disco) {
  89. // for chrome, add multistream cap
  90. }
  91. connection.jingle.pc_constraints = RTC.pc_constraints;
  92. if (config.useIPv6) {
  93. // https://code.google.com/p/webrtc/issues/detail?id=2828
  94. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  95. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  96. }
  97. if(!password)
  98. password = document.getElementById('password').value;
  99. var anonymousConnectionFailed = false;
  100. connection.connect(jid, password, function (status, msg) {
  101. if (status === Strophe.Status.CONNECTED) {
  102. console.log('connected');
  103. if (config.useStunTurn) {
  104. connection.jingle.getStunAndTurnCredentials();
  105. }
  106. document.getElementById('connect').disabled = true;
  107. if(password)
  108. authenticatedUser = true;
  109. maybeDoJoin();
  110. } else if (status === Strophe.Status.CONNFAIL) {
  111. if(msg === 'x-strophe-bad-non-anon-jid') {
  112. anonymousConnectionFailed = true;
  113. }
  114. console.log('status', status);
  115. } else if (status === Strophe.Status.DISCONNECTED) {
  116. if(anonymousConnectionFailed) {
  117. // prompt user for username and password
  118. $(document).trigger('passwordrequired.main');
  119. }
  120. } else if (status === Strophe.Status.AUTHFAIL) {
  121. // wrong password or username, prompt user
  122. $(document).trigger('passwordrequired.main');
  123. } else {
  124. console.log('status', status);
  125. }
  126. });
  127. }
  128. /**
  129. * We ask for audio and video combined stream in order to get permissions and
  130. * not to ask twice.
  131. */
  132. function obtainAudioAndVideoPermissions(callback) {
  133. // Get AV
  134. getUserMediaWithConstraints(
  135. ['audio', 'video'],
  136. function (avStream) {
  137. callback(avStream);
  138. },
  139. function (error) {
  140. console.error('failed to obtain audio/video stream - stop', error);
  141. },
  142. config.resolution || '360');
  143. }
  144. function maybeDoJoin() {
  145. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  146. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  147. doJoin();
  148. }
  149. }
  150. function doJoin() {
  151. var roomnode = null;
  152. var path = window.location.pathname;
  153. var roomjid;
  154. // determinde the room node from the url
  155. // TODO: just the roomnode or the whole bare jid?
  156. if (config.getroomnode && typeof config.getroomnode === 'function') {
  157. // custom function might be responsible for doing the pushstate
  158. roomnode = config.getroomnode(path);
  159. } else {
  160. /* fall back to default strategy
  161. * this is making assumptions about how the URL->room mapping happens.
  162. * It currently assumes deployment at root, with a rewrite like the
  163. * following one (for nginx):
  164. location ~ ^/([a-zA-Z0-9]+)$ {
  165. rewrite ^/(.*)$ / break;
  166. }
  167. */
  168. if (path.length > 1) {
  169. roomnode = path.substr(1).toLowerCase();
  170. } else {
  171. roomnode = RoomNameGenerator.generateRoomWithoutSeparator(3);
  172. window.history.pushState('VideoChat',
  173. 'Room: ' + roomnode, window.location.pathname + roomnode);
  174. }
  175. }
  176. roomName = roomnode + '@' + config.hosts.muc;
  177. roomjid = roomName;
  178. if (config.useNicks) {
  179. var nick = window.prompt('Your nickname (optional)');
  180. if (nick) {
  181. roomjid += '/' + nick;
  182. } else {
  183. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  184. }
  185. } else {
  186. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  187. if(!authenticatedUser)
  188. tmpJid = tmpJid.substr(0, 8);
  189. roomjid += '/' + tmpJid;
  190. }
  191. connection.emuc.doJoin(roomjid);
  192. }
  193. function waitForRemoteVideo(selector, ssrc, stream) {
  194. if (selector.removed || !selector.parent().is(":visible")) {
  195. console.warn("Media removed before had started", selector);
  196. return;
  197. }
  198. if (stream.id === 'mixedmslabel') return;
  199. if (selector[0].currentTime > 0) {
  200. RTC.attachMediaStream(selector, stream); // FIXME: why do i have to do this for FF?
  201. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  202. // in order to get rid of too many maps
  203. if (ssrc && selector.attr('src')) {
  204. videoSrcToSsrc[selector.attr('src')] = ssrc;
  205. } else {
  206. console.warn("No ssrc given for video", selector);
  207. }
  208. $(document).trigger('videoactive.jingle', [selector]);
  209. } else {
  210. setTimeout(function () {
  211. waitForRemoteVideo(selector, ssrc, stream);
  212. }, 250);
  213. }
  214. }
  215. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  216. var sess = connection.jingle.sessions[sid];
  217. var thessrc;
  218. // look up an associated JID for a stream id
  219. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  220. var ssrclines
  221. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  222. ssrclines = ssrclines.filter(function (line) {
  223. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  224. });
  225. if (ssrclines.length) {
  226. thessrc = ssrclines[0].substring(7).split(' ')[0];
  227. // ok to overwrite the one from focus? might save work in colibri.js
  228. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  229. if (ssrc2jid[thessrc]) {
  230. data.peerjid = ssrc2jid[thessrc];
  231. }
  232. }
  233. }
  234. mediaStreams.push(new MediaStream(data, sid, thessrc));
  235. var container;
  236. var remotes = document.getElementById('remoteVideos');
  237. if (data.peerjid) {
  238. VideoLayout.ensurePeerContainerExists(data.peerjid);
  239. container = document.getElementById(
  240. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  241. } else {
  242. if (data.stream.id !== 'mixedmslabel') {
  243. console.error( 'can not associate stream',
  244. data.stream.id,
  245. 'with a participant');
  246. // We don't want to add it here since it will cause troubles
  247. return;
  248. }
  249. // FIXME: for the mixed ms we dont need a video -- currently
  250. container = document.createElement('span');
  251. container.id = 'mixedstream';
  252. container.className = 'videocontainer';
  253. remotes.appendChild(container);
  254. Util.playSoundNotification('userJoined');
  255. }
  256. var isVideo = data.stream.getVideoTracks().length > 0;
  257. if (container) {
  258. VideoLayout.addRemoteStreamElement( container,
  259. sid,
  260. data.stream,
  261. data.peerjid,
  262. thessrc);
  263. }
  264. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  265. if (isVideo &&
  266. data.peerjid && sess.peerjid === data.peerjid &&
  267. data.stream.getVideoTracks().length === 0 &&
  268. connection.jingle.localVideo.getVideoTracks().length > 0) {
  269. //
  270. window.setTimeout(function () {
  271. sendKeyframe(sess.peerconnection);
  272. }, 3000);
  273. }
  274. });
  275. /**
  276. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  277. * @param videoSrc the video "src" identifier.
  278. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  279. * belongs.
  280. */
  281. function getJidFromVideoSrc(videoSrc)
  282. {
  283. if (videoSrc === localVideoSrc)
  284. return connection.emuc.myroomjid;
  285. var ssrc = videoSrcToSsrc[videoSrc];
  286. if (!ssrc)
  287. {
  288. return null;
  289. }
  290. return ssrc2jid[ssrc];
  291. }
  292. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  293. function sendKeyframe(pc) {
  294. console.log('sendkeyframe', pc.iceConnectionState);
  295. if (pc.iceConnectionState !== 'connected') return; // safe...
  296. pc.setRemoteDescription(
  297. pc.remoteDescription,
  298. function () {
  299. pc.createAnswer(
  300. function (modifiedAnswer) {
  301. pc.setLocalDescription(
  302. modifiedAnswer,
  303. function () {
  304. // noop
  305. },
  306. function (error) {
  307. console.log('triggerKeyframe setLocalDescription failed', error);
  308. }
  309. );
  310. },
  311. function (error) {
  312. console.log('triggerKeyframe createAnswer failed', error);
  313. }
  314. );
  315. },
  316. function (error) {
  317. console.log('triggerKeyframe setRemoteDescription failed', error);
  318. }
  319. );
  320. }
  321. // Really mute video, i.e. dont even send black frames
  322. function muteVideo(pc, unmute) {
  323. // FIXME: this probably needs another of those lovely state safeguards...
  324. // which checks for iceconn == connected and sigstate == stable
  325. pc.setRemoteDescription(pc.remoteDescription,
  326. function () {
  327. pc.createAnswer(
  328. function (answer) {
  329. var sdp = new SDP(answer.sdp);
  330. if (sdp.media.length > 1) {
  331. if (unmute)
  332. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  333. else
  334. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  335. sdp.raw = sdp.session + sdp.media.join('');
  336. answer.sdp = sdp.raw;
  337. }
  338. pc.setLocalDescription(answer,
  339. function () {
  340. console.log('mute SLD ok');
  341. },
  342. function (error) {
  343. console.log('mute SLD error');
  344. }
  345. );
  346. },
  347. function (error) {
  348. console.log(error);
  349. }
  350. );
  351. },
  352. function (error) {
  353. console.log('muteVideo SRD error');
  354. }
  355. );
  356. }
  357. /**
  358. * Callback for audio levels changed.
  359. * @param jid JID of the user
  360. * @param audioLevel the audio level value
  361. */
  362. function audioLevelUpdated(jid, audioLevel)
  363. {
  364. var resourceJid;
  365. if(jid === LocalStatsCollector.LOCAL_JID)
  366. {
  367. resourceJid = AudioLevels.LOCAL_LEVEL;
  368. if(isAudioMuted())
  369. return;
  370. }
  371. else
  372. {
  373. resourceJid = Strophe.getResourceFromJid(jid);
  374. }
  375. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  376. }
  377. /**
  378. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  379. */
  380. function startRtpStatsCollector()
  381. {
  382. stopRTPStatsCollector();
  383. if (config.enableRtpStats)
  384. {
  385. statsCollector = new StatsCollector(
  386. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  387. statsCollector.start();
  388. }
  389. }
  390. /**
  391. * Stops the {@link StatsCollector}.
  392. */
  393. function stopRTPStatsCollector()
  394. {
  395. if (statsCollector)
  396. {
  397. statsCollector.stop();
  398. statsCollector = null;
  399. }
  400. }
  401. /**
  402. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  403. * @param stream the stream that will be used for collecting statistics.
  404. */
  405. function startLocalRtpStatsCollector(stream)
  406. {
  407. if(config.enableRtpStats)
  408. {
  409. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  410. localStatsCollector.start();
  411. }
  412. }
  413. /**
  414. * Stops the {@link LocalStatsCollector}.
  415. */
  416. function stopLocalRtpStatsCollector()
  417. {
  418. if(localStatsCollector)
  419. {
  420. localStatsCollector.stop();
  421. localStatsCollector = null;
  422. }
  423. }
  424. $(document).bind('callincoming.jingle', function (event, sid) {
  425. var sess = connection.jingle.sessions[sid];
  426. // TODO: do we check activecall == null?
  427. activecall = sess;
  428. startRtpStatsCollector();
  429. // Bind data channel listener in case we're a regular participant
  430. if (config.openSctp)
  431. {
  432. bindDataChannelListener(sess.peerconnection);
  433. }
  434. // TODO: check affiliation and/or role
  435. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  436. sess.usedrip = true; // not-so-naive trickle ice
  437. sess.sendAnswer();
  438. sess.accept();
  439. });
  440. $(document).bind('conferenceCreated.jingle', function (event, focus)
  441. {
  442. startRtpStatsCollector();
  443. });
  444. $(document).bind('conferenceCreated.jingle', function (event, focus)
  445. {
  446. // Bind data channel listener in case we're the focus
  447. if (config.openSctp)
  448. {
  449. bindDataChannelListener(focus.peerconnection);
  450. }
  451. });
  452. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  453. // Leave the room if my call has been remotely terminated.
  454. if (connection.emuc.joined && focus == null && reason === 'kick') {
  455. sessionTerminated = true;
  456. connection.emuc.doLeave();
  457. openMessageDialog( "Session Terminated",
  458. "Ouch! You have been kicked out of the meet!");
  459. }
  460. });
  461. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  462. // put our ssrcs into presence so other clients can identify our stream
  463. var sess = connection.jingle.sessions[sid];
  464. var newssrcs = {};
  465. var directions = {};
  466. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  467. localSDP.media.forEach(function (media) {
  468. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  469. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  470. // assumes a single local ssrc
  471. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  472. newssrcs[type] = ssrc;
  473. directions[type] = (
  474. SDPUtil.find_line(media, 'a=sendrecv') ||
  475. SDPUtil.find_line(media, 'a=recvonly') ||
  476. SDPUtil.find_line(media, 'a=sendonly') ||
  477. SDPUtil.find_line(media, 'a=inactive') ||
  478. 'a=sendrecv').substr(2);
  479. }
  480. });
  481. console.log('new ssrcs', newssrcs);
  482. // Have to clear presence map to get rid of removed streams
  483. connection.emuc.clearPresenceMedia();
  484. var i = 0;
  485. Object.keys(newssrcs).forEach(function (mtype) {
  486. i++;
  487. var type = mtype;
  488. // Change video type to screen
  489. if (mtype === 'video' && isUsingScreenStream) {
  490. type = 'screen';
  491. }
  492. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  493. });
  494. if (i > 0) {
  495. connection.emuc.sendPresence();
  496. }
  497. });
  498. $(document).bind('joined.muc', function (event, jid, info) {
  499. updateRoomUrl(window.location.href);
  500. document.getElementById('localNick').appendChild(
  501. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  502. );
  503. if (Object.keys(connection.emuc.members).length < 1) {
  504. focus = new ColibriFocus(connection, config.hosts.bridge);
  505. if (nickname !== null) {
  506. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  507. nickname);
  508. }
  509. Toolbar.showSipCallButton(true);
  510. Toolbar.showRecordingButton(false);
  511. }
  512. if (!focus)
  513. {
  514. Toolbar.showSipCallButton(false);
  515. }
  516. if (focus && config.etherpad_base) {
  517. Etherpad.init();
  518. }
  519. VideoLayout.showFocusIndicator();
  520. // Add myself to the contact list.
  521. ContactList.addContact(jid);
  522. // Once we've joined the muc show the toolbar
  523. Toolbar.showToolbar();
  524. if (info.displayName)
  525. $(document).trigger('displaynamechanged',
  526. ['localVideoContainer', info.displayName + ' (me)']);
  527. });
  528. $(document).bind('entered.muc', function (event, jid, info, pres) {
  529. console.log('entered', jid, info);
  530. console.log('is focus?' + focus ? 'true' : 'false');
  531. // Add Peer's container
  532. VideoLayout.ensurePeerContainerExists(jid);
  533. if (focus !== null) {
  534. // FIXME: this should prepare the video
  535. if (focus.confid === null) {
  536. console.log('make new conference with', jid);
  537. focus.makeConference(Object.keys(connection.emuc.members));
  538. Toolbar.showRecordingButton(true);
  539. } else {
  540. console.log('invite', jid, 'into conference');
  541. focus.addNewParticipant(jid);
  542. }
  543. }
  544. else if (sharedKey) {
  545. Toolbar.updateLockButton();
  546. }
  547. });
  548. $(document).bind('left.muc', function (event, jid) {
  549. console.log('left.muc', jid);
  550. // Need to call this with a slight delay, otherwise the element couldn't be
  551. // found for some reason.
  552. window.setTimeout(function () {
  553. var container = document.getElementById(
  554. 'participant_' + Strophe.getResourceFromJid(jid));
  555. if (container) {
  556. // hide here, wait for video to close before removing
  557. $(container).hide();
  558. VideoLayout.resizeThumbnails();
  559. }
  560. }, 10);
  561. // Unlock large video
  562. if (focusedVideoSrc)
  563. {
  564. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  565. {
  566. console.info("Focused video owner has left the conference");
  567. focusedVideoSrc = null;
  568. }
  569. }
  570. connection.jingle.terminateByJid(jid);
  571. if (focus == null
  572. // I shouldn't be the one that left to enter here.
  573. && jid !== connection.emuc.myroomjid
  574. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  575. // If our session has been terminated for some reason
  576. // (kicked, hangup), don't try to become the focus
  577. && !sessionTerminated) {
  578. console.log('welcome to our new focus... myself');
  579. focus = new ColibriFocus(connection, config.hosts.bridge);
  580. if (nickname !== null) {
  581. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  582. nickname);
  583. }
  584. Toolbar.showSipCallButton(true);
  585. if (Object.keys(connection.emuc.members).length > 0) {
  586. focus.makeConference(Object.keys(connection.emuc.members));
  587. Toolbar.showRecordingButton(true);
  588. }
  589. $(document).trigger('focusechanged.muc', [focus]);
  590. }
  591. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  592. console.log('everyone left');
  593. // FIXME: closing the connection is a hack to avoid some
  594. // problems with reinit
  595. disposeConference();
  596. focus = new ColibriFocus(connection, config.hosts.bridge);
  597. if (nickname !== null) {
  598. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  599. nickname);
  600. }
  601. Toolbar.showSipCallButton(true);
  602. Toolbar.showRecordingButton(false);
  603. }
  604. if (connection.emuc.getPrezi(jid)) {
  605. $(document).trigger('presentationremoved.muc',
  606. [jid, connection.emuc.getPrezi(jid)]);
  607. }
  608. });
  609. $(document).bind('presence.muc', function (event, jid, info, pres) {
  610. // Remove old ssrcs coming from the jid
  611. Object.keys(ssrc2jid).forEach(function (ssrc) {
  612. if (ssrc2jid[ssrc] == jid) {
  613. delete ssrc2jid[ssrc];
  614. }
  615. if (ssrc2videoType[ssrc] == jid) {
  616. delete ssrc2videoType[ssrc];
  617. }
  618. });
  619. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  620. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  621. var ssrcV = ssrc.getAttribute('ssrc');
  622. ssrc2jid[ssrcV] = jid;
  623. var type = ssrc.getAttribute('type');
  624. ssrc2videoType[ssrcV] = type;
  625. // might need to update the direction if participant just went from sendrecv to recvonly
  626. if (type === 'video' || type === 'screen') {
  627. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  628. switch (ssrc.getAttribute('direction')) {
  629. case 'sendrecv':
  630. el.show();
  631. break;
  632. case 'recvonly':
  633. el.hide();
  634. // FIXME: Check if we have to change large video
  635. //VideoLayout.updateLargeVideo(el);
  636. break;
  637. }
  638. }
  639. });
  640. if (info.displayName && info.displayName.length > 0)
  641. $(document).trigger('displaynamechanged',
  642. [jid, info.displayName]);
  643. if (focus !== null && info.displayName !== null) {
  644. focus.setEndpointDisplayName(jid, info.displayName);
  645. }
  646. });
  647. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  648. VideoLayout.setPresenceStatus(
  649. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  650. });
  651. $(document).bind('passwordrequired.muc', function (event, jid) {
  652. console.log('on password required', jid);
  653. $.prompt('<h2>Password required</h2>' +
  654. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  655. persistent: true,
  656. buttons: { "Ok": true, "Cancel": false},
  657. defaultButton: 1,
  658. loaded: function (event) {
  659. document.getElementById('lockKey').focus();
  660. },
  661. submit: function (e, v, m, f) {
  662. if (v) {
  663. var lockKey = document.getElementById('lockKey');
  664. if (lockKey.value !== null) {
  665. setSharedKey(lockKey.value);
  666. connection.emuc.doJoin(jid, lockKey.value);
  667. }
  668. }
  669. }
  670. });
  671. });
  672. $(document).bind('passwordrequired.main', function (event) {
  673. console.log('password is required');
  674. $.prompt('<h2>Password required</h2>' +
  675. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  676. '<input id="passwordrequired.password" type="password" placeholder="user password">', {
  677. persistent: true,
  678. buttons: { "Ok": true, "Cancel": false},
  679. defaultButton: 1,
  680. loaded: function (event) {
  681. document.getElementById('passwordrequired.username').focus();
  682. },
  683. submit: function (e, v, m, f) {
  684. if (v) {
  685. var username = document.getElementById('passwordrequired.username');
  686. var password = document.getElementById('passwordrequired.password');
  687. if (username.value !== null && password.value != null) {
  688. connect(username.value, password.value);
  689. }
  690. }
  691. }
  692. });
  693. });
  694. /**
  695. * Checks if video identified by given src is desktop stream.
  696. * @param videoSrc eg.
  697. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  698. * @returns {boolean}
  699. */
  700. function isVideoSrcDesktop(videoSrc) {
  701. // FIXME: fix this mapping mess...
  702. // figure out if large video is desktop stream or just a camera
  703. var isDesktop = false;
  704. if (localVideoSrc === videoSrc) {
  705. // local video
  706. isDesktop = isUsingScreenStream;
  707. } else {
  708. // Do we have associations...
  709. var videoSsrc = videoSrcToSsrc[videoSrc];
  710. if (videoSsrc) {
  711. var videoType = ssrc2videoType[videoSsrc];
  712. if (videoType) {
  713. // Finally there...
  714. isDesktop = videoType === 'screen';
  715. } else {
  716. console.error("No video type for ssrc: " + videoSsrc);
  717. }
  718. } else {
  719. console.error("No ssrc for src: " + videoSrc);
  720. }
  721. }
  722. return isDesktop;
  723. }
  724. function getConferenceHandler() {
  725. return focus ? focus : activecall;
  726. }
  727. function toggleVideo() {
  728. if (!(connection && connection.jingle.localVideo))
  729. return;
  730. var sess = getConferenceHandler();
  731. if (sess) {
  732. sess.toggleVideoMute(
  733. function (isMuted) {
  734. if (isMuted) {
  735. $('#video').removeClass("icon-camera");
  736. $('#video').addClass("icon-camera icon-camera-disabled");
  737. } else {
  738. $('#video').removeClass("icon-camera icon-camera-disabled");
  739. $('#video').addClass("icon-camera");
  740. }
  741. }
  742. );
  743. }
  744. sess = focus || activecall;
  745. if (!sess) {
  746. return;
  747. }
  748. sess.pendingop = ismuted ? 'unmute' : 'mute';
  749. // connection.emuc.addVideoInfoToPresence(!ismuted);
  750. // connection.emuc.sendPresence();
  751. sess.modifySources();
  752. }
  753. /**
  754. * Mutes / unmutes audio for the local participant.
  755. */
  756. function toggleAudio() {
  757. if (!(connection && connection.jingle.localAudio)) {
  758. preMuted = true;
  759. // We still click the button.
  760. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  761. return;
  762. }
  763. var localAudio = connection.jingle.localAudio;
  764. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  765. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  766. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  767. // isMuted is the opposite of audioEnabled
  768. connection.emuc.addAudioInfoToPresence(audioEnabled);
  769. connection.emuc.sendPresence();
  770. }
  771. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  772. }
  773. /**
  774. * Checks whether the audio is muted or not.
  775. * @returns {boolean} true if audio is muted and false if not.
  776. */
  777. function isAudioMuted()
  778. {
  779. var localAudio = connection.jingle.localAudio;
  780. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  781. if(localAudio.getAudioTracks()[idx].enabled === true)
  782. return false;
  783. }
  784. return true;
  785. }
  786. // Starts or stops the recording for the conference.
  787. function toggleRecording() {
  788. if (focus === null || focus.confid === null) {
  789. console.log('non-focus, or conference not yet organized: not enabling recording');
  790. return;
  791. }
  792. if (!recordingToken)
  793. {
  794. $.prompt('<h2>Enter recording token</h2>' +
  795. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  796. {
  797. persistent: false,
  798. buttons: { "Save": true, "Cancel": false},
  799. defaultButton: 1,
  800. loaded: function (event) {
  801. document.getElementById('recordingToken').focus();
  802. },
  803. submit: function (e, v, m, f) {
  804. if (v) {
  805. var token = document.getElementById('recordingToken');
  806. if (token.value) {
  807. setRecordingToken(Util.escapeHtml(token.value));
  808. toggleRecording();
  809. }
  810. }
  811. }
  812. }
  813. );
  814. return;
  815. }
  816. var oldState = focus.recordingEnabled;
  817. Toolbar.toggleRecordingButtonState();
  818. focus.setRecording(!oldState,
  819. recordingToken,
  820. function (state) {
  821. console.log("New recording state: ", state);
  822. if (state == oldState) //failed to change, reset the token because it might have been wrong
  823. {
  824. Toolbar.toggleRecordingButtonState();
  825. setRecordingToken(null);
  826. }
  827. }
  828. );
  829. }
  830. /**
  831. * Returns an array of the video horizontal and vertical indents,
  832. * so that if fits its parent.
  833. *
  834. * @return an array with 2 elements, the horizontal indent and the vertical
  835. * indent
  836. */
  837. function getCameraVideoPosition(videoWidth,
  838. videoHeight,
  839. videoSpaceWidth,
  840. videoSpaceHeight) {
  841. // Parent height isn't completely calculated when we position the video in
  842. // full screen mode and this is why we use the screen height in this case.
  843. // Need to think it further at some point and implement it properly.
  844. var isFullScreen = document.fullScreen ||
  845. document.mozFullScreen ||
  846. document.webkitIsFullScreen;
  847. if (isFullScreen)
  848. videoSpaceHeight = window.innerHeight;
  849. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  850. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  851. return [horizontalIndent, verticalIndent];
  852. }
  853. /**
  854. * Returns an array of the video horizontal and vertical indents.
  855. * Centers horizontally and top aligns vertically.
  856. *
  857. * @return an array with 2 elements, the horizontal indent and the vertical
  858. * indent
  859. */
  860. function getDesktopVideoPosition(videoWidth,
  861. videoHeight,
  862. videoSpaceWidth,
  863. videoSpaceHeight) {
  864. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  865. var verticalIndent = 0;// Top aligned
  866. return [horizontalIndent, verticalIndent];
  867. }
  868. /**
  869. * Returns an array of the video dimensions, so that it covers the screen.
  870. * It leaves no empty areas, but some parts of the video might not be visible.
  871. *
  872. * @return an array with 2 elements, the video width and the video height
  873. */
  874. function getCameraVideoSize(videoWidth,
  875. videoHeight,
  876. videoSpaceWidth,
  877. videoSpaceHeight) {
  878. if (!videoWidth)
  879. videoWidth = currentVideoWidth;
  880. if (!videoHeight)
  881. videoHeight = currentVideoHeight;
  882. var aspectRatio = videoWidth / videoHeight;
  883. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  884. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  885. if (availableWidth / aspectRatio < videoSpaceHeight) {
  886. availableHeight = videoSpaceHeight;
  887. availableWidth = availableHeight * aspectRatio;
  888. }
  889. if (availableHeight * aspectRatio < videoSpaceWidth) {
  890. availableWidth = videoSpaceWidth;
  891. availableHeight = availableWidth / aspectRatio;
  892. }
  893. return [availableWidth, availableHeight];
  894. }
  895. $(document).ready(function () {
  896. if(config.enableWelcomePage && window.location.pathname == "/" &&
  897. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  898. {
  899. $("#videoconference_page").hide();
  900. $("#domain_name").text(window.location.host + "/");
  901. $("span[name='appName']").text(brand.appName);
  902. $("#enter_room_button").click(function()
  903. {
  904. var val = $("#enter_room_field").val();
  905. if(!val)
  906. val = $("#enter_room_field").attr("room_name");
  907. window.location.pathname = "/" + val;
  908. });
  909. $("#enter_room_field").keydown(function (event) {
  910. if (event.keyCode === 13) {
  911. var val = Util.escapeHtml(this.value);
  912. window.location.pathname = "/" + val;
  913. }
  914. });
  915. function animate(word) {
  916. var currentVal = $("#enter_room_field").attr("placeholder");
  917. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  918. setTimeout(function() {
  919. animate(word.substring(1, word.length))
  920. }, 150);
  921. }
  922. function update_roomname()
  923. {
  924. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  925. $("#enter_room_field").attr("room_name", word);
  926. $("#enter_room_field").attr("placeholder", "");
  927. animate(word);
  928. setTimeout(update_roomname, 10000);
  929. }
  930. update_roomname();
  931. $("#disable_welcome").click(function () {
  932. window.localStorage.welcomePageDisabled = $("#disable_welcome").is(":checked");
  933. });
  934. return;
  935. }
  936. $("#welcome_page").hide();
  937. Chat.init();
  938. $('body').popover({ selector: '[data-toggle=popover]',
  939. trigger: 'click hover'});
  940. // Set the defaults for prompt dialogs.
  941. jQuery.prompt.setDefaults({persistent: false});
  942. // Set default desktop sharing method
  943. setDesktopSharing(config.desktopSharing);
  944. // Initialize Chrome extension inline installs
  945. if (config.chromeExtensionId) {
  946. initInlineInstalls();
  947. }
  948. // By default we use camera
  949. getVideoSize = getCameraVideoSize;
  950. getVideoPosition = getCameraVideoPosition;
  951. VideoLayout.resizeLargeVideoContainer();
  952. $(window).resize(function () {
  953. VideoLayout.resizeLargeVideoContainer();
  954. VideoLayout.positionLarge();
  955. });
  956. // Listen for large video size updates
  957. document.getElementById('largeVideo')
  958. .addEventListener('loadedmetadata', function (e) {
  959. currentVideoWidth = this.videoWidth;
  960. currentVideoHeight = this.videoHeight;
  961. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  962. });
  963. if (!$('#settings').is(':visible')) {
  964. console.log('init');
  965. init();
  966. } else {
  967. loginInfo.onsubmit = function (e) {
  968. if (e.preventDefault) e.preventDefault();
  969. $('#settings').hide();
  970. init();
  971. };
  972. }
  973. });
  974. $(window).bind('beforeunload', function () {
  975. if (connection && connection.connected) {
  976. // ensure signout
  977. $.ajax({
  978. type: 'POST',
  979. url: config.bosh,
  980. async: false,
  981. cache: false,
  982. contentType: 'application/xml',
  983. 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>",
  984. success: function (data) {
  985. console.log('signed out');
  986. console.log(data);
  987. },
  988. error: function (XMLHttpRequest, textStatus, errorThrown) {
  989. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  990. }
  991. });
  992. }
  993. disposeConference(true);
  994. });
  995. function disposeConference(onUnload) {
  996. var handler = getConferenceHandler();
  997. if (handler && handler.peerconnection) {
  998. // FIXME: probably removing streams is not required and close() should be enough
  999. if (connection.jingle.localAudio) {
  1000. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1001. }
  1002. if (connection.jingle.localVideo) {
  1003. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1004. }
  1005. handler.peerconnection.close();
  1006. }
  1007. stopRTPStatsCollector();
  1008. if(onUnload) {
  1009. stopLocalRtpStatsCollector();
  1010. }
  1011. focus = null;
  1012. activecall = null;
  1013. }
  1014. function dump(elem, filename) {
  1015. elem = elem.parentNode;
  1016. elem.download = filename || 'meetlog.json';
  1017. elem.href = 'data:application/json;charset=utf-8,\n';
  1018. var data = {};
  1019. if (connection.jingle) {
  1020. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1021. var session = connection.jingle.sessions[sid];
  1022. if (session.peerconnection && session.peerconnection.updateLog) {
  1023. // FIXME: should probably be a .dump call
  1024. data["jingle_" + session.sid] = {
  1025. updateLog: session.peerconnection.updateLog,
  1026. stats: session.peerconnection.stats,
  1027. url: window.location.href
  1028. };
  1029. }
  1030. });
  1031. }
  1032. metadata = {};
  1033. metadata.time = new Date();
  1034. metadata.url = window.location.href;
  1035. metadata.ua = navigator.userAgent;
  1036. if (connection.logger) {
  1037. metadata.xmpp = connection.logger.log;
  1038. }
  1039. data.metadata = metadata;
  1040. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1041. return false;
  1042. }
  1043. /**
  1044. * Changes the style class of the element given by id.
  1045. */
  1046. function buttonClick(id, classname) {
  1047. $(id).toggleClass(classname); // add the class to the clicked element
  1048. }
  1049. /**
  1050. * Shows a message to the user.
  1051. *
  1052. * @param titleString the title of the message
  1053. * @param messageString the text of the message
  1054. */
  1055. function openMessageDialog(titleString, messageString) {
  1056. $.prompt(messageString,
  1057. {
  1058. title: titleString,
  1059. persistent: false
  1060. }
  1061. );
  1062. }
  1063. /**
  1064. * Locks / unlocks the room.
  1065. */
  1066. function lockRoom(lock) {
  1067. if (lock)
  1068. connection.emuc.lockRoom(sharedKey);
  1069. else
  1070. connection.emuc.lockRoom('');
  1071. Toolbar.updateLockButton();
  1072. }
  1073. /**
  1074. * Sets the shared key.
  1075. */
  1076. function setSharedKey(sKey) {
  1077. sharedKey = sKey;
  1078. }
  1079. function setRecordingToken(token) {
  1080. recordingToken = token;
  1081. }
  1082. /**
  1083. * Updates the room invite url.
  1084. */
  1085. function updateRoomUrl(newRoomUrl) {
  1086. roomUrl = newRoomUrl;
  1087. // If the invite dialog has been already opened we update the information.
  1088. var inviteLink = document.getElementById('inviteLinkRef');
  1089. if (inviteLink) {
  1090. inviteLink.value = roomUrl;
  1091. inviteLink.select();
  1092. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1093. }
  1094. }
  1095. /**
  1096. * Warning to the user that the conference window is about to be closed.
  1097. */
  1098. function closePageWarning() {
  1099. if (focus !== null)
  1100. return "You are the owner of this conference call and"
  1101. + " you are about to end it.";
  1102. else
  1103. return "You are about to leave this conversation.";
  1104. }
  1105. /**
  1106. * Resizes and repositions videos in full screen mode.
  1107. */
  1108. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1109. function () {
  1110. VideoLayout.resizeLargeVideoContainer();
  1111. VideoLayout.positionLarge();
  1112. isFullScreen = document.fullScreen ||
  1113. document.mozFullScreen ||
  1114. document.webkitIsFullScreen;
  1115. if (isFullScreen) {
  1116. setView("fullscreen");
  1117. }
  1118. else {
  1119. setView("default");
  1120. }
  1121. }
  1122. );
  1123. /**
  1124. * Sets the current view.
  1125. */
  1126. function setView(viewName) {
  1127. // if (viewName == "fullscreen") {
  1128. // document.getElementById('videolayout_fullscreen').disabled = false;
  1129. // document.getElementById('videolayout_default').disabled = true;
  1130. // }
  1131. // else {
  1132. // document.getElementById('videolayout_default').disabled = false;
  1133. // document.getElementById('videolayout_fullscreen').disabled = true;
  1134. // }
  1135. }
  1136. function hangUp() {
  1137. if (connection && connection.connected) {
  1138. // ensure signout
  1139. $.ajax({
  1140. type: 'POST',
  1141. url: config.bosh,
  1142. async: false,
  1143. cache: false,
  1144. contentType: 'application/xml',
  1145. 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>",
  1146. success: function (data) {
  1147. console.log('signed out');
  1148. console.log(data);
  1149. },
  1150. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1151. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1152. }
  1153. });
  1154. }
  1155. disposeConference(true);
  1156. }
  1157. $(document).bind('fatalError.jingle',
  1158. function (event, session, error)
  1159. {
  1160. sessionTerminated = true;
  1161. connection.emuc.doLeave();
  1162. openMessageDialog( "Sorry",
  1163. "Your browser version is too old. Please update and try again...");
  1164. }
  1165. );
  1166. function callSipButtonClicked()
  1167. {
  1168. $.prompt('<h2>Enter SIP number</h2>' +
  1169. '<input id="sipNumber" type="text" value="" autofocus>',
  1170. {
  1171. persistent: false,
  1172. buttons: { "Dial": true, "Cancel": false},
  1173. defaultButton: 2,
  1174. loaded: function (event)
  1175. {
  1176. document.getElementById('sipNumber').focus();
  1177. },
  1178. submit: function (e, v, m, f)
  1179. {
  1180. if (v)
  1181. {
  1182. var numberInput = document.getElementById('sipNumber');
  1183. if (numberInput.value && numberInput.value.length)
  1184. {
  1185. connection.rayo.dial(
  1186. numberInput.value, 'fromnumber', roomName);
  1187. }
  1188. }
  1189. }
  1190. }
  1191. );
  1192. }
  1193. function hangup() {
  1194. disposeConference();
  1195. sessionTerminated = true;
  1196. connection.emuc.doLeave();
  1197. var buttons = {};
  1198. if(config.enableWelcomePage)
  1199. {
  1200. setTimeout(function()
  1201. {
  1202. window.localStorage.welcomePageDisabled = false;
  1203. window.location.pathname = "/";
  1204. }, 10000);
  1205. }
  1206. $.prompt("Session Terminated",
  1207. {
  1208. title: "You hung up the call",
  1209. persistent: true,
  1210. buttons: {
  1211. "Join again": true
  1212. },
  1213. closeText: '',
  1214. submit: function(event, value, message, formVals)
  1215. {
  1216. window.location.reload();
  1217. return false;
  1218. }
  1219. }
  1220. );
  1221. }