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

app.js 54KB

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