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 56KB

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