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.

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