選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

app.js 43KB

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