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

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