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.

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