Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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