You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. //FIXME:
  4. import createRoomLocker from './modules/UI/authentication/RoomLocker';
  5. //FIXME:
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import ConnectionQuality from './modules/connectionquality/connectionquality';
  8. import Recorder from './modules/recorder/Recorder';
  9. import CQEvents from './service/connectionquality/CQEvents';
  10. import UIEvents from './service/UI/UIEvents';
  11. const ConnectionEvents = JitsiMeetJS.events.connection;
  12. const ConnectionErrors = JitsiMeetJS.errors.connection;
  13. const ConferenceEvents = JitsiMeetJS.events.conference;
  14. const ConferenceErrors = JitsiMeetJS.errors.conference;
  15. const TrackEvents = JitsiMeetJS.events.track;
  16. const TrackErrors = JitsiMeetJS.errors.track;
  17. let room, connection, localAudio, localVideo, roomLocker;
  18. let currentAudioInputDevices, currentVideoInputDevices;
  19. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  20. /**
  21. * Known custom conference commands.
  22. */
  23. const commands = {
  24. CONNECTION_QUALITY: "stats",
  25. EMAIL: "email",
  26. AVATAR_URL: "avatar-url",
  27. ETHERPAD: "etherpad",
  28. SHARED_VIDEO: "shared-video",
  29. CUSTOM_ROLE: "custom-role"
  30. };
  31. /**
  32. * Open Connection. When authentication failed it shows auth dialog.
  33. * @param roomName the room name to use
  34. * @returns Promise<JitsiConnection>
  35. */
  36. function connect(roomName) {
  37. return openConnection({retry: true, roomName: roomName})
  38. .catch(function (err) {
  39. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  40. APP.UI.notifyTokenAuthFailed();
  41. } else {
  42. APP.UI.notifyConnectionFailed(err);
  43. }
  44. throw err;
  45. });
  46. }
  47. /**
  48. * Share data to other users.
  49. * @param command the command
  50. * @param {string} value new value
  51. */
  52. function sendData (command, value) {
  53. room.removeCommand(command);
  54. room.sendCommand(command, {value: value});
  55. }
  56. /**
  57. * Get user nickname by user id.
  58. * @param {string} id user id
  59. * @returns {string?} user nickname or undefined if user is unknown.
  60. */
  61. function getDisplayName (id) {
  62. if (APP.conference.isLocalId(id)) {
  63. return APP.settings.getDisplayName();
  64. }
  65. let participant = room.getParticipantById(id);
  66. if (participant && participant.getDisplayName()) {
  67. return participant.getDisplayName();
  68. }
  69. }
  70. /**
  71. * Mute or unmute local audio stream if it exists.
  72. * @param {boolean} muted if audio stream should be muted or unmuted.
  73. * @param {boolean} indicates if this local audio mute was a result of user
  74. * interaction
  75. *
  76. */
  77. function muteLocalAudio (muted, userInteraction) {
  78. if (!localAudio) {
  79. return;
  80. }
  81. if (muted) {
  82. localAudio.mute().then(function(value) {},
  83. function(value) {
  84. console.warn('Audio Mute was rejected:', value);
  85. }
  86. );
  87. } else {
  88. localAudio.unmute().then(function(value) {},
  89. function(value) {
  90. console.warn('Audio unmute was rejected:', value);
  91. }
  92. );
  93. }
  94. }
  95. /**
  96. * Mute or unmute local video stream if it exists.
  97. * @param {boolean} muted if video stream should be muted or unmuted.
  98. */
  99. function muteLocalVideo (muted) {
  100. if (!localVideo) {
  101. return;
  102. }
  103. if (muted) {
  104. localVideo.mute().then(function(value) {},
  105. function(value) {
  106. console.warn('Video mute was rejected:', value);
  107. }
  108. );
  109. } else {
  110. localVideo.unmute().then(function(value) {},
  111. function(value) {
  112. console.warn('Video unmute was rejected:', value);
  113. }
  114. );
  115. }
  116. }
  117. /**
  118. * Check if the welcome page is enabled and redirects to it.
  119. */
  120. function maybeRedirectToWelcomePage() {
  121. if (!config.enableWelcomePage) {
  122. return;
  123. }
  124. // redirect to welcome page
  125. setTimeout(() => {
  126. APP.settings.setWelcomePageEnabled(true);
  127. window.location.pathname = "/";
  128. }, 3000);
  129. }
  130. /**
  131. * Executes connection.disconnect and shows the feedback dialog
  132. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  133. * @returns Promise.
  134. */
  135. function disconnectAndShowFeedback(requestFeedback) {
  136. APP.UI.hideRingOverLay();
  137. connection.disconnect();
  138. APP.API.sendPostisMessage({
  139. method: 'video-conference-left',
  140. params: {roomName: APP.conference.roomName}
  141. });
  142. if (requestFeedback) {
  143. return APP.UI.requestFeedback();
  144. } else {
  145. return Promise.resolve();
  146. }
  147. }
  148. /**
  149. * Disconnect from the conference and optionally request user feedback.
  150. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  151. */
  152. function hangup (requestFeedback = false) {
  153. const errCallback = (f, err) => {
  154. console.error('Error occurred during hanging up: ', err);
  155. return f();
  156. };
  157. const disconnect = disconnectAndShowFeedback.bind(null, requestFeedback);
  158. APP.conference._room.leave()
  159. .then(disconnect)
  160. .catch(errCallback.bind(null, disconnect))
  161. .then(maybeRedirectToWelcomePage)
  162. .catch(errCallback.bind(null, maybeRedirectToWelcomePage));
  163. }
  164. /**
  165. * Create local tracks of specified types.
  166. * @param {string[]} devices - required track types ('audio', 'video' etc.)
  167. * @param {string|null} [cameraDeviceId] - camera device id, if undefined - one
  168. * from settings will be used
  169. * @param {string|null} [micDeviceId] - microphone device id, if undefined - one
  170. * from settings will be used
  171. * @returns {Promise<JitsiLocalTrack[]>}
  172. */
  173. function createLocalTracks (devices, cameraDeviceId, micDeviceId) {
  174. return JitsiMeetJS.createLocalTracks({
  175. // copy array to avoid mutations inside library
  176. devices: devices.slice(0),
  177. resolution: config.resolution,
  178. cameraDeviceId: typeof cameraDeviceId === 'undefined'
  179. || cameraDeviceId === null
  180. ? APP.settings.getCameraDeviceId()
  181. : cameraDeviceId,
  182. micDeviceId: typeof micDeviceId === 'undefined' || micDeviceId === null
  183. ? APP.settings.getMicDeviceId()
  184. : micDeviceId,
  185. // adds any ff fake device settings if any
  186. firefox_fake_device: config.firefox_fake_device
  187. }).catch(function (err) {
  188. console.error('failed to create local tracks', ...devices, err);
  189. return Promise.reject(err);
  190. });
  191. }
  192. /**
  193. * Stores lists of current 'audioinput' and 'videoinput' devices
  194. * @param {MediaDeviceInfo[]} devices
  195. */
  196. function setCurrentMediaDevices(devices) {
  197. currentAudioInputDevices = devices.filter(
  198. d => d.kind === 'audioinput');
  199. currentVideoInputDevices = devices.filter(
  200. d => d.kind === 'videoinput');
  201. }
  202. /**
  203. * Changes the email for the local user
  204. * @param email {string} the new email
  205. */
  206. function changeLocalEmail(email = '') {
  207. email = email.trim();
  208. if (email === APP.settings.getEmail()) {
  209. return;
  210. }
  211. APP.settings.setEmail(email);
  212. APP.UI.setUserEmail(room.myUserId(), email);
  213. sendData(commands.EMAIL, email);
  214. }
  215. /**
  216. * Changes the local avatar url for the local user
  217. * @param avatarUrl {string} the new avatar url
  218. */
  219. function changeLocalAvatarUrl(avatarUrl = '') {
  220. avatarUrl = avatarUrl.trim();
  221. if (avatarUrl === APP.settings.getAvatarUrl()) {
  222. return;
  223. }
  224. APP.settings.setAvatarUrl(avatarUrl);
  225. APP.UI.setUserAvatarUrl(room.myUserId(), avatarUrl);
  226. sendData(commands.AVATAR_URL, avatarUrl);
  227. }
  228. /**
  229. * Changes the display name for the local user
  230. * @param nickname {string} the new display name
  231. */
  232. function changeLocalDisplayName(nickname = '') {
  233. nickname = nickname.trim();
  234. if (nickname === APP.settings.getDisplayName()) {
  235. return;
  236. }
  237. APP.settings.setDisplayName(nickname);
  238. room.setDisplayName(nickname);
  239. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  240. }
  241. class ConferenceConnector {
  242. constructor(resolve, reject) {
  243. this._resolve = resolve;
  244. this._reject = reject;
  245. this.reconnectTimeout = null;
  246. room.on(ConferenceEvents.CONFERENCE_JOINED,
  247. this._handleConferenceJoined.bind(this));
  248. room.on(ConferenceEvents.CONFERENCE_FAILED,
  249. this._onConferenceFailed.bind(this));
  250. room.on(ConferenceEvents.CONFERENCE_ERROR,
  251. this._onConferenceError.bind(this));
  252. }
  253. _handleConferenceFailed(err, msg) {
  254. this._unsubscribe();
  255. this._reject(err);
  256. }
  257. _onConferenceFailed(err, ...params) {
  258. console.error('CONFERENCE FAILED:', err, ...params);
  259. APP.UI.hideRingOverLay();
  260. switch (err) {
  261. // room is locked by the password
  262. case ConferenceErrors.PASSWORD_REQUIRED:
  263. APP.UI.markRoomLocked(true);
  264. roomLocker.requirePassword().then(function () {
  265. room.join(roomLocker.password);
  266. });
  267. break;
  268. case ConferenceErrors.CONNECTION_ERROR:
  269. {
  270. let [msg] = params;
  271. APP.UI.notifyConnectionFailed(msg);
  272. }
  273. break;
  274. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  275. APP.UI.notifyBridgeDown();
  276. break;
  277. // not enough rights to create conference
  278. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  279. // schedule reconnect to check if someone else created the room
  280. this.reconnectTimeout = setTimeout(function () {
  281. room.join();
  282. }, 5000);
  283. // notify user that auth is required
  284. AuthHandler.requireAuth(room, roomLocker.password);
  285. break;
  286. case ConferenceErrors.RESERVATION_ERROR:
  287. {
  288. let [code, msg] = params;
  289. APP.UI.notifyReservationError(code, msg);
  290. }
  291. break;
  292. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  293. APP.UI.notifyGracefulShutdown();
  294. break;
  295. case ConferenceErrors.JINGLE_FATAL_ERROR:
  296. APP.UI.notifyInternalError();
  297. break;
  298. case ConferenceErrors.CONFERENCE_DESTROYED:
  299. {
  300. let [reason] = params;
  301. APP.UI.hideStats();
  302. APP.UI.notifyConferenceDestroyed(reason);
  303. }
  304. break;
  305. case ConferenceErrors.FOCUS_DISCONNECTED:
  306. {
  307. let [focus, retrySec] = params;
  308. APP.UI.notifyFocusDisconnected(focus, retrySec);
  309. }
  310. break;
  311. case ConferenceErrors.FOCUS_LEFT:
  312. room.leave().then(() => connection.disconnect());
  313. APP.UI.notifyFocusLeft();
  314. break;
  315. case ConferenceErrors.CONFERENCE_MAX_USERS:
  316. connection.disconnect();
  317. APP.UI.notifyMaxUsersLimitReached();
  318. break;
  319. default:
  320. this._handleConferenceFailed(err, ...params);
  321. }
  322. }
  323. _onConferenceError(err, ...params) {
  324. console.error('CONFERENCE Error:', err, params);
  325. switch (err) {
  326. case ConferenceErrors.CHAT_ERROR:
  327. {
  328. let [code, msg] = params;
  329. APP.UI.showChatError(code, msg);
  330. }
  331. break;
  332. default:
  333. console.error("Unknown error.");
  334. }
  335. }
  336. _unsubscribe() {
  337. room.off(
  338. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  339. room.off(
  340. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  341. if (this.reconnectTimeout !== null) {
  342. clearTimeout(this.reconnectTimeout);
  343. }
  344. AuthHandler.closeAuth();
  345. }
  346. _handleConferenceJoined() {
  347. this._unsubscribe();
  348. this._resolve();
  349. }
  350. connect() {
  351. room.join();
  352. }
  353. }
  354. export default {
  355. localId: undefined,
  356. isModerator: false,
  357. audioMuted: false,
  358. videoMuted: false,
  359. isSharingScreen: false,
  360. isDesktopSharingEnabled: false,
  361. /**
  362. * Open new connection and join to the conference.
  363. * @param {object} options
  364. * @param {string} roomName name of the conference
  365. * @returns {Promise}
  366. */
  367. init(options) {
  368. let self = this;
  369. this.roomName = options.roomName;
  370. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  371. // attaches global error handler, if there is already one, respect it
  372. if(JitsiMeetJS.getGlobalOnErrorHandler){
  373. var oldOnErrorHandler = window.onerror;
  374. window.onerror = function (message, source, lineno, colno, error) {
  375. JitsiMeetJS.getGlobalOnErrorHandler(
  376. message, source, lineno, colno, error);
  377. if(oldOnErrorHandler)
  378. oldOnErrorHandler(message, source, lineno, colno, error);
  379. };
  380. var oldOnUnhandledRejection = window.onunhandledrejection;
  381. window.onunhandledrejection = function(event) {
  382. JitsiMeetJS.getGlobalOnErrorHandler(
  383. null, null, null, null, event.reason);
  384. if(oldOnUnhandledRejection)
  385. oldOnUnhandledRejection(event);
  386. };
  387. }
  388. let audioAndVideoError, audioOnlyError;
  389. return JitsiMeetJS.init(config).then(() => {
  390. return Promise.all([
  391. // try to retrieve audio and video
  392. createLocalTracks(['audio', 'video'])
  393. // if failed then try to retrieve only audio
  394. .catch(err => {
  395. audioAndVideoError = err;
  396. return createLocalTracks(['audio']);
  397. })
  398. // if audio also failed then just return empty array
  399. .catch(err => {
  400. audioOnlyError = err;
  401. return [];
  402. }),
  403. connect(options.roomName)
  404. ]);
  405. }).then(([tracks, con]) => {
  406. if (audioAndVideoError) {
  407. if (audioOnlyError) {
  408. // If both requests for 'audio' + 'video' and 'audio' only
  409. // failed, we assume that there is some problems with user's
  410. // microphone and show corresponding dialog.
  411. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  412. } else {
  413. // If request for 'audio' + 'video' failed, but request for
  414. // 'audio' only was OK, we assume that we had problems with
  415. // camera and show corresponding dialog.
  416. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  417. }
  418. }
  419. console.log('initialized with %s local tracks', tracks.length);
  420. APP.connection = connection = con;
  421. this._createRoom(tracks);
  422. this.isDesktopSharingEnabled =
  423. JitsiMeetJS.isDesktopSharingEnabled();
  424. if(this.isDesktopSharingEnabled)
  425. APP.API.addPostisMessageListener('toggle-share-screen',
  426. () => this.toggleScreenSharing());
  427. // if user didn't give access to mic or camera or doesn't have
  428. // them at all, we disable corresponding toolbar buttons
  429. if (!tracks.find((t) => t.isAudioTrack())) {
  430. APP.UI.disableMicrophoneButton();
  431. }
  432. if (!tracks.find((t) => t.isVideoTrack())) {
  433. APP.UI.disableCameraButton();
  434. }
  435. // update list of available devices
  436. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  437. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  438. JitsiMeetJS.mediaDevices.enumerateDevices(function(devices) {
  439. // Ugly way to synchronize real device IDs with local
  440. // storage and settings menu. This is a workaround until
  441. // getConstraints() method will be implemented in browsers.
  442. if (localAudio) {
  443. localAudio._setRealDeviceIdFromDeviceList(devices);
  444. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  445. }
  446. if (localVideo) {
  447. localVideo._setRealDeviceIdFromDeviceList(devices);
  448. APP.settings.setCameraDeviceId(
  449. localVideo.getDeviceId());
  450. }
  451. setCurrentMediaDevices(devices);
  452. APP.UI.onAvailableDevicesChanged(devices);
  453. });
  454. JitsiMeetJS.mediaDevices.addEventListener(
  455. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  456. (devices) => {
  457. // Just defer callback until other event callbacks are
  458. // processed.
  459. window.setTimeout(() => {
  460. checkLocalDevicesAfterDeviceListChanged(devices)
  461. .then(() => {
  462. setCurrentMediaDevices(devices);
  463. APP.UI.onAvailableDevicesChanged(devices);
  464. });
  465. }, 0);
  466. });
  467. }
  468. if (config.iAmRecorder)
  469. this.recorder = new Recorder();
  470. // XXX The API will take care of disconnecting from the XMPP server
  471. // (and, thus, leaving the room) on unload.
  472. return new Promise((resolve, reject) => {
  473. (new ConferenceConnector(resolve, reject)).connect();
  474. });
  475. function checkAudioOutputDeviceAfterDeviceListChanged(newDevices) {
  476. if (!JitsiMeetJS.mediaDevices
  477. .isDeviceChangeAvailable('output')) {
  478. return;
  479. }
  480. var selectedAudioOutputDeviceId =
  481. APP.settings.getAudioOutputDeviceId(),
  482. availableAudioOutputDevices = newDevices.filter(d => {
  483. return d.kind === 'audiooutput';
  484. });
  485. if (selectedAudioOutputDeviceId !== 'default' &&
  486. !availableAudioOutputDevices.find(d =>
  487. d.deviceId === selectedAudioOutputDeviceId)) {
  488. APP.settings.setAudioOutputDeviceId('default');
  489. }
  490. }
  491. function checkLocalDevicesAfterDeviceListChanged(newDevices) {
  492. // Event handler can be fire before direct enumerateDevices()
  493. // call, so handle this situation here.
  494. if (!currentAudioInputDevices && !currentVideoInputDevices) {
  495. setCurrentMediaDevices(newDevices);
  496. }
  497. checkAudioOutputDeviceAfterDeviceListChanged(newDevices);
  498. let availableAudioInputDevices = newDevices.filter(
  499. d => d.kind === 'audioinput'),
  500. availableVideoInputDevices = newDevices.filter(
  501. d => d.kind === 'videoinput'),
  502. selectedAudioInputDeviceId = APP.settings.getMicDeviceId(),
  503. selectedVideoInputDeviceId =
  504. APP.settings.getCameraDeviceId(),
  505. selectedAudioInputDevice = availableAudioInputDevices.find(
  506. d => d.deviceId === selectedAudioInputDeviceId),
  507. selectedVideoInputDevice = availableVideoInputDevices.find(
  508. d => d.deviceId === selectedVideoInputDeviceId),
  509. tracksToCreate = [],
  510. micIdToUse = null,
  511. cameraIdToUse = null;
  512. // Here we handle case when no device was initially plugged, but
  513. // then it's connected OR new device was connected when previous
  514. // track has ended.
  515. if (!localAudio || localAudio.disposed || localAudio.isEnded()){
  516. if (availableAudioInputDevices.length
  517. && availableAudioInputDevices[0].label !== '') {
  518. tracksToCreate.push('audio');
  519. micIdToUse = availableAudioInputDevices[0].deviceId;
  520. } else {
  521. APP.UI.disableMicrophoneButton();
  522. }
  523. }
  524. if ((!localVideo || localVideo.disposed || localVideo.isEnded())
  525. && !self.isSharingScreen){
  526. if (availableVideoInputDevices.length
  527. && availableVideoInputDevices[0].label !== '') {
  528. tracksToCreate.push('video');
  529. cameraIdToUse = availableVideoInputDevices[0].deviceId;
  530. } else {
  531. APP.UI.disableCameraButton();
  532. }
  533. }
  534. if (localAudio && !localAudio.disposed && !localAudio.isEnded()
  535. && selectedAudioInputDevice
  536. && selectedAudioInputDeviceId !== localAudio.getDeviceId()
  537. && tracksToCreate.indexOf('audio') === -1) {
  538. tracksToCreate.push('audio');
  539. micIdToUse = selectedAudioInputDeviceId;
  540. }
  541. if (localVideo && !localVideo.disposed && !localVideo.isEnded()
  542. && selectedVideoInputDevice
  543. && selectedVideoInputDeviceId !== localVideo.getDeviceId()
  544. && tracksToCreate.indexOf('video') === -1
  545. && !self.isSharingScreen) {
  546. tracksToCreate.push('video');
  547. cameraIdToUse = selectedVideoInputDeviceId;
  548. }
  549. if (tracksToCreate.length) {
  550. return createNewTracks(
  551. tracksToCreate, cameraIdToUse, micIdToUse);
  552. } else {
  553. return Promise.resolve();
  554. }
  555. function createNewTracks(type, cameraDeviceId, micDeviceId) {
  556. let audioTrackCreationError;
  557. let videoTrackCreationError;
  558. let audioRequested = type.indexOf('audio') !== -1;
  559. let videoRequested = type.indexOf('video') !== -1;
  560. let promise;
  561. if (audioRequested && micDeviceId !== null) {
  562. if (videoRequested && cameraDeviceId !== null) {
  563. promise = createLocalTracks(
  564. type, cameraDeviceId, micDeviceId)
  565. .catch(() => {
  566. return Promise.all([
  567. createAudioTrack(false),
  568. createVideoTrack(false)]);
  569. })
  570. .then((audioTracks, videoTracks) => {
  571. if (audioTrackCreationError) {
  572. if (videoTrackCreationError) {
  573. APP.UI.showDeviceErrorDialog(
  574. audioTrackCreationError,
  575. videoTrackCreationError);
  576. } else {
  577. APP.UI.showDeviceErrorDialog(
  578. audioTrackCreationError,
  579. null);
  580. }
  581. } else if (videoTrackCreationError) {
  582. APP.UI.showDeviceErrorDialog(
  583. null,
  584. videoTrackCreationError);
  585. }
  586. return (audioTracks || [])
  587. .concat(videoTracks || []);
  588. });
  589. } else {
  590. promise = createAudioTrack();
  591. }
  592. } else if (videoRequested && cameraDeviceId !== null) {
  593. promise = createVideoTrack();
  594. } else {
  595. promise = Promise.resolve([]);
  596. }
  597. return promise
  598. .then(onTracksCreated);
  599. function createAudioTrack(showError) {
  600. return createLocalTracks(['audio'], null, micDeviceId)
  601. .catch(err => {
  602. audioTrackCreationError = err;
  603. if (showError) {
  604. APP.UI.showDeviceErrorDialog(err, null);
  605. }
  606. return [];
  607. });
  608. }
  609. function createVideoTrack(showError) {
  610. return createLocalTracks(
  611. ['video'], cameraDeviceId, null)
  612. .catch(err => {
  613. videoTrackCreationError = err;
  614. if (showError) {
  615. APP.UI.showDeviceErrorDialog(null, err);
  616. }
  617. return [];
  618. });
  619. }
  620. }
  621. function onTracksCreated(tracks) {
  622. return Promise.all((tracks || []).map(track => {
  623. if (track.isAudioTrack()) {
  624. let audioWasMuted = self.audioMuted;
  625. return self.useAudioStream(track).then(() => {
  626. console.log('switched local audio');
  627. // If we plugged-in new device (and switched to
  628. // it), but video was muted before, or we
  629. // unplugged current device and selected new
  630. // one, then mute new video track.
  631. if (audioWasMuted ||
  632. currentAudioInputDevices.length >
  633. availableAudioInputDevices.length) {
  634. muteLocalAudio(true);
  635. }
  636. });
  637. } else if (track.isVideoTrack()) {
  638. let videoWasMuted = self.videoMuted;
  639. return self.useVideoStream(track).then(() => {
  640. console.log('switched local video');
  641. // TODO: maybe make video large if we
  642. // are not in conference yet
  643. // If we plugged-in new device (and switched to
  644. // it), but video was muted before, or we
  645. // unplugged current device and selected new
  646. // one, then mute new video track.
  647. if (videoWasMuted ||
  648. (currentVideoInputDevices.length >
  649. availableVideoInputDevices.length)) {
  650. muteLocalVideo(true);
  651. }
  652. });
  653. } else {
  654. console.error("Ignored not an audio nor a "
  655. + "video track: ", track);
  656. return Promise.resolve();
  657. }
  658. }));
  659. }
  660. }
  661. });
  662. },
  663. /**
  664. * Check if id is id of the local user.
  665. * @param {string} id id to check
  666. * @returns {boolean}
  667. */
  668. isLocalId (id) {
  669. return this.localId === id;
  670. },
  671. /**
  672. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  673. * @param mute true for mute and false for unmute.
  674. */
  675. muteAudio (mute) {
  676. muteLocalAudio(mute);
  677. },
  678. /**
  679. * Returns whether local audio is muted or not.
  680. * @returns {boolean}
  681. */
  682. isLocalAudioMuted() {
  683. return this.audioMuted;
  684. },
  685. /**
  686. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  687. */
  688. toggleAudioMuted () {
  689. this.muteAudio(!this.audioMuted);
  690. },
  691. /**
  692. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  693. * @param mute true for mute and false for unmute.
  694. */
  695. muteVideo (mute) {
  696. muteLocalVideo(mute);
  697. },
  698. /**
  699. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  700. */
  701. toggleVideoMuted () {
  702. this.muteVideo(!this.videoMuted);
  703. },
  704. /**
  705. * Retrieve list of conference participants (without local user).
  706. * @returns {JitsiParticipant[]}
  707. */
  708. listMembers () {
  709. return room.getParticipants();
  710. },
  711. /**
  712. * Retrieve list of ids of conference participants (without local user).
  713. * @returns {string[]}
  714. */
  715. listMembersIds () {
  716. return room.getParticipants().map(p => p.getId());
  717. },
  718. /**
  719. * Checks whether the participant identified by id is a moderator.
  720. * @id id to search for participant
  721. * @return {boolean} whether the participant is moderator
  722. */
  723. isParticipantModerator (id) {
  724. let user = room.getParticipantById(id);
  725. return user && user.isModerator();
  726. },
  727. /**
  728. * Check if SIP is supported.
  729. * @returns {boolean}
  730. */
  731. sipGatewayEnabled () {
  732. return room.isSIPCallingSupported();
  733. },
  734. get membersCount () {
  735. return room.getParticipants().length + 1;
  736. },
  737. /**
  738. * Returns true if the callstats integration is enabled, otherwise returns
  739. * false.
  740. *
  741. * @returns true if the callstats integration is enabled, otherwise returns
  742. * false.
  743. */
  744. isCallstatsEnabled () {
  745. return room.isCallstatsEnabled();
  746. },
  747. /**
  748. * Sends the given feedback through CallStats if enabled.
  749. *
  750. * @param overallFeedback an integer between 1 and 5 indicating the
  751. * user feedback
  752. * @param detailedFeedback detailed feedback from the user. Not yet used
  753. */
  754. sendFeedback (overallFeedback, detailedFeedback) {
  755. return room.sendFeedback (overallFeedback, detailedFeedback);
  756. },
  757. // used by torture currently
  758. isJoined () {
  759. return this._room
  760. && this._room.isJoined();
  761. },
  762. getConnectionState () {
  763. return this._room
  764. && this._room.getConnectionState();
  765. },
  766. getMyUserId () {
  767. return this._room
  768. && this._room.myUserId();
  769. },
  770. /**
  771. * Indicates if recording is supported in this conference.
  772. */
  773. isRecordingSupported() {
  774. return this._room && this._room.isRecordingSupported();
  775. },
  776. /**
  777. * Returns the recording state or undefined if the room is not defined.
  778. */
  779. getRecordingState() {
  780. return (this._room) ? this._room.getRecordingState() : undefined;
  781. },
  782. /**
  783. * Will be filled with values only when config.debug is enabled.
  784. * Its used by torture to check audio levels.
  785. */
  786. audioLevelsMap: {},
  787. /**
  788. * Returns the stored audio level (stored only if config.debug is enabled)
  789. * @param id the id for the user audio level to return (the id value is
  790. * returned for the participant using getMyUserId() method)
  791. */
  792. getPeerSSRCAudioLevel (id) {
  793. return this.audioLevelsMap[id];
  794. },
  795. /**
  796. * @return {number} the number of participants in the conference with at
  797. * least one track.
  798. */
  799. getNumberOfParticipantsWithTracks() {
  800. return this._room.getParticipants()
  801. .filter((p) => p.getTracks().length > 0)
  802. .length;
  803. },
  804. /**
  805. * Returns the stats.
  806. */
  807. getStats() {
  808. return ConnectionQuality.getStats();
  809. },
  810. // end used by torture
  811. getLogs () {
  812. return room.getLogs();
  813. },
  814. /**
  815. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  816. * desire to keep room private to this instance and (2) the need of other
  817. * modules to send and receive commands to and from participants.
  818. * Eventually, this instance remains in control with respect to the
  819. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  820. * JitsiConference) is to be used in the implementation of the Command(s)
  821. * API of this instance.
  822. */
  823. commands: {
  824. /**
  825. * Known custom conference commands.
  826. */
  827. defaults: commands,
  828. /**
  829. * Receives notifications from other participants about commands aka
  830. * custom events (sent by sendCommand or sendCommandOnce methods).
  831. * @param command {String} the name of the command
  832. * @param handler {Function} handler for the command
  833. */
  834. addCommandListener () {
  835. room.addCommandListener.apply(room, arguments);
  836. },
  837. /**
  838. * Removes command.
  839. * @param name {String} the name of the command.
  840. */
  841. removeCommand () {
  842. room.removeCommand.apply(room, arguments);
  843. },
  844. /**
  845. * Sends command.
  846. * @param name {String} the name of the command.
  847. * @param values {Object} with keys and values that will be sent.
  848. */
  849. sendCommand () {
  850. room.sendCommand.apply(room, arguments);
  851. },
  852. /**
  853. * Sends command one time.
  854. * @param name {String} the name of the command.
  855. * @param values {Object} with keys and values that will be sent.
  856. */
  857. sendCommandOnce () {
  858. room.sendCommandOnce.apply(room, arguments);
  859. }
  860. },
  861. _createRoom (localTracks) {
  862. room = connection.initJitsiConference(APP.conference.roomName,
  863. this._getConferenceOptions());
  864. this.localId = room.myUserId();
  865. localTracks.forEach((track) => {
  866. if (track.isAudioTrack()) {
  867. this.useAudioStream(track);
  868. } else if (track.isVideoTrack()) {
  869. this.useVideoStream(track);
  870. } else {
  871. console.error(
  872. "Ignored not an audio nor a video track: ", track);
  873. }
  874. });
  875. roomLocker = createRoomLocker(room);
  876. this._room = room; // FIXME do not use this
  877. let email = APP.settings.getEmail();
  878. email && sendData(this.commands.defaults.EMAIL, email);
  879. let avatarUrl = APP.settings.getAvatarUrl();
  880. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  881. avatarUrl);
  882. let nick = APP.settings.getDisplayName();
  883. if (config.useNicks && !nick) {
  884. nick = APP.UI.askForNickname();
  885. APP.settings.setDisplayName(nick);
  886. }
  887. nick && room.setDisplayName(nick);
  888. this._setupListeners();
  889. },
  890. _getConferenceOptions() {
  891. let options = config;
  892. if(config.enableRecording && !config.recordingType) {
  893. options.recordingType = (config.hosts &&
  894. (typeof config.hosts.jirecon != "undefined"))?
  895. "jirecon" : "colibri";
  896. }
  897. return options;
  898. },
  899. /**
  900. * Start using provided video stream.
  901. * Stops previous video stream.
  902. * @param {JitsiLocalTrack} [stream] new stream to use or null
  903. * @returns {Promise}
  904. */
  905. useVideoStream (stream) {
  906. let promise = Promise.resolve();
  907. if (localVideo) {
  908. // this calls room.removeTrack internally
  909. // so we don't need to remove it manually
  910. promise = localVideo.dispose();
  911. }
  912. localVideo = stream;
  913. return promise.then(function () {
  914. if (stream) {
  915. return room.addTrack(stream);
  916. }
  917. }).then(() => {
  918. if (stream) {
  919. this.videoMuted = stream.isMuted();
  920. this.isSharingScreen = stream.videoType === 'desktop';
  921. APP.UI.addLocalStream(stream);
  922. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  923. } else {
  924. this.videoMuted = false;
  925. this.isSharingScreen = false;
  926. }
  927. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  928. APP.UI.updateDesktopSharingButtons();
  929. });
  930. },
  931. /**
  932. * Start using provided audio stream.
  933. * Stops previous audio stream.
  934. * @param {JitsiLocalTrack} [stream] new stream to use or null
  935. * @returns {Promise}
  936. */
  937. useAudioStream (stream) {
  938. let promise = Promise.resolve();
  939. if (localAudio) {
  940. // this calls room.removeTrack internally
  941. // so we don't need to remove it manually
  942. promise = localAudio.dispose();
  943. }
  944. localAudio = stream;
  945. return promise.then(function () {
  946. if (stream) {
  947. return room.addTrack(stream);
  948. }
  949. }).then(() => {
  950. if (stream) {
  951. this.audioMuted = stream.isMuted();
  952. APP.UI.addLocalStream(stream);
  953. } else {
  954. this.audioMuted = false;
  955. }
  956. APP.UI.enableMicrophoneButton();
  957. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  958. });
  959. },
  960. videoSwitchInProgress: false,
  961. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  962. if (this.videoSwitchInProgress) {
  963. console.warn("Switch in progress.");
  964. return;
  965. }
  966. if (!this.isDesktopSharingEnabled) {
  967. console.warn("Cannot toggle screen sharing: not supported.");
  968. return;
  969. }
  970. this.videoSwitchInProgress = true;
  971. if (shareScreen) {
  972. createLocalTracks(['desktop']).then(([stream]) => {
  973. stream.on(
  974. TrackEvents.LOCAL_TRACK_STOPPED,
  975. () => {
  976. // if stream was stopped during screensharing session
  977. // then we should switch to video
  978. // otherwise we stopped it because we already switched
  979. // to video, so nothing to do here
  980. if (this.isSharingScreen) {
  981. this.toggleScreenSharing(false);
  982. }
  983. }
  984. );
  985. return this.useVideoStream(stream);
  986. }).then(() => {
  987. this.videoSwitchInProgress = false;
  988. console.log('sharing local desktop');
  989. }).catch((err) => {
  990. this.videoSwitchInProgress = false;
  991. this.toggleScreenSharing(false);
  992. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  993. return;
  994. }
  995. console.error('failed to share local desktop', err);
  996. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  997. APP.UI.showExtensionRequiredDialog(
  998. config.desktopSharingFirefoxExtensionURL
  999. );
  1000. return;
  1001. }
  1002. // Handling:
  1003. // TrackErrors.PERMISSION_DENIED
  1004. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1005. // TrackErrors.GENERAL
  1006. // and any other
  1007. let dialogTxt;
  1008. let dialogTitle;
  1009. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1010. dialogTxt = APP.translation.generateTranslationHTML(
  1011. "dialog.screenSharingPermissionDeniedError");
  1012. dialogTitle = APP.translation.generateTranslationHTML(
  1013. "dialog.error");
  1014. } else {
  1015. dialogTxt = APP.translation.generateTranslationHTML(
  1016. "dialog.failtoinstall");
  1017. dialogTitle = APP.translation.generateTranslationHTML(
  1018. "dialog.permissionDenied");
  1019. }
  1020. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  1021. });
  1022. } else {
  1023. createLocalTracks(['video']).then(
  1024. ([stream]) => this.useVideoStream(stream)
  1025. ).then(() => {
  1026. this.videoSwitchInProgress = false;
  1027. console.log('sharing local video');
  1028. }).catch((err) => {
  1029. this.useVideoStream(null);
  1030. this.videoSwitchInProgress = false;
  1031. console.error('failed to share local video', err);
  1032. });
  1033. }
  1034. },
  1035. /**
  1036. * Setup interaction between conference and UI.
  1037. */
  1038. _setupListeners () {
  1039. // add local streams when joined to the conference
  1040. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1041. APP.UI.mucJoined();
  1042. APP.API.sendPostisMessage({
  1043. method: 'video-conference-joined',
  1044. params: {roomName: APP.conference.roomName}
  1045. });
  1046. });
  1047. room.on(
  1048. ConferenceEvents.AUTH_STATUS_CHANGED,
  1049. function (authEnabled, authLogin) {
  1050. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1051. }
  1052. );
  1053. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1054. if (user.isHidden())
  1055. return;
  1056. console.log('USER %s connnected', id, user);
  1057. APP.API.notifyUserJoined(id);
  1058. APP.UI.addUser(id, user.getDisplayName());
  1059. // check the roles for the new user and reflect them
  1060. APP.UI.updateUserRole(user);
  1061. });
  1062. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1063. console.log('USER %s LEFT', id, user);
  1064. APP.API.notifyUserLeft(id);
  1065. APP.UI.removeUser(id, user.getDisplayName());
  1066. APP.UI.onSharedVideoStop(id);
  1067. });
  1068. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1069. if (this.isLocalId(id)) {
  1070. console.info(`My role changed, new role: ${role}`);
  1071. this.isModerator = room.isModerator();
  1072. APP.UI.updateLocalRole(room.isModerator());
  1073. } else {
  1074. let user = room.getParticipantById(id);
  1075. if (user) {
  1076. APP.UI.updateUserRole(user);
  1077. }
  1078. }
  1079. });
  1080. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1081. if(!track || track.isLocal())
  1082. return;
  1083. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1084. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1085. });
  1086. APP.UI.addRemoteStream(track);
  1087. });
  1088. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1089. if(!track || track.isLocal())
  1090. return;
  1091. APP.UI.removeRemoteStream(track);
  1092. });
  1093. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1094. if(!track)
  1095. return;
  1096. const handler = (track.getType() === "audio")?
  1097. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1098. let id;
  1099. const mute = track.isMuted();
  1100. if(track.isLocal()){
  1101. id = this.localId;
  1102. if(track.getType() === "audio") {
  1103. this.audioMuted = mute;
  1104. } else {
  1105. this.videoMuted = mute;
  1106. }
  1107. } else {
  1108. id = track.getParticipantId();
  1109. }
  1110. handler(id , mute);
  1111. });
  1112. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1113. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1114. lvl = 0;
  1115. }
  1116. if(config.debug)
  1117. {
  1118. this.audioLevelsMap[id] = lvl;
  1119. if(config.debugAudioLevels)
  1120. console.log("AudioLevel:" + id + "/" + lvl);
  1121. }
  1122. APP.UI.setAudioLevel(id, lvl);
  1123. });
  1124. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1125. //FIXME
  1126. if (config.muteLocalVideoIfNotInLastN) {
  1127. // TODO mute or unmute if required
  1128. // mark video on UI
  1129. // APP.UI.markVideoMuted(true/false);
  1130. }
  1131. });
  1132. room.on(
  1133. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1134. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1135. });
  1136. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1137. APP.UI.markDominantSpeaker(id);
  1138. });
  1139. if (!interfaceConfig.filmStripOnly) {
  1140. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1141. APP.UI.markVideoInterrupted(true);
  1142. });
  1143. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1144. APP.UI.markVideoInterrupted(false);
  1145. });
  1146. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1147. let nick = getDisplayName(id);
  1148. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1149. APP.UI.addMessage(id, nick, text, ts);
  1150. });
  1151. }
  1152. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1153. APP.API.notifyDisplayNameChanged(id, displayName);
  1154. APP.UI.changeDisplayName(id, displayName);
  1155. });
  1156. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1157. console.log("Received recorder status change: ", status, error);
  1158. APP.UI.updateRecordingState(status);
  1159. });
  1160. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1161. APP.UI.updateUserStatus(id, status);
  1162. });
  1163. room.on(ConferenceEvents.KICKED, () => {
  1164. APP.UI.hideStats();
  1165. APP.UI.notifyKicked();
  1166. // FIXME close
  1167. });
  1168. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1169. APP.UI.updateDTMFSupport(isDTMFSupported);
  1170. });
  1171. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1172. if (room.isModerator()) {
  1173. let promise = roomLocker.isLocked
  1174. ? roomLocker.askToUnlock()
  1175. : roomLocker.askToLock();
  1176. promise.then(() => {
  1177. APP.UI.markRoomLocked(roomLocker.isLocked);
  1178. });
  1179. } else {
  1180. roomLocker.notifyModeratorRequired();
  1181. }
  1182. });
  1183. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1184. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1185. if (!interfaceConfig.filmStripOnly) {
  1186. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1187. APP.API.notifySendingChatMessage(message);
  1188. room.sendTextMessage(message);
  1189. });
  1190. }
  1191. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1192. ConnectionQuality.updateLocalStats(stats);
  1193. });
  1194. ConnectionQuality.addListener(
  1195. CQEvents.LOCALSTATS_UPDATED,
  1196. (percent, stats) => {
  1197. APP.UI.updateLocalStats(percent, stats);
  1198. // send local stats to other users
  1199. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  1200. {
  1201. children: ConnectionQuality.convertToMUCStats(stats),
  1202. attributes: {
  1203. xmlns: 'http://jitsi.org/jitmeet/stats'
  1204. }
  1205. });
  1206. }
  1207. );
  1208. // listen to remote stats
  1209. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  1210. (values, from) => {
  1211. ConnectionQuality.updateRemoteStats(from, values);
  1212. });
  1213. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1214. (id, percent, stats) => {
  1215. APP.UI.updateRemoteStats(id, percent, stats);
  1216. });
  1217. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1218. APP.UI.initEtherpad(value);
  1219. });
  1220. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1221. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1222. APP.UI.setUserEmail(from, data.value);
  1223. });
  1224. APP.UI.addListener(UIEvents.AVATAR_URL_CHANGED, changeLocalAvatarUrl);
  1225. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1226. (data, from) => {
  1227. APP.UI.setUserAvatarUrl(from, data.value);
  1228. });
  1229. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1230. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1231. (startAudioMuted, startVideoMuted) => {
  1232. room.setStartMutedPolicy({
  1233. audio: startAudioMuted,
  1234. video: startVideoMuted
  1235. });
  1236. }
  1237. );
  1238. room.on(
  1239. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1240. ({ audio, video }) => {
  1241. APP.UI.onStartMutedChanged(audio, video);
  1242. }
  1243. );
  1244. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1245. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1246. && APP.UI.notifyInitiallyMuted();
  1247. });
  1248. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1249. APP.UI.inviteParticipants(
  1250. roomUrl,
  1251. APP.conference.roomName,
  1252. roomLocker.password,
  1253. APP.settings.getDisplayName()
  1254. );
  1255. });
  1256. room.on(
  1257. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1258. APP.UI.updateDevicesAvailability(id, devices);
  1259. }
  1260. );
  1261. // call hangup
  1262. APP.UI.addListener(UIEvents.HANGUP, () => {
  1263. hangup(true);
  1264. });
  1265. // logout
  1266. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1267. AuthHandler.logout(room).then(function (url) {
  1268. if (url) {
  1269. window.location.href = url;
  1270. } else {
  1271. hangup(true);
  1272. }
  1273. });
  1274. });
  1275. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1276. room.dial(sipNumber);
  1277. });
  1278. // Starts or stops the recording for the conference.
  1279. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1280. room.toggleRecording(options);
  1281. });
  1282. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1283. room.setSubject(topic);
  1284. });
  1285. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1286. APP.UI.setSubject(subject);
  1287. });
  1288. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1289. room.kickParticipant(id);
  1290. });
  1291. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1292. room.muteParticipant(id);
  1293. });
  1294. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1295. AuthHandler.authenticate(room);
  1296. });
  1297. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1298. room.selectParticipant(id);
  1299. });
  1300. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1301. var smallVideoId = smallVideo.getId();
  1302. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1303. && !APP.conference.isLocalId(smallVideoId))
  1304. if (isPinned)
  1305. room.pinParticipant(smallVideoId);
  1306. // When the library starts supporting multiple pins we would
  1307. // pass the isPinned parameter together with the identifier,
  1308. // but currently we send null to indicate that we unpin the
  1309. // last pinned.
  1310. else
  1311. room.pinParticipant(null);
  1312. });
  1313. APP.UI.addListener(
  1314. UIEvents.VIDEO_DEVICE_CHANGED,
  1315. (cameraDeviceId) => {
  1316. createLocalTracks(['video'])
  1317. .then(([stream]) => {
  1318. this.useVideoStream(stream);
  1319. console.log('switched local video device');
  1320. APP.settings.setCameraDeviceId(cameraDeviceId);
  1321. })
  1322. .catch((err) => {
  1323. APP.UI.showDeviceErrorDialog(null, err);
  1324. APP.UI.setSelectedCameraFromSettings();
  1325. });
  1326. }
  1327. );
  1328. APP.UI.addListener(
  1329. UIEvents.AUDIO_DEVICE_CHANGED,
  1330. (micDeviceId) => {
  1331. createLocalTracks(['audio'])
  1332. .then(([stream]) => {
  1333. this.useAudioStream(stream);
  1334. console.log('switched local audio device');
  1335. APP.settings.setMicDeviceId(micDeviceId);
  1336. })
  1337. .catch((err) => {
  1338. APP.UI.showDeviceErrorDialog(err, null);
  1339. APP.UI.setSelectedMicFromSettings();
  1340. });
  1341. }
  1342. );
  1343. APP.UI.addListener(
  1344. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1345. (audioOutputDeviceId) => {
  1346. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1347. .then(() => console.log('changed audio output device'))
  1348. .catch((err) => {
  1349. console.warn('Failed to change audio output device. ' +
  1350. 'Default or previously set audio output device ' +
  1351. 'will be used instead.', err);
  1352. APP.UI.setSelectedAudioOutputFromSettings();
  1353. });
  1354. }
  1355. );
  1356. APP.UI.addListener(
  1357. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1358. );
  1359. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1360. (url, state, time, isMuted, volume) => {
  1361. // send start and stop commands once, and remove any updates
  1362. // that had left
  1363. if (state === 'stop' || state === 'start' || state === 'playing') {
  1364. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1365. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1366. value: url,
  1367. attributes: {
  1368. state: state,
  1369. time: time,
  1370. muted: isMuted,
  1371. volume: volume
  1372. }
  1373. });
  1374. }
  1375. else {
  1376. // in case of paused, in order to allow late users to join
  1377. // paused
  1378. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1379. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1380. value: url,
  1381. attributes: {
  1382. state: state,
  1383. time: time,
  1384. muted: isMuted,
  1385. volume: volume
  1386. }
  1387. });
  1388. }
  1389. });
  1390. room.addCommandListener(
  1391. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1392. if (attributes.state === 'stop') {
  1393. APP.UI.onSharedVideoStop(id, attributes);
  1394. }
  1395. else if (attributes.state === 'start') {
  1396. APP.UI.onSharedVideoStart(id, value, attributes);
  1397. }
  1398. else if (attributes.state === 'playing'
  1399. || attributes.state === 'pause') {
  1400. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1401. }
  1402. });
  1403. },
  1404. /**
  1405. * Adss any room listener.
  1406. * @param eventName one of the ConferenceEvents
  1407. * @param callBack the function to be called when the event occurs
  1408. */
  1409. addConferenceListener(eventName, callBack) {
  1410. room.on(eventName, callBack);
  1411. }
  1412. };