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

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