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.

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