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

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