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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var activecall = null;
  6. var RTC = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var recordingToken ='';
  10. var roomUrl = null;
  11. var ssrc2jid = {};
  12. /**
  13. * The stats collector that process stats data and triggers updates to app.js.
  14. * @type {StatsCollector}
  15. */
  16. var statsCollector = null;
  17. /**
  18. * The stats collector for the local stream.
  19. * @type {LocalStatsCollector}
  20. */
  21. var localStatsCollector = null;
  22. /**
  23. * Indicates whether ssrc is camera video or desktop stream.
  24. * FIXME: remove those maps
  25. */
  26. var ssrc2videoType = {};
  27. var videoSrcToSsrc = {};
  28. /**
  29. * Currently focused video "src"(displayed in large video).
  30. * @type {String}
  31. */
  32. var focusedVideoSrc = null;
  33. var mutedAudios = {};
  34. var localVideoSrc = null;
  35. var flipXLocalVideo = true;
  36. var isFullScreen = false;
  37. var toolbarTimeout = null;
  38. var currentVideoWidth = null;
  39. var currentVideoHeight = null;
  40. /**
  41. * Method used to calculate large video size.
  42. * @type {function ()}
  43. */
  44. var getVideoSize;
  45. /**
  46. * Method used to get large video position.
  47. * @type {function ()}
  48. */
  49. var getVideoPosition;
  50. /* window.onbeforeunload = closePageWarning; */
  51. var sessionTerminated = false;
  52. function init() {
  53. RTC = setupRTC();
  54. if (RTC === null) {
  55. window.location.href = 'webrtcrequired.html';
  56. return;
  57. } else if (RTC.browser !== 'chrome') {
  58. window.location.href = 'chromeonly.html';
  59. return;
  60. }
  61. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  62. if (nickname) {
  63. connection.emuc.addDisplayNameToPresence(nickname);
  64. }
  65. if (connection.disco) {
  66. // for chrome, add multistream cap
  67. }
  68. connection.jingle.pc_constraints = RTC.pc_constraints;
  69. if (config.useIPv6) {
  70. // https://code.google.com/p/webrtc/issues/detail?id=2828
  71. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  72. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  73. }
  74. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  75. connection.connect(jid, document.getElementById('password').value, function (status) {
  76. if (status === Strophe.Status.CONNECTED) {
  77. console.log('connected');
  78. if (config.useStunTurn) {
  79. connection.jingle.getStunAndTurnCredentials();
  80. }
  81. obtainAudioAndVideoPermissions(function () {
  82. getUserMediaWithConstraints(['audio'], audioStreamReady,
  83. function (error) {
  84. console.error('failed to obtain audio stream - stop', error);
  85. });
  86. });
  87. document.getElementById('connect').disabled = true;
  88. } else {
  89. console.log('status', status);
  90. }
  91. });
  92. }
  93. /**
  94. * HTTPS only:
  95. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  96. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  97. */
  98. function obtainAudioAndVideoPermissions(callback) {
  99. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  100. if (location.protocol !== 'https:') {
  101. callback();
  102. return;
  103. }
  104. // Get AV
  105. getUserMediaWithConstraints(
  106. ['audio', 'video'],
  107. function (avStream) {
  108. avStream.stop();
  109. callback();
  110. },
  111. function (error) {
  112. console.error('failed to obtain audio/video stream - stop', error);
  113. });
  114. }
  115. function audioStreamReady(stream) {
  116. VideoLayout.changeLocalAudio(stream);
  117. startLocalRtpStatsCollector(stream);
  118. if (RTC.browser !== 'firefox') {
  119. getUserMediaWithConstraints(['video'],
  120. videoStreamReady,
  121. videoStreamFailed,
  122. config.resolution || '360');
  123. } else {
  124. doJoin();
  125. }
  126. }
  127. function videoStreamReady(stream) {
  128. VideoLayout.changeLocalVideo(stream, true);
  129. doJoin();
  130. }
  131. function videoStreamFailed(error) {
  132. console.warn("Failed to obtain video stream - continue anyway", error);
  133. doJoin();
  134. }
  135. function doJoin() {
  136. var roomnode = null;
  137. var path = window.location.pathname;
  138. var roomjid;
  139. // determinde the room node from the url
  140. // TODO: just the roomnode or the whole bare jid?
  141. if (config.getroomnode && typeof config.getroomnode === 'function') {
  142. // custom function might be responsible for doing the pushstate
  143. roomnode = config.getroomnode(path);
  144. } else {
  145. /* fall back to default strategy
  146. * this is making assumptions about how the URL->room mapping happens.
  147. * It currently assumes deployment at root, with a rewrite like the
  148. * following one (for nginx):
  149. location ~ ^/([a-zA-Z0-9]+)$ {
  150. rewrite ^/(.*)$ / break;
  151. }
  152. */
  153. if (path.length > 1) {
  154. roomnode = path.substr(1).toLowerCase();
  155. } else {
  156. roomnode = Math.random().toString(36).substr(2, 20);
  157. window.history.pushState('VideoChat',
  158. 'Room: ' + roomnode, window.location.pathname + roomnode);
  159. }
  160. }
  161. roomjid = roomnode + '@' + config.hosts.muc;
  162. if (config.useNicks) {
  163. var nick = window.prompt('Your nickname (optional)');
  164. if (nick) {
  165. roomjid += '/' + nick;
  166. } else {
  167. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  168. }
  169. } else {
  170. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0, 8);
  171. }
  172. connection.emuc.doJoin(roomjid);
  173. }
  174. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  175. function waitForRemoteVideo(selector, sid, ssrc) {
  176. if (selector.removed) {
  177. console.warn("media removed before had started", selector);
  178. return;
  179. }
  180. var sess = connection.jingle.sessions[sid];
  181. if (data.stream.id === 'mixedmslabel') return;
  182. var videoTracks = data.stream.getVideoTracks();
  183. // console.log("waiting..", videoTracks, selector[0]);
  184. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  185. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  186. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  187. // in order to get rid of too many maps
  188. if (ssrc) {
  189. videoSrcToSsrc[sel.attr('src')] = ssrc;
  190. } else {
  191. console.warn("No ssrc given for video", sel);
  192. }
  193. $(document).trigger('callactive.jingle', [selector, sid]);
  194. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  195. } else {
  196. setTimeout(function () { waitForRemoteVideo(selector, sid, ssrc); }, 250);
  197. }
  198. }
  199. var sess = connection.jingle.sessions[sid];
  200. var thessrc;
  201. // look up an associated JID for a stream id
  202. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  203. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  204. ssrclines = ssrclines.filter(function (line) {
  205. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  206. });
  207. if (ssrclines.length) {
  208. thessrc = ssrclines[0].substring(7).split(' ')[0];
  209. // ok to overwrite the one from focus? might save work in colibri.js
  210. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  211. if (ssrc2jid[thessrc]) {
  212. data.peerjid = ssrc2jid[thessrc];
  213. }
  214. }
  215. }
  216. var container;
  217. var remotes = document.getElementById('remoteVideos');
  218. if (data.peerjid) {
  219. VideoLayout.ensurePeerContainerExists(data.peerjid);
  220. container = document.getElementById(
  221. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  222. } else {
  223. if (data.stream.id !== 'mixedmslabel') {
  224. console.error( 'can not associate stream',
  225. data.stream.id,
  226. 'with a participant');
  227. // We don't want to add it here since it will cause troubles
  228. return;
  229. }
  230. // FIXME: for the mixed ms we dont need a video -- currently
  231. container = document.createElement('span');
  232. container.className = 'videocontainer';
  233. remotes.appendChild(container);
  234. Util.playSoundNotification('userJoined');
  235. }
  236. var isVideo = data.stream.getVideoTracks().length > 0;
  237. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  238. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  239. vid.id = id;
  240. vid.autoplay = true;
  241. vid.oncontextmenu = function () { return false; };
  242. container.appendChild(vid);
  243. // TODO: make mixedstream display:none via css?
  244. if (id.indexOf('mixedmslabel') !== -1) {
  245. container.id = 'mixedstream';
  246. $(container).hide();
  247. }
  248. var sel = $('#' + id);
  249. sel.hide();
  250. RTC.attachMediaStream(sel, data.stream);
  251. if (isVideo) {
  252. waitForRemoteVideo(sel, sid, thessrc);
  253. }
  254. data.stream.onended = function () {
  255. console.log('stream ended', this.id);
  256. // Mark video as removed to cancel waiting loop(if video is removed before has started)
  257. sel.removed = true;
  258. sel.remove();
  259. var audioCount = $('#' + container.id + '>audio').length;
  260. var videoCount = $('#' + container.id + '>video').length;
  261. if (!audioCount && !videoCount) {
  262. console.log("Remove whole user", container.id);
  263. // Remove whole container
  264. container.remove();
  265. Util.playSoundNotification('userLeft');
  266. VideoLayout.resizeThumbnails();
  267. }
  268. VideoLayout.checkChangeLargeVideo(vid.src);
  269. };
  270. // Add click handler.
  271. container.onclick = function (event) {
  272. /*
  273. * FIXME It turns out that videoThumb may not exist (if there is no
  274. * actual video).
  275. */
  276. var videoThumb = $('#' + container.id + '>video').get(0);
  277. if (videoThumb)
  278. VideoLayout.handleVideoThumbClicked(videoThumb.src);
  279. event.preventDefault();
  280. return false;
  281. };
  282. // Add hover handler
  283. $(container).hover(
  284. function() {
  285. VideoLayout.showDisplayName(container.id, true);
  286. },
  287. function() {
  288. var videoSrc = null;
  289. if ($('#' + container.id + '>video')
  290. && $('#' + container.id + '>video').length > 0) {
  291. videoSrc = $('#' + container.id + '>video').get(0).src;
  292. }
  293. // If the video has been "pinned" by the user we want to keep the
  294. // display name on place.
  295. if (!VideoLayout.isLargeVideoVisible()
  296. || videoSrc !== $('#largeVideo').attr('src'))
  297. VideoLayout.showDisplayName(container.id, false);
  298. }
  299. );
  300. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  301. if (isVideo &&
  302. data.peerjid && sess.peerjid === data.peerjid &&
  303. data.stream.getVideoTracks().length === 0 &&
  304. connection.jingle.localVideo.getVideoTracks().length > 0) {
  305. //
  306. window.setTimeout(function () {
  307. sendKeyframe(sess.peerconnection);
  308. }, 3000);
  309. }
  310. });
  311. /**
  312. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  313. * @param videoSrc the video "src" identifier.
  314. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  315. * belongs.
  316. */
  317. function getJidFromVideoSrc(videoSrc)
  318. {
  319. if (videoSrc === localVideoSrc)
  320. return connection.emuc.myroomjid;
  321. var ssrc = videoSrcToSsrc[videoSrc];
  322. if (!ssrc)
  323. {
  324. return null;
  325. }
  326. return ssrc2jid[ssrc];
  327. }
  328. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  329. function sendKeyframe(pc) {
  330. console.log('sendkeyframe', pc.iceConnectionState);
  331. if (pc.iceConnectionState !== 'connected') return; // safe...
  332. pc.setRemoteDescription(
  333. pc.remoteDescription,
  334. function () {
  335. pc.createAnswer(
  336. function (modifiedAnswer) {
  337. pc.setLocalDescription(
  338. modifiedAnswer,
  339. function () {
  340. // noop
  341. },
  342. function (error) {
  343. console.log('triggerKeyframe setLocalDescription failed', error);
  344. }
  345. );
  346. },
  347. function (error) {
  348. console.log('triggerKeyframe createAnswer failed', error);
  349. }
  350. );
  351. },
  352. function (error) {
  353. console.log('triggerKeyframe setRemoteDescription failed', error);
  354. }
  355. );
  356. }
  357. // Really mute video, i.e. dont even send black frames
  358. function muteVideo(pc, unmute) {
  359. // FIXME: this probably needs another of those lovely state safeguards...
  360. // which checks for iceconn == connected and sigstate == stable
  361. pc.setRemoteDescription(pc.remoteDescription,
  362. function () {
  363. pc.createAnswer(
  364. function (answer) {
  365. var sdp = new SDP(answer.sdp);
  366. if (sdp.media.length > 1) {
  367. if (unmute)
  368. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  369. else
  370. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  371. sdp.raw = sdp.session + sdp.media.join('');
  372. answer.sdp = sdp.raw;
  373. }
  374. pc.setLocalDescription(answer,
  375. function () {
  376. console.log('mute SLD ok');
  377. },
  378. function (error) {
  379. console.log('mute SLD error');
  380. }
  381. );
  382. },
  383. function (error) {
  384. console.log(error);
  385. }
  386. );
  387. },
  388. function (error) {
  389. console.log('muteVideo SRD error');
  390. }
  391. );
  392. }
  393. /**
  394. * Callback called by {@link StatsCollector} in intervals supplied to it's
  395. * constructor.
  396. * @param statsCollector {@link StatsCollector} source of the event.
  397. */
  398. function statsUpdated(statsCollector)
  399. {
  400. Object.keys(statsCollector.jid2stats).forEach(function (jid)
  401. {
  402. var peerStats = statsCollector.jid2stats[jid];
  403. Object.keys(peerStats.ssrc2AudioLevel).forEach(function (ssrc)
  404. {
  405. if (jid !== connection.emuc.myRoomJid)
  406. AudioLevels.updateAudioLevel( Strophe.getResourceFromJid(jid),
  407. peerStats.ssrc2AudioLevel[ssrc]);
  408. });
  409. });
  410. }
  411. /**
  412. * Callback called by {@link LocalStatsCollector} in intervals supplied to it's
  413. * constructor.
  414. * @param statsCollector {@link LocalStatsCollector} source of the event.
  415. */
  416. function localStatsUpdated(statsCollector)
  417. {
  418. if (connection.emuc.myRoomJid)
  419. AudioLevels.updateAudioLevel(
  420. Strophe.getResourceFromJid(connection.emuc.myRoomJid),
  421. statsCollector.audioLevel);
  422. }
  423. /**
  424. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  425. */
  426. function startRtpStatsCollector()
  427. {
  428. stopRTPStatsCollector();
  429. if (config.enableRtpStats)
  430. {
  431. statsCollector = new StatsCollector(
  432. getConferenceHandler().peerconnection, 200, statsUpdated);
  433. stopLocalRtpStatsCollector();
  434. statsCollector.start();
  435. }
  436. }
  437. /**
  438. * Stops the {@link StatsCollector}.
  439. */
  440. function stopRTPStatsCollector()
  441. {
  442. if (statsCollector)
  443. {
  444. statsCollector.stop();
  445. statsCollector = null;
  446. }
  447. }
  448. /**
  449. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  450. * @param stream the stream that will be used for collecting statistics.
  451. */
  452. function startLocalRtpStatsCollector(stream)
  453. {
  454. if(config.enableRtpStats)
  455. {
  456. localStatsCollector = new LocalStatsCollector(stream, 200, localStatsUpdated);
  457. localStatsCollector.start();
  458. }
  459. }
  460. /**
  461. * Stops the {@link LocalStatsCollector}.
  462. */
  463. function stopLocalRtpStatsCollector()
  464. {
  465. if(localStatsCollector)
  466. {
  467. localStatsCollector.stop();
  468. localStatsCollector = null;
  469. }
  470. }
  471. $(document).bind('callincoming.jingle', function (event, sid) {
  472. var sess = connection.jingle.sessions[sid];
  473. // TODO: do we check activecall == null?
  474. activecall = sess;
  475. startRtpStatsCollector();
  476. // Bind data channel listener in case we're a regular participant
  477. if (config.openSctp)
  478. {
  479. bindDataChannelListener(sess.peerconnection);
  480. }
  481. // TODO: check affiliation and/or role
  482. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  483. sess.usedrip = true; // not-so-naive trickle ice
  484. sess.sendAnswer();
  485. sess.accept();
  486. });
  487. $(document).bind('conferenceCreated.jingle', function (event, focus)
  488. {
  489. startRtpStatsCollector();
  490. });
  491. $(document).bind('conferenceCreated.jingle', function (event, focus)
  492. {
  493. // Bind data channel listener in case we're the focus
  494. if (config.openSctp)
  495. {
  496. bindDataChannelListener(focus.peerconnection);
  497. }
  498. });
  499. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  500. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  501. // ignore mixedmslabela0 and v0
  502. videoelem.show();
  503. VideoLayout.resizeThumbnails();
  504. // Update the large video to the last added video only if there's no
  505. // current active or focused speaker.
  506. if (!focusedVideoSrc && !VideoLayout.getDominantSpeakerResourceJid())
  507. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  508. VideoLayout.showFocusIndicator();
  509. }
  510. });
  511. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  512. // Leave the room if my call has been remotely terminated.
  513. if (connection.emuc.joined && focus == null && reason === 'kick') {
  514. sessionTerminated = true;
  515. connection.emuc.doLeave();
  516. openMessageDialog( "Session Terminated",
  517. "Ouch! You have been kicked out of the meet!");
  518. }
  519. });
  520. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  521. // put our ssrcs into presence so other clients can identify our stream
  522. var sess = connection.jingle.sessions[sid];
  523. var newssrcs = {};
  524. var directions = {};
  525. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  526. localSDP.media.forEach(function (media) {
  527. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  528. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  529. // assumes a single local ssrc
  530. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  531. newssrcs[type] = ssrc;
  532. directions[type] = (
  533. SDPUtil.find_line(media, 'a=sendrecv') ||
  534. SDPUtil.find_line(media, 'a=recvonly') ||
  535. SDPUtil.find_line(media, 'a=sendonly') ||
  536. SDPUtil.find_line(media, 'a=inactive') ||
  537. 'a=sendrecv').substr(2);
  538. }
  539. });
  540. console.log('new ssrcs', newssrcs);
  541. // Have to clear presence map to get rid of removed streams
  542. connection.emuc.clearPresenceMedia();
  543. var i = 0;
  544. Object.keys(newssrcs).forEach(function (mtype) {
  545. i++;
  546. var type = mtype;
  547. // Change video type to screen
  548. if (mtype === 'video' && isUsingScreenStream) {
  549. type = 'screen';
  550. }
  551. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  552. });
  553. if (i > 0) {
  554. connection.emuc.sendPresence();
  555. }
  556. });
  557. $(document).bind('joined.muc', function (event, jid, info) {
  558. updateRoomUrl(window.location.href);
  559. document.getElementById('localNick').appendChild(
  560. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  561. );
  562. if (Object.keys(connection.emuc.members).length < 1) {
  563. focus = new ColibriFocus(connection, config.hosts.bridge);
  564. if (nickname !== null) {
  565. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  566. nickname);
  567. }
  568. Toolbar.showRecordingButton(false);
  569. }
  570. if (focus && config.etherpad_base) {
  571. Etherpad.init();
  572. }
  573. VideoLayout.showFocusIndicator();
  574. // Once we've joined the muc show the toolbar
  575. Toolbar.showToolbar();
  576. var displayName = '';
  577. if (info.displayName)
  578. displayName = info.displayName + ' (me)';
  579. VideoLayout.setDisplayName('localVideoContainer', displayName);
  580. });
  581. $(document).bind('entered.muc', function (event, jid, info, pres) {
  582. console.log('entered', jid, info);
  583. console.log('is focus?' + focus ? 'true' : 'false');
  584. // Add Peer's container
  585. VideoLayout.ensurePeerContainerExists(jid);
  586. if (focus !== null) {
  587. // FIXME: this should prepare the video
  588. if (focus.confid === null) {
  589. console.log('make new conference with', jid);
  590. focus.makeConference(Object.keys(connection.emuc.members));
  591. Toolbar.showRecordingButton(true);
  592. } else {
  593. console.log('invite', jid, 'into conference');
  594. focus.addNewParticipant(jid);
  595. }
  596. }
  597. else if (sharedKey) {
  598. Toolbar.updateLockButton();
  599. }
  600. });
  601. $(document).bind('left.muc', function (event, jid) {
  602. console.log('left.muc', jid);
  603. // Need to call this with a slight delay, otherwise the element couldn't be
  604. // found for some reason.
  605. window.setTimeout(function () {
  606. var container = document.getElementById(
  607. 'participant_' + Strophe.getResourceFromJid(jid));
  608. if (container) {
  609. // hide here, wait for video to close before removing
  610. $(container).hide();
  611. VideoLayout.resizeThumbnails();
  612. }
  613. }, 10);
  614. // Unlock large video
  615. if (focusedVideoSrc)
  616. {
  617. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  618. {
  619. console.info("Focused video owner has left the conference");
  620. focusedVideoSrc = null;
  621. }
  622. }
  623. connection.jingle.terminateByJid(jid);
  624. if (focus == null
  625. // I shouldn't be the one that left to enter here.
  626. && jid !== connection.emuc.myroomjid
  627. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  628. // If our session has been terminated for some reason
  629. // (kicked, hangup), don't try to become the focus
  630. && !sessionTerminated) {
  631. console.log('welcome to our new focus... myself');
  632. focus = new ColibriFocus(connection, config.hosts.bridge);
  633. if (nickname !== null) {
  634. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  635. nickname);
  636. }
  637. if (Object.keys(connection.emuc.members).length > 0) {
  638. focus.makeConference(Object.keys(connection.emuc.members));
  639. Toolbar.showRecordingButton(true);
  640. }
  641. $(document).trigger('focusechanged.muc', [focus]);
  642. }
  643. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  644. console.log('everyone left');
  645. // FIXME: closing the connection is a hack to avoid some
  646. // problems with reinit
  647. disposeConference();
  648. focus = new ColibriFocus(connection, config.hosts.bridge);
  649. if (nickname !== null) {
  650. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  651. nickname);
  652. }
  653. Toolbar.showRecordingButton(false);
  654. }
  655. if (connection.emuc.getPrezi(jid)) {
  656. $(document).trigger('presentationremoved.muc',
  657. [jid, connection.emuc.getPrezi(jid)]);
  658. }
  659. });
  660. $(document).bind('presence.muc', function (event, jid, info, pres) {
  661. // Remove old ssrcs coming from the jid
  662. Object.keys(ssrc2jid).forEach(function (ssrc) {
  663. if (ssrc2jid[ssrc] == jid) {
  664. delete ssrc2jid[ssrc];
  665. }
  666. if (ssrc2videoType[ssrc] == jid) {
  667. delete ssrc2videoType[ssrc];
  668. }
  669. });
  670. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  671. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  672. var ssrcV = ssrc.getAttribute('ssrc');
  673. ssrc2jid[ssrcV] = jid;
  674. var type = ssrc.getAttribute('type');
  675. ssrc2videoType[ssrcV] = type;
  676. // might need to update the direction if participant just went from sendrecv to recvonly
  677. if (type === 'video' || type === 'screen') {
  678. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  679. switch (ssrc.getAttribute('direction')) {
  680. case 'sendrecv':
  681. el.show();
  682. break;
  683. case 'recvonly':
  684. el.hide();
  685. // FIXME: Check if we have to change large video
  686. //VideoLayout.checkChangeLargeVideo(el);
  687. break;
  688. }
  689. }
  690. });
  691. if (jid === connection.emuc.myroomjid) {
  692. VideoLayout.setDisplayName('localVideoContainer',
  693. info.displayName);
  694. } else {
  695. VideoLayout.ensurePeerContainerExists(jid);
  696. VideoLayout.setDisplayName(
  697. 'participant_' + Strophe.getResourceFromJid(jid),
  698. info.displayName);
  699. }
  700. if (focus !== null && info.displayName !== null) {
  701. focus.setEndpointDisplayName(jid, info.displayName);
  702. }
  703. });
  704. $(document).bind('passwordrequired.muc', function (event, jid) {
  705. console.log('on password required', jid);
  706. $.prompt('<h2>Password required</h2>' +
  707. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  708. persistent: true,
  709. buttons: { "Ok": true, "Cancel": false},
  710. defaultButton: 1,
  711. loaded: function (event) {
  712. document.getElementById('lockKey').focus();
  713. },
  714. submit: function (e, v, m, f) {
  715. if (v) {
  716. var lockKey = document.getElementById('lockKey');
  717. if (lockKey.value !== null) {
  718. setSharedKey(lockKey.value);
  719. connection.emuc.doJoin(jid, lockKey.value);
  720. }
  721. }
  722. }
  723. });
  724. });
  725. /**
  726. * Checks if video identified by given src is desktop stream.
  727. * @param videoSrc eg.
  728. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  729. * @returns {boolean}
  730. */
  731. function isVideoSrcDesktop(videoSrc) {
  732. // FIXME: fix this mapping mess...
  733. // figure out if large video is desktop stream or just a camera
  734. var isDesktop = false;
  735. if (localVideoSrc === videoSrc) {
  736. // local video
  737. isDesktop = isUsingScreenStream;
  738. } else {
  739. // Do we have associations...
  740. var videoSsrc = videoSrcToSsrc[videoSrc];
  741. if (videoSsrc) {
  742. var videoType = ssrc2videoType[videoSsrc];
  743. if (videoType) {
  744. // Finally there...
  745. isDesktop = videoType === 'screen';
  746. } else {
  747. console.error("No video type for ssrc: " + videoSsrc);
  748. }
  749. } else {
  750. console.error("No ssrc for src: " + videoSrc);
  751. }
  752. }
  753. return isDesktop;
  754. }
  755. function getConferenceHandler() {
  756. return focus ? focus : activecall;
  757. }
  758. function toggleVideo() {
  759. if (!(connection && connection.jingle.localVideo))
  760. return;
  761. var sess = getConferenceHandler();
  762. if (sess) {
  763. sess.toggleVideoMute(
  764. function (isMuted) {
  765. if (isMuted) {
  766. $('#video').removeClass("icon-camera");
  767. $('#video').addClass("icon-camera icon-camera-disabled");
  768. } else {
  769. $('#video').removeClass("icon-camera icon-camera-disabled");
  770. $('#video').addClass("icon-camera");
  771. }
  772. }
  773. );
  774. }
  775. sess = focus || activecall;
  776. if (!sess) {
  777. return;
  778. }
  779. sess.pendingop = ismuted ? 'unmute' : 'mute';
  780. // connection.emuc.addVideoInfoToPresence(!ismuted);
  781. // connection.emuc.sendPresence();
  782. sess.modifySources();
  783. }
  784. /**
  785. * Mutes / unmutes audio for the local participant.
  786. */
  787. function toggleAudio() {
  788. if (!(connection && connection.jingle.localAudio)) {
  789. preMuted = true;
  790. // We still click the button.
  791. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  792. return;
  793. }
  794. var localAudio = connection.jingle.localAudio;
  795. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  796. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  797. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  798. // isMuted is the opposite of audioEnabled
  799. connection.emuc.addAudioInfoToPresence(audioEnabled);
  800. connection.emuc.sendPresence();
  801. }
  802. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  803. }
  804. // Starts or stops the recording for the conference.
  805. function toggleRecording() {
  806. if (focus === null || focus.confid === null) {
  807. console.log('non-focus, or conference not yet organized: not enabling recording');
  808. return;
  809. }
  810. if (!recordingToken)
  811. {
  812. $.prompt('<h2>Enter recording token</h2>' +
  813. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  814. {
  815. persistent: false,
  816. buttons: { "Save": true, "Cancel": false},
  817. defaultButton: 1,
  818. loaded: function (event) {
  819. document.getElementById('recordingToken').focus();
  820. },
  821. submit: function (e, v, m, f) {
  822. if (v) {
  823. var token = document.getElementById('recordingToken');
  824. if (token.value) {
  825. setRecordingToken(Util.escapeHtml(token.value));
  826. toggleRecording();
  827. }
  828. }
  829. }
  830. }
  831. );
  832. return;
  833. }
  834. var oldState = focus.recordingEnabled;
  835. Toolbar.toggleRecordingButtonState();
  836. focus.setRecording(!oldState,
  837. recordingToken,
  838. function (state) {
  839. console.log("New recording state: ", state);
  840. if (state == oldState) //failed to change, reset the token because it might have been wrong
  841. {
  842. Toolbar.toggleRecordingButtonState();
  843. setRecordingToken(null);
  844. }
  845. }
  846. );
  847. }
  848. /**
  849. * Returns an array of the video horizontal and vertical indents,
  850. * so that if fits its parent.
  851. *
  852. * @return an array with 2 elements, the horizontal indent and the vertical
  853. * indent
  854. */
  855. function getCameraVideoPosition(videoWidth,
  856. videoHeight,
  857. videoSpaceWidth,
  858. videoSpaceHeight) {
  859. // Parent height isn't completely calculated when we position the video in
  860. // full screen mode and this is why we use the screen height in this case.
  861. // Need to think it further at some point and implement it properly.
  862. var isFullScreen = document.fullScreen ||
  863. document.mozFullScreen ||
  864. document.webkitIsFullScreen;
  865. if (isFullScreen)
  866. videoSpaceHeight = window.innerHeight;
  867. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  868. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  869. return [horizontalIndent, verticalIndent];
  870. }
  871. /**
  872. * Returns an array of the video horizontal and vertical indents.
  873. * Centers horizontally and top aligns vertically.
  874. *
  875. * @return an array with 2 elements, the horizontal indent and the vertical
  876. * indent
  877. */
  878. function getDesktopVideoPosition(videoWidth,
  879. videoHeight,
  880. videoSpaceWidth,
  881. videoSpaceHeight) {
  882. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  883. var verticalIndent = 0;// Top aligned
  884. return [horizontalIndent, verticalIndent];
  885. }
  886. /**
  887. * Returns an array of the video dimensions, so that it covers the screen.
  888. * It leaves no empty areas, but some parts of the video might not be visible.
  889. *
  890. * @return an array with 2 elements, the video width and the video height
  891. */
  892. function getCameraVideoSize(videoWidth,
  893. videoHeight,
  894. videoSpaceWidth,
  895. videoSpaceHeight) {
  896. if (!videoWidth)
  897. videoWidth = currentVideoWidth;
  898. if (!videoHeight)
  899. videoHeight = currentVideoHeight;
  900. var aspectRatio = videoWidth / videoHeight;
  901. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  902. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  903. if (availableWidth / aspectRatio < videoSpaceHeight) {
  904. availableHeight = videoSpaceHeight;
  905. availableWidth = availableHeight * aspectRatio;
  906. }
  907. if (availableHeight * aspectRatio < videoSpaceWidth) {
  908. availableWidth = videoSpaceWidth;
  909. availableHeight = availableWidth / aspectRatio;
  910. }
  911. return [availableWidth, availableHeight];
  912. }
  913. $(document).ready(function () {
  914. Chat.init();
  915. $('body').popover({ selector: '[data-toggle=popover]',
  916. trigger: 'click hover'});
  917. // Set the defaults for prompt dialogs.
  918. jQuery.prompt.setDefaults({persistent: false});
  919. // Set default desktop sharing method
  920. setDesktopSharing(config.desktopSharing);
  921. // Initialize Chrome extension inline installs
  922. if (config.chromeExtensionId) {
  923. initInlineInstalls();
  924. }
  925. // By default we use camera
  926. getVideoSize = getCameraVideoSize;
  927. getVideoPosition = getCameraVideoPosition;
  928. VideoLayout.resizeLargeVideoContainer();
  929. $(window).resize(function () {
  930. VideoLayout.resizeLargeVideoContainer();
  931. VideoLayout.positionLarge();
  932. });
  933. // Listen for large video size updates
  934. document.getElementById('largeVideo')
  935. .addEventListener('loadedmetadata', function (e) {
  936. currentVideoWidth = this.videoWidth;
  937. currentVideoHeight = this.videoHeight;
  938. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  939. });
  940. if (!$('#settings').is(':visible')) {
  941. console.log('init');
  942. init();
  943. } else {
  944. loginInfo.onsubmit = function (e) {
  945. if (e.preventDefault) e.preventDefault();
  946. $('#settings').hide();
  947. init();
  948. };
  949. }
  950. });
  951. $(window).bind('beforeunload', function () {
  952. if (connection && connection.connected) {
  953. // ensure signout
  954. $.ajax({
  955. type: 'POST',
  956. url: config.bosh,
  957. async: false,
  958. cache: false,
  959. contentType: 'application/xml',
  960. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  961. success: function (data) {
  962. console.log('signed out');
  963. console.log(data);
  964. },
  965. error: function (XMLHttpRequest, textStatus, errorThrown) {
  966. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  967. }
  968. });
  969. }
  970. disposeConference(true);
  971. });
  972. function disposeConference(onUnload) {
  973. var handler = getConferenceHandler();
  974. if (handler && handler.peerconnection) {
  975. // FIXME: probably removing streams is not required and close() should be enough
  976. if (connection.jingle.localAudio) {
  977. handler.peerconnection.removeStream(connection.jingle.localAudio);
  978. }
  979. if (connection.jingle.localVideo) {
  980. handler.peerconnection.removeStream(connection.jingle.localVideo);
  981. }
  982. handler.peerconnection.close();
  983. }
  984. stopRTPStatsCollector();
  985. if(!onUnload) {
  986. startLocalRtpStatsCollector(connection.jingle.localAudio);
  987. }
  988. else
  989. {
  990. stopLocalRtpStatsCollector();
  991. }
  992. focus = null;
  993. activecall = null;
  994. }
  995. function dump(elem, filename) {
  996. elem = elem.parentNode;
  997. elem.download = filename || 'meetlog.json';
  998. elem.href = 'data:application/json;charset=utf-8,\n';
  999. var data = {};
  1000. if (connection.jingle) {
  1001. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1002. var session = connection.jingle.sessions[sid];
  1003. if (session.peerconnection && session.peerconnection.updateLog) {
  1004. // FIXME: should probably be a .dump call
  1005. data["jingle_" + session.sid] = {
  1006. updateLog: session.peerconnection.updateLog,
  1007. stats: session.peerconnection.stats,
  1008. url: window.location.href
  1009. };
  1010. }
  1011. });
  1012. }
  1013. metadata = {};
  1014. metadata.time = new Date();
  1015. metadata.url = window.location.href;
  1016. metadata.ua = navigator.userAgent;
  1017. if (connection.logger) {
  1018. metadata.xmpp = connection.logger.log;
  1019. }
  1020. data.metadata = metadata;
  1021. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1022. return false;
  1023. }
  1024. /**
  1025. * Changes the style class of the element given by id.
  1026. */
  1027. function buttonClick(id, classname) {
  1028. $(id).toggleClass(classname); // add the class to the clicked element
  1029. }
  1030. /**
  1031. * Shows a message to the user.
  1032. *
  1033. * @param titleString the title of the message
  1034. * @param messageString the text of the message
  1035. */
  1036. function openMessageDialog(titleString, messageString) {
  1037. $.prompt(messageString,
  1038. {
  1039. title: titleString,
  1040. persistent: false
  1041. }
  1042. );
  1043. }
  1044. /**
  1045. * Locks / unlocks the room.
  1046. */
  1047. function lockRoom(lock) {
  1048. if (lock)
  1049. connection.emuc.lockRoom(sharedKey);
  1050. else
  1051. connection.emuc.lockRoom('');
  1052. Toolbar.updateLockButton();
  1053. }
  1054. /**
  1055. * Sets the shared key.
  1056. */
  1057. function setSharedKey(sKey) {
  1058. sharedKey = sKey;
  1059. }
  1060. function setRecordingToken(token) {
  1061. recordingToken = token;
  1062. }
  1063. /**
  1064. * Updates the room invite url.
  1065. */
  1066. function updateRoomUrl(newRoomUrl) {
  1067. roomUrl = newRoomUrl;
  1068. // If the invite dialog has been already opened we update the information.
  1069. var inviteLink = document.getElementById('inviteLinkRef');
  1070. if (inviteLink) {
  1071. inviteLink.value = roomUrl;
  1072. inviteLink.select();
  1073. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1074. }
  1075. }
  1076. /**
  1077. * Warning to the user that the conference window is about to be closed.
  1078. */
  1079. function closePageWarning() {
  1080. if (focus !== null)
  1081. return "You are the owner of this conference call and"
  1082. + " you are about to end it.";
  1083. else
  1084. return "You are about to leave this conversation.";
  1085. }
  1086. /**
  1087. * Resizes and repositions videos in full screen mode.
  1088. */
  1089. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1090. function () {
  1091. VideoLayout.resizeLargeVideoContainer();
  1092. VideoLayout.positionLarge();
  1093. isFullScreen = document.fullScreen ||
  1094. document.mozFullScreen ||
  1095. document.webkitIsFullScreen;
  1096. if (isFullScreen) {
  1097. setView("fullscreen");
  1098. }
  1099. else {
  1100. setView("default");
  1101. }
  1102. }
  1103. );
  1104. /**
  1105. * Sets the current view.
  1106. */
  1107. function setView(viewName) {
  1108. // if (viewName == "fullscreen") {
  1109. // document.getElementById('videolayout_fullscreen').disabled = false;
  1110. // document.getElementById('videolayout_default').disabled = true;
  1111. // }
  1112. // else {
  1113. // document.getElementById('videolayout_default').disabled = false;
  1114. // document.getElementById('videolayout_fullscreen').disabled = true;
  1115. // }
  1116. }
  1117. $(document).bind('fatalError.jingle',
  1118. function (event, session, error)
  1119. {
  1120. sessionTerminated = true;
  1121. connection.emuc.doLeave();
  1122. openMessageDialog( "Sorry",
  1123. "Your browser version is too old. Please update and try again...");
  1124. }
  1125. );