您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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