You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 53KB

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