Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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