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

conference.js 85KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  5. import AuthHandler from './modules/UI/authentication/AuthHandler';
  6. import Recorder from './modules/recorder/Recorder';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import { reload, reportError } from './modules/util/helpers';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import analytics from './modules/analytics/analytics';
  13. import EventEmitter from "events";
  14. import { getLocationContextRoot } from './react/features/app';
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. EMAIL_COMMAND,
  22. lockStateChanged
  23. } from './react/features/base/conference';
  24. import { updateDeviceList } from './react/features/base/devices';
  25. import {
  26. isFatalJitsiConnectionError
  27. } from './react/features/base/lib-jitsi-meet';
  28. import { setVideoAvailable } from './react/features/base/media';
  29. import {
  30. localParticipantRoleChanged,
  31. MAX_DISPLAY_NAME_LENGTH,
  32. participantJoined,
  33. participantLeft,
  34. participantRoleChanged,
  35. participantUpdated
  36. } from './react/features/base/participants';
  37. import {
  38. replaceLocalTrack,
  39. trackAdded,
  40. trackRemoved
  41. } from './react/features/base/tracks';
  42. import { showDesktopPicker } from './react/features/desktop-picker';
  43. import {
  44. mediaPermissionPromptVisibilityChanged,
  45. suspendDetected
  46. } from './react/features/overlay';
  47. import { showDesktopSharingButton } from './react/features/toolbox';
  48. const ConnectionEvents = JitsiMeetJS.events.connection;
  49. const ConnectionErrors = JitsiMeetJS.errors.connection;
  50. const ConferenceEvents = JitsiMeetJS.events.conference;
  51. const ConferenceErrors = JitsiMeetJS.errors.conference;
  52. const TrackEvents = JitsiMeetJS.events.track;
  53. const TrackErrors = JitsiMeetJS.errors.track;
  54. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  55. const eventEmitter = new EventEmitter();
  56. let room;
  57. let connection;
  58. let localAudio, localVideo;
  59. let initialAudioMutedState = false, initialVideoMutedState = false;
  60. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  61. /*
  62. * Logic to open a desktop picker put on the window global for
  63. * lib-jitsi-meet to detect and invoke
  64. */
  65. window.JitsiMeetScreenObtainer = {
  66. openDesktopPicker(options, onSourceChoose) {
  67. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  68. }
  69. };
  70. /**
  71. * Known custom conference commands.
  72. */
  73. const commands = {
  74. AVATAR_ID: AVATAR_ID_COMMAND,
  75. AVATAR_URL: AVATAR_URL_COMMAND,
  76. CUSTOM_ROLE: "custom-role",
  77. EMAIL: EMAIL_COMMAND,
  78. ETHERPAD: "etherpad",
  79. SHARED_VIDEO: "shared-video"
  80. };
  81. /**
  82. * Open Connection. When authentication failed it shows auth dialog.
  83. * @param roomName the room name to use
  84. * @returns Promise<JitsiConnection>
  85. */
  86. function connect(roomName) {
  87. return openConnection({retry: true, roomName: roomName})
  88. .catch(function (err) {
  89. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  90. APP.UI.notifyTokenAuthFailed();
  91. } else {
  92. APP.UI.notifyConnectionFailed(err);
  93. }
  94. throw err;
  95. });
  96. }
  97. /**
  98. * Share data to other users.
  99. * @param command the command
  100. * @param {string} value new value
  101. */
  102. function sendData(command, value) {
  103. if(!room) {
  104. return;
  105. }
  106. room.removeCommand(command);
  107. room.sendCommand(command, {value: value});
  108. }
  109. /**
  110. * Sets up initially the properties of the local participant - email, avatarID,
  111. * avatarURL, displayName, etc.
  112. */
  113. function _setupLocalParticipantProperties() {
  114. const email = APP.settings.getEmail();
  115. email && sendData(commands.EMAIL, email);
  116. const avatarUrl = APP.settings.getAvatarUrl();
  117. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  118. if (!email && !avatarUrl) {
  119. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  120. }
  121. let nick = APP.settings.getDisplayName();
  122. if (config.useNicks && !nick) {
  123. nick = APP.UI.askForNickname();
  124. APP.settings.setDisplayName(nick);
  125. }
  126. nick && room.setDisplayName(nick);
  127. }
  128. /**
  129. * Get user nickname by user id.
  130. * @param {string} id user id
  131. * @returns {string?} user nickname or undefined if user is unknown.
  132. */
  133. function getDisplayName(id) {
  134. if (APP.conference.isLocalId(id)) {
  135. return APP.settings.getDisplayName();
  136. }
  137. let participant = room.getParticipantById(id);
  138. if (participant && participant.getDisplayName()) {
  139. return participant.getDisplayName();
  140. }
  141. }
  142. /**
  143. * Mute or unmute local audio stream if it exists.
  144. * @param {boolean} muted - if audio stream should be muted or unmuted.
  145. * @param {boolean} userInteraction - indicates if this local audio mute was a
  146. * result of user interaction
  147. */
  148. function muteLocalAudio(muted) {
  149. muteLocalMedia(localAudio, muted, 'Audio');
  150. }
  151. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  152. if (!localMedia) {
  153. return;
  154. }
  155. const method = muted ? 'mute' : 'unmute';
  156. localMedia[method]().catch(reason => {
  157. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  158. });
  159. }
  160. /**
  161. * Mute or unmute local video stream if it exists.
  162. * @param {boolean} muted if video stream should be muted or unmuted.
  163. */
  164. function muteLocalVideo(muted) {
  165. muteLocalMedia(localVideo, muted, 'Video');
  166. }
  167. /**
  168. * Check if the welcome page is enabled and redirects to it.
  169. * If requested show a thank you dialog before that.
  170. * If we have a close page enabled, redirect to it without
  171. * showing any other dialog.
  172. *
  173. * @param {object} options used to decide which particular close page to show
  174. * or if close page is disabled, whether we should show the thankyou dialog
  175. * @param {boolean} options.thankYouDialogVisible - whether we should
  176. * show thank you dialog
  177. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  178. */
  179. function maybeRedirectToWelcomePage(options) {
  180. // if close page is enabled redirect to it, without further action
  181. if (config.enableClosePage) {
  182. const { isGuest } = APP.store.getState()['features/jwt'];
  183. // save whether current user is guest or not, before navigating
  184. // to close page
  185. window.sessionStorage.setItem('guest', isGuest);
  186. assignWindowLocationPathname('static/'
  187. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  188. return;
  189. }
  190. // else: show thankYou dialog only if there is no feedback
  191. if (options.thankYouDialogVisible)
  192. APP.UI.messageHandler.openMessageDialog(
  193. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  194. // if Welcome page is enabled redirect to welcome page after 3 sec.
  195. if (config.enableWelcomePage) {
  196. setTimeout(() => {
  197. APP.settings.setWelcomePageEnabled(true);
  198. assignWindowLocationPathname('./');
  199. }, 3000);
  200. }
  201. }
  202. /**
  203. * Assigns a specific pathname to window.location.pathname taking into account
  204. * the context root of the Web app.
  205. *
  206. * @param {string} pathname - The pathname to assign to
  207. * window.location.pathname. If the specified pathname is relative, the context
  208. * root of the Web app will be prepended to the specified pathname before
  209. * assigning it to window.location.pathname.
  210. * @return {void}
  211. */
  212. function assignWindowLocationPathname(pathname) {
  213. const windowLocation = window.location;
  214. if (!pathname.startsWith('/')) {
  215. // A pathname equal to ./ specifies the current directory. It will be
  216. // fine but pointless to include it because contextRoot is the current
  217. // directory.
  218. pathname.startsWith('./') && (pathname = pathname.substring(2));
  219. pathname = getLocationContextRoot(windowLocation) + pathname;
  220. }
  221. windowLocation.pathname = pathname;
  222. }
  223. /**
  224. * Create local tracks of specified types.
  225. * @param {Object} options
  226. * @param {string[]} options.devices - required track types
  227. * ('audio', 'video' etc.)
  228. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  229. * undefined - one from settings will be used
  230. * @param {string|null} (options.micDeviceId) - microphone device id, if
  231. * undefined - one from settings will be used
  232. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  233. * for gUM permission prompt
  234. * @returns {Promise<JitsiLocalTrack[]>}
  235. */
  236. function createLocalTracks(options, checkForPermissionPrompt) {
  237. options || (options = {});
  238. return JitsiMeetJS
  239. .createLocalTracks({
  240. // copy array to avoid mutations inside library
  241. devices: options.devices.slice(0),
  242. desktopSharingSources: options.desktopSharingSources,
  243. resolution: config.resolution,
  244. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  245. options.cameraDeviceId === null
  246. ? APP.settings.getCameraDeviceId()
  247. : options.cameraDeviceId,
  248. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  249. options.micDeviceId === null
  250. ? APP.settings.getMicDeviceId()
  251. : options.micDeviceId,
  252. // adds any ff fake device settings if any
  253. firefox_fake_device: config.firefox_fake_device,
  254. desktopSharingExtensionExternalInstallation:
  255. options.desktopSharingExtensionExternalInstallation
  256. }, checkForPermissionPrompt).then( (tracks) => {
  257. tracks.forEach((track) => {
  258. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  259. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  260. });
  261. return tracks;
  262. }).catch(function (err) {
  263. logger.error(
  264. 'failed to create local tracks', options.devices, err);
  265. return Promise.reject(err);
  266. });
  267. }
  268. class ConferenceConnector {
  269. constructor(resolve, reject) {
  270. this._resolve = resolve;
  271. this._reject = reject;
  272. this.reconnectTimeout = null;
  273. room.on(ConferenceEvents.CONFERENCE_JOINED,
  274. this._handleConferenceJoined.bind(this));
  275. room.on(ConferenceEvents.CONFERENCE_FAILED,
  276. this._onConferenceFailed.bind(this));
  277. room.on(ConferenceEvents.CONFERENCE_ERROR,
  278. this._onConferenceError.bind(this));
  279. }
  280. _handleConferenceFailed(err) {
  281. this._unsubscribe();
  282. this._reject(err);
  283. }
  284. _onConferenceFailed(err, ...params) {
  285. APP.store.dispatch(conferenceFailed(room, err, ...params));
  286. logger.error('CONFERENCE FAILED:', err, ...params);
  287. switch (err) {
  288. case ConferenceErrors.CONNECTION_ERROR:
  289. {
  290. let [msg] = params;
  291. APP.UI.notifyConnectionFailed(msg);
  292. }
  293. break;
  294. case ConferenceErrors.NOT_ALLOWED_ERROR:
  295. {
  296. // let's show some auth not allowed page
  297. assignWindowLocationPathname('static/authError.html');
  298. }
  299. break;
  300. // not enough rights to create conference
  301. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  302. // Schedule reconnect to check if someone else created the room.
  303. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  304. const { password }
  305. = APP.store.getState()['features/base/conference'];
  306. AuthHandler.requireAuth(room, password);
  307. }
  308. break;
  309. case ConferenceErrors.RESERVATION_ERROR:
  310. {
  311. let [code, msg] = params;
  312. APP.UI.notifyReservationError(code, msg);
  313. }
  314. break;
  315. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  316. APP.UI.notifyGracefulShutdown();
  317. break;
  318. case ConferenceErrors.JINGLE_FATAL_ERROR:
  319. APP.UI.notifyInternalError();
  320. break;
  321. case ConferenceErrors.CONFERENCE_DESTROYED:
  322. {
  323. let [reason] = params;
  324. APP.UI.hideStats();
  325. APP.UI.notifyConferenceDestroyed(reason);
  326. }
  327. break;
  328. // FIXME FOCUS_DISCONNECTED is confusing event name.
  329. // What really happens there is that the library is not ready yet,
  330. // because Jicofo is not available, but it is going to give
  331. // it another try.
  332. case ConferenceErrors.FOCUS_DISCONNECTED:
  333. {
  334. let [focus, retrySec] = params;
  335. APP.UI.notifyFocusDisconnected(focus, retrySec);
  336. }
  337. break;
  338. case ConferenceErrors.FOCUS_LEFT:
  339. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  340. // FIXME the conference should be stopped by the library and not by
  341. // the app. Both the errors above are unrecoverable from the library
  342. // perspective.
  343. room.leave().then(() => connection.disconnect());
  344. break;
  345. case ConferenceErrors.CONFERENCE_MAX_USERS:
  346. connection.disconnect();
  347. APP.UI.notifyMaxUsersLimitReached();
  348. break;
  349. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  350. reload();
  351. break;
  352. default:
  353. this._handleConferenceFailed(err, ...params);
  354. }
  355. }
  356. _onConferenceError(err, ...params) {
  357. logger.error('CONFERENCE Error:', err, params);
  358. switch (err) {
  359. case ConferenceErrors.CHAT_ERROR:
  360. {
  361. let [code, msg] = params;
  362. APP.UI.showChatError(code, msg);
  363. }
  364. break;
  365. default:
  366. logger.error("Unknown error.", err);
  367. }
  368. }
  369. _unsubscribe() {
  370. room.off(
  371. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  372. room.off(
  373. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  374. if (this.reconnectTimeout !== null) {
  375. clearTimeout(this.reconnectTimeout);
  376. }
  377. AuthHandler.closeAuth();
  378. }
  379. _handleConferenceJoined() {
  380. this._unsubscribe();
  381. this._resolve();
  382. }
  383. connect() {
  384. room.join();
  385. }
  386. }
  387. /**
  388. * Disconnects the connection.
  389. * @returns resolved Promise. We need this in order to make the Promise.all
  390. * call in hangup() to resolve when all operations are finished.
  391. */
  392. function disconnect() {
  393. connection.disconnect();
  394. APP.API.notifyConferenceLeft(APP.conference.roomName);
  395. return Promise.resolve();
  396. }
  397. /**
  398. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  399. *
  400. * @param {JitsiMeetJS.connection.error} error - The reported error.
  401. * @returns {void}
  402. * @private
  403. */
  404. function _connectionFailedHandler(error) {
  405. if (isFatalJitsiConnectionError(error)) {
  406. APP.connection.removeEventListener(
  407. ConnectionEvents.CONNECTION_FAILED,
  408. _connectionFailedHandler);
  409. if (room)
  410. room.leave();
  411. }
  412. }
  413. export default {
  414. isModerator: false,
  415. audioMuted: false,
  416. videoMuted: false,
  417. isSharingScreen: false,
  418. /**
  419. * Indicates if the desktop sharing functionality has been enabled.
  420. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  421. * as well as the status returned by
  422. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  423. * either if the desktop sharing is not supported by the current browser
  424. * or if it was disabled through lib-jitsi-meet specific options (check
  425. * config.js for listed options).
  426. */
  427. isDesktopSharingEnabled: false,
  428. /**
  429. * Set to <tt>true</tt> if the desktop sharing functionality has been
  430. * explicitly disabled in the config.
  431. */
  432. isDesktopSharingDisabledByConfig: false,
  433. /**
  434. * The text displayed when the desktop sharing button is disabled through
  435. * the config. The value is set through
  436. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  437. */
  438. desktopSharingDisabledTooltip: null,
  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. * Creates local media tracks and connects to a room. Will show error
  449. * dialogs in case accessing the local microphone and/or camera failed. Will
  450. * show guidance overlay for users on how to give access to camera and/or
  451. * microphone,
  452. * @param {string} roomName
  453. * @param {object} options
  454. * @param {boolean} options.startScreenSharing - if <tt>true</tt> should
  455. * start with screensharing instead of camera video.
  456. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  457. */
  458. createInitialLocalTracksAndConnect(roomName, options = {}) {
  459. let audioAndVideoError,
  460. audioOnlyError,
  461. screenSharingError,
  462. videoOnlyError;
  463. JitsiMeetJS.mediaDevices.addEventListener(
  464. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  465. browser =>
  466. APP.store.dispatch(
  467. mediaPermissionPromptVisibilityChanged(true, browser))
  468. );
  469. // First try to retrieve both audio and video.
  470. let tryCreateLocalTracks;
  471. // FIXME the logic about trying to go audio only on error is duplicated
  472. if (options.startScreenSharing) {
  473. tryCreateLocalTracks = this._createDesktopTrack()
  474. .then(desktopStream => {
  475. return createLocalTracks({ devices: ['audio'] }, true)
  476. .then(([audioStream]) => {
  477. return [desktopStream, audioStream];
  478. })
  479. .catch(error => {
  480. audioOnlyError = error;
  481. return [desktopStream];
  482. });
  483. }).catch(error => {
  484. logger.error('Failed to obtain desktop stream', error);
  485. screenSharingError = error;
  486. return createLocalTracks({ devices: ['audio'] }, true);
  487. }).catch(error => {
  488. audioOnlyError = error;
  489. return [];
  490. });
  491. } else {
  492. tryCreateLocalTracks = createLocalTracks(
  493. {devices: ['audio', 'video']}, true)
  494. .catch(err => {
  495. // If failed then try to retrieve only audio.
  496. audioAndVideoError = err;
  497. return createLocalTracks({devices: ['audio']}, true);
  498. })
  499. .catch(err => {
  500. audioOnlyError = err;
  501. // Try video only...
  502. return createLocalTracks({devices: ['video']}, true);
  503. })
  504. .catch(err => {
  505. videoOnlyError = err;
  506. return [];
  507. });
  508. }
  509. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  510. .then(([tracks, con]) => {
  511. APP.store.dispatch(
  512. mediaPermissionPromptVisibilityChanged(false));
  513. // FIXME If there will be microphone error it will cover any
  514. // screensharing dialog, but it's still better than in
  515. // the reverse order where the screensharing dialog will
  516. // sometimes be closing the microphone alert ($.prompt.close();
  517. // is called). Need to figure out dialogs chaining to fix that.
  518. if (screenSharingError) {
  519. this._handleScreenSharingError(screenSharingError);
  520. }
  521. if (audioAndVideoError || audioOnlyError) {
  522. if (audioOnlyError || videoOnlyError) {
  523. // If both requests for 'audio' + 'video' and 'audio'
  524. // only failed, we assume that there are some problems
  525. // with user's microphone and show corresponding dialog.
  526. APP.UI.showDeviceErrorDialog(
  527. audioOnlyError, videoOnlyError);
  528. } else {
  529. // If request for 'audio' + 'video' failed, but request
  530. // for 'audio' only was OK, we assume that we had
  531. // problems with camera and show corresponding dialog.
  532. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  533. }
  534. }
  535. return [tracks, con];
  536. });
  537. },
  538. /**
  539. * Open new connection and join to the conference.
  540. * @param {object} options
  541. * @param {string} roomName name of the conference
  542. * @returns {Promise}
  543. */
  544. init(options) {
  545. this.roomName = options.roomName;
  546. // attaches global error handler, if there is already one, respect it
  547. if(JitsiMeetJS.getGlobalOnErrorHandler){
  548. var oldOnErrorHandler = window.onerror;
  549. window.onerror = function (message, source, lineno, colno, error) {
  550. JitsiMeetJS.getGlobalOnErrorHandler(
  551. message, source, lineno, colno, error);
  552. if(oldOnErrorHandler)
  553. oldOnErrorHandler(message, source, lineno, colno, error);
  554. };
  555. var oldOnUnhandledRejection = window.onunhandledrejection;
  556. window.onunhandledrejection = function(event) {
  557. JitsiMeetJS.getGlobalOnErrorHandler(
  558. null, null, null, null, event.reason);
  559. if(oldOnUnhandledRejection)
  560. oldOnUnhandledRejection(event);
  561. };
  562. }
  563. return JitsiMeetJS.init(
  564. Object.assign(
  565. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  566. ).then(() => {
  567. analytics.init();
  568. return this.createInitialLocalTracksAndConnect(
  569. options.roomName, {
  570. startScreenSharing: config.startScreenSharing
  571. });
  572. }).then(([tracks, con]) => {
  573. tracks.forEach(track => {
  574. if((track.isAudioTrack() && initialAudioMutedState)
  575. || (track.isVideoTrack() && initialVideoMutedState)) {
  576. track.mute();
  577. }
  578. });
  579. logger.log('initialized with %s local tracks', tracks.length);
  580. con.addEventListener(
  581. ConnectionEvents.CONNECTION_FAILED,
  582. _connectionFailedHandler);
  583. APP.connection = connection = con;
  584. // Desktop sharing related stuff:
  585. this.isDesktopSharingDisabledByConfig
  586. = config.disableDesktopSharing;
  587. this.isDesktopSharingEnabled
  588. = !this.isDesktopSharingDisabledByConfig
  589. && JitsiMeetJS.isDesktopSharingEnabled();
  590. this.desktopSharingDisabledTooltip
  591. = interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP;
  592. eventEmitter.emit(
  593. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  594. this.isDesktopSharingEnabled);
  595. APP.store.dispatch(showDesktopSharingButton());
  596. this._createRoom(tracks);
  597. APP.remoteControl.init();
  598. if (UIUtil.isButtonEnabled('contacts')
  599. && !interfaceConfig.filmStripOnly) {
  600. APP.UI.ContactList = new ContactList(room);
  601. }
  602. // if user didn't give access to mic or camera or doesn't have
  603. // them at all, we disable corresponding toolbar buttons
  604. if (!tracks.find((t) => t.isAudioTrack())) {
  605. APP.UI.setMicrophoneButtonEnabled(false);
  606. }
  607. if (!tracks.find((t) => t.isVideoTrack())) {
  608. // Instead of disabling the button we want to show button
  609. // muted, so that the user can have the opportunity to add
  610. // the video later on, even if joined without it.
  611. this.videoMuted = true;
  612. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  613. // FIXME this is a workaround for the situation where
  614. // both audio and video permissions are rejected initially
  615. // and the callback from _initDeviceList will never be
  616. // executed (GUM not initialized - check lib-jitsi-meet).
  617. // The goal here is to disable the video icon in case no
  618. // video permissions were granted.
  619. this.updateVideoIconEnabled();
  620. }
  621. this._initDeviceList();
  622. if (config.iAmRecorder)
  623. this.recorder = new Recorder();
  624. // XXX The API will take care of disconnecting from the XMPP
  625. // server (and, thus, leaving the room) on unload.
  626. return new Promise((resolve, reject) => {
  627. (new ConferenceConnector(resolve, reject)).connect();
  628. });
  629. });
  630. },
  631. /**
  632. * Check if id is id of the local user.
  633. * @param {string} id id to check
  634. * @returns {boolean}
  635. */
  636. isLocalId(id) {
  637. return this.getMyUserId() === id;
  638. },
  639. /**
  640. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  641. * @param mute true for mute and false for unmute.
  642. */
  643. muteAudio(mute) {
  644. muteLocalAudio(mute);
  645. },
  646. /**
  647. * Returns whether local audio is muted or not.
  648. * @returns {boolean}
  649. */
  650. isLocalAudioMuted() {
  651. return this.audioMuted;
  652. },
  653. /**
  654. * Simulates toolbar button click for audio mute. Used by shortcuts
  655. * and API.
  656. * @param {boolean} force - If the track is not created, the operation
  657. * will be executed after the track is created. Otherwise the operation
  658. * will be ignored.
  659. */
  660. toggleAudioMuted(force = false) {
  661. if(!localAudio && force) {
  662. initialAudioMutedState = !initialAudioMutedState;
  663. return;
  664. }
  665. this.muteAudio(!this.audioMuted);
  666. },
  667. /**
  668. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  669. * @param mute true for mute and false for unmute.
  670. */
  671. muteVideo(mute) {
  672. muteLocalVideo(mute);
  673. },
  674. /**
  675. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  676. * @param {boolean} force - If the track is not created, the operation
  677. * will be executed after the track is created. Otherwise the operation
  678. * will be ignored.
  679. */
  680. toggleVideoMuted(force = false) {
  681. if(!localVideo && force) {
  682. initialVideoMutedState = !initialVideoMutedState;
  683. return;
  684. }
  685. this.muteVideo(!this.videoMuted);
  686. },
  687. /**
  688. * Retrieve list of conference participants (without local user).
  689. * @returns {JitsiParticipant[]}
  690. */
  691. listMembers() {
  692. return room.getParticipants();
  693. },
  694. /**
  695. * Retrieve list of ids of conference participants (without local user).
  696. * @returns {string[]}
  697. */
  698. listMembersIds() {
  699. return room.getParticipants().map(p => p.getId());
  700. },
  701. /**
  702. * Checks whether the participant identified by id is a moderator.
  703. * @id id to search for participant
  704. * @return {boolean} whether the participant is moderator
  705. */
  706. isParticipantModerator(id) {
  707. let user = room.getParticipantById(id);
  708. return user && user.isModerator();
  709. },
  710. /**
  711. * Check if SIP is supported.
  712. * @returns {boolean}
  713. */
  714. sipGatewayEnabled() {
  715. return room.isSIPCallingSupported();
  716. },
  717. get membersCount() {
  718. return room.getParticipants().length + 1;
  719. },
  720. /**
  721. * Returns true if the callstats integration is enabled, otherwise returns
  722. * false.
  723. *
  724. * @returns true if the callstats integration is enabled, otherwise returns
  725. * false.
  726. */
  727. isCallstatsEnabled() {
  728. return room && room.isCallstatsEnabled();
  729. },
  730. /**
  731. * Sends the given feedback through CallStats if enabled.
  732. *
  733. * @param overallFeedback an integer between 1 and 5 indicating the
  734. * user feedback
  735. * @param detailedFeedback detailed feedback from the user. Not yet used
  736. */
  737. sendFeedback(overallFeedback, detailedFeedback) {
  738. return room.sendFeedback (overallFeedback, detailedFeedback);
  739. },
  740. /**
  741. * Get speaker stats that track total dominant speaker time.
  742. *
  743. * @returns {object} A hash with keys being user ids and values being the
  744. * library's SpeakerStats model used for calculating time as dominant
  745. * speaker.
  746. */
  747. getSpeakerStats() {
  748. return room.getSpeakerStats();
  749. },
  750. /**
  751. * Returns the connection times stored in the library.
  752. */
  753. getConnectionTimes() {
  754. return this._room.getConnectionTimes();
  755. },
  756. // used by torture currently
  757. isJoined() {
  758. return this._room
  759. && this._room.isJoined();
  760. },
  761. getConnectionState() {
  762. return this._room
  763. && this._room.getConnectionState();
  764. },
  765. /**
  766. * Obtains current P2P ICE connection state.
  767. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  768. * P2P connection
  769. */
  770. getP2PConnectionState() {
  771. return this._room
  772. && this._room.getP2PConnectionState();
  773. },
  774. /**
  775. * Starts P2P (for tests only)
  776. * @private
  777. */
  778. _startP2P() {
  779. try {
  780. this._room && this._room.startP2PSession();
  781. } catch (error) {
  782. logger.error("Start P2P failed", error);
  783. throw error;
  784. }
  785. },
  786. /**
  787. * Stops P2P (for tests only)
  788. * @private
  789. */
  790. _stopP2P() {
  791. try {
  792. this._room && this._room.stopP2PSession();
  793. } catch (error) {
  794. logger.error("Stop P2P failed", error);
  795. throw error;
  796. }
  797. },
  798. /**
  799. * Checks whether or not our connection is currently in interrupted and
  800. * reconnect attempts are in progress.
  801. *
  802. * @returns {boolean} true if the connection is in interrupted state or
  803. * false otherwise.
  804. */
  805. isConnectionInterrupted() {
  806. return this._room.isConnectionInterrupted();
  807. },
  808. /**
  809. * Finds JitsiParticipant for given id.
  810. *
  811. * @param {string} id participant's identifier(MUC nickname).
  812. *
  813. * @returns {JitsiParticipant|null} participant instance for given id or
  814. * null if not found.
  815. */
  816. getParticipantById(id) {
  817. return room ? room.getParticipantById(id) : null;
  818. },
  819. /**
  820. * Get participant connection status for the participant.
  821. *
  822. * @param {string} id participant's identifier(MUC nickname)
  823. *
  824. * @returns {ParticipantConnectionStatus|null} the status of the participant
  825. * or null if no such participant is found or participant is the local user.
  826. */
  827. getParticipantConnectionStatus(id) {
  828. let participant = this.getParticipantById(id);
  829. return participant ? participant.getConnectionStatus() : null;
  830. },
  831. /**
  832. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  833. * the given <tt>id</tt>.
  834. *
  835. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  836. *
  837. * @return {string} the participant's display name or the default string if
  838. * absent.
  839. */
  840. getParticipantDisplayName(id) {
  841. let displayName = getDisplayName(id);
  842. if (displayName) {
  843. return displayName;
  844. } else {
  845. if (APP.conference.isLocalId(id)) {
  846. return APP.translation.generateTranslationHTML(
  847. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  848. } else {
  849. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  850. }
  851. }
  852. },
  853. getMyUserId() {
  854. return this._room
  855. && this._room.myUserId();
  856. },
  857. /**
  858. * Indicates if recording is supported in this conference.
  859. */
  860. isRecordingSupported() {
  861. return this._room && this._room.isRecordingSupported();
  862. },
  863. /**
  864. * Returns the recording state or undefined if the room is not defined.
  865. */
  866. getRecordingState() {
  867. return (this._room) ? this._room.getRecordingState() : undefined;
  868. },
  869. /**
  870. * Will be filled with values only when config.debug is enabled.
  871. * Its used by torture to check audio levels.
  872. */
  873. audioLevelsMap: {},
  874. /**
  875. * Returns the stored audio level (stored only if config.debug is enabled)
  876. * @param id the id for the user audio level to return (the id value is
  877. * returned for the participant using getMyUserId() method)
  878. */
  879. getPeerSSRCAudioLevel(id) {
  880. return this.audioLevelsMap[id];
  881. },
  882. /**
  883. * @return {number} the number of participants in the conference with at
  884. * least one track.
  885. */
  886. getNumberOfParticipantsWithTracks() {
  887. return this._room.getParticipants()
  888. .filter((p) => p.getTracks().length > 0)
  889. .length;
  890. },
  891. /**
  892. * Returns the stats.
  893. */
  894. getStats() {
  895. return room.connectionQuality.getStats();
  896. },
  897. // end used by torture
  898. getLogs() {
  899. return room.getLogs();
  900. },
  901. /**
  902. * Download logs, a function that can be called from console while
  903. * debugging.
  904. * @param filename (optional) specify target filename
  905. */
  906. saveLogs(filename = 'meetlog.json') {
  907. // this can be called from console and will not have reference to this
  908. // that's why we reference the global var
  909. let logs = APP.conference.getLogs();
  910. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  911. let elem = document.createElement('a');
  912. elem.download = filename;
  913. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  914. elem.dataset.downloadurl
  915. = ['text/json', elem.download, elem.href].join(':');
  916. elem.dispatchEvent(new MouseEvent('click', {
  917. view: window,
  918. bubbles: true,
  919. cancelable: false
  920. }));
  921. },
  922. /**
  923. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  924. * desire to keep room private to this instance and (2) the need of other
  925. * modules to send and receive commands to and from participants.
  926. * Eventually, this instance remains in control with respect to the
  927. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  928. * JitsiConference) is to be used in the implementation of the Command(s)
  929. * API of this instance.
  930. */
  931. commands: {
  932. /**
  933. * Known custom conference commands.
  934. */
  935. defaults: commands,
  936. /**
  937. * Receives notifications from other participants about commands aka
  938. * custom events (sent by sendCommand or sendCommandOnce methods).
  939. * @param command {String} the name of the command
  940. * @param handler {Function} handler for the command
  941. */
  942. addCommandListener () {
  943. room.addCommandListener.apply(room, arguments);
  944. },
  945. /**
  946. * Removes command.
  947. * @param name {String} the name of the command.
  948. */
  949. removeCommand () {
  950. room.removeCommand.apply(room, arguments);
  951. },
  952. /**
  953. * Sends command.
  954. * @param name {String} the name of the command.
  955. * @param values {Object} with keys and values that will be sent.
  956. */
  957. sendCommand () {
  958. room.sendCommand.apply(room, arguments);
  959. },
  960. /**
  961. * Sends command one time.
  962. * @param name {String} the name of the command.
  963. * @param values {Object} with keys and values that will be sent.
  964. */
  965. sendCommandOnce () {
  966. room.sendCommandOnce.apply(room, arguments);
  967. }
  968. },
  969. _createRoom (localTracks) {
  970. room = connection.initJitsiConference(APP.conference.roomName,
  971. this._getConferenceOptions());
  972. this._setLocalAudioVideoStreams(localTracks);
  973. this._room = room; // FIXME do not use this
  974. _setupLocalParticipantProperties();
  975. this._setupListeners();
  976. },
  977. /**
  978. * Sets local video and audio streams.
  979. * @param {JitsiLocalTrack[]} tracks=[]
  980. * @returns {Promise[]}
  981. * @private
  982. */
  983. _setLocalAudioVideoStreams(tracks = []) {
  984. return tracks.map(track => {
  985. if (track.isAudioTrack()) {
  986. return this.useAudioStream(track);
  987. } else if (track.isVideoTrack()) {
  988. return this.useVideoStream(track);
  989. } else {
  990. logger.error(
  991. "Ignored not an audio nor a video track: ", track);
  992. return Promise.resolve();
  993. }
  994. });
  995. },
  996. _getConferenceOptions() {
  997. let options = config;
  998. if(config.enableRecording && !config.recordingType) {
  999. options.recordingType = (config.hosts &&
  1000. (typeof config.hosts.jirecon != "undefined"))?
  1001. "jirecon" : "colibri";
  1002. }
  1003. return options;
  1004. },
  1005. /**
  1006. * Start using provided video stream.
  1007. * Stops previous video stream.
  1008. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1009. * @returns {Promise}
  1010. */
  1011. useVideoStream(newStream) {
  1012. return APP.store.dispatch(
  1013. replaceLocalTrack(localVideo, newStream, room))
  1014. .then(() => {
  1015. localVideo = newStream;
  1016. if (newStream) {
  1017. this.videoMuted = newStream.isMuted();
  1018. this.isSharingScreen = newStream.videoType === 'desktop';
  1019. APP.UI.addLocalStream(newStream);
  1020. } else {
  1021. // No video is treated the same way as being video muted
  1022. this.videoMuted = true;
  1023. this.isSharingScreen = false;
  1024. }
  1025. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  1026. this.updateVideoIconEnabled();
  1027. APP.UI.updateDesktopSharingButtons();
  1028. });
  1029. },
  1030. /**
  1031. * Start using provided audio stream.
  1032. * Stops previous audio stream.
  1033. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1034. * @returns {Promise}
  1035. */
  1036. useAudioStream(newStream) {
  1037. return APP.store.dispatch(
  1038. replaceLocalTrack(localAudio, newStream, room))
  1039. .then(() => {
  1040. localAudio = newStream;
  1041. if (newStream) {
  1042. this.audioMuted = newStream.isMuted();
  1043. APP.UI.addLocalStream(newStream);
  1044. } else {
  1045. this.audioMuted = false;
  1046. }
  1047. APP.UI.setMicrophoneButtonEnabled(true);
  1048. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  1049. });
  1050. },
  1051. /**
  1052. * Triggers a tooltip to display when a feature was attempted to be used
  1053. * while in audio only mode.
  1054. *
  1055. * @param {string} featureName - The name of the feature that attempted to
  1056. * toggle.
  1057. * @private
  1058. * @returns {void}
  1059. */
  1060. _displayAudioOnlyTooltip(featureName) {
  1061. let tooltipElementId = null;
  1062. switch (featureName) {
  1063. case 'screenShare':
  1064. tooltipElementId = '#screenshareWhileAudioOnly';
  1065. break;
  1066. case 'videoMute':
  1067. tooltipElementId = '#unmuteWhileAudioOnly';
  1068. break;
  1069. }
  1070. if (tooltipElementId) {
  1071. APP.UI.showToolbar(6000);
  1072. APP.UI.showCustomToolbarPopup(
  1073. tooltipElementId, true, 5000);
  1074. }
  1075. },
  1076. /**
  1077. * Returns whether or not the conference is currently in audio only mode.
  1078. *
  1079. * @returns {boolean}
  1080. */
  1081. isAudioOnly() {
  1082. return Boolean(
  1083. APP.store.getState()['features/base/conference'].audioOnly);
  1084. },
  1085. videoSwitchInProgress: false,
  1086. /**
  1087. * This fields stores a handler which will create a Promise which turns off
  1088. * the screen sharing and restores the previous video state (was there
  1089. * any video, before switching to screen sharing ? was it muted ?).
  1090. *
  1091. * Once called this fields is cleared to <tt>null</tt>.
  1092. * @type {Function|null}
  1093. */
  1094. _untoggleScreenSharing: null,
  1095. /**
  1096. * Creates a Promise which turns off the screen sharing and restores
  1097. * the previous state described by the arguments.
  1098. *
  1099. * This method is bound to the appropriate values, after switching to screen
  1100. * sharing and stored in {@link _untoggleScreenSharing}.
  1101. *
  1102. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1103. * used, before switching to screen sharing.
  1104. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1105. * switching to screen sharing.
  1106. * @return {Promise} resolved after the screen sharing is turned off, or
  1107. * rejected with some error (no idea what kind of error, possible GUM error)
  1108. * in case it fails.
  1109. * @private
  1110. */
  1111. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1112. this._untoggleScreenSharing = null;
  1113. this.videoSwitchInProgress = true;
  1114. APP.remoteControl.receiver.stop();
  1115. let promise = null;
  1116. if (didHaveVideo) {
  1117. promise = createLocalTracks({ devices: ['video'] })
  1118. .then(([stream]) => this.useVideoStream(stream))
  1119. .then(() => {
  1120. JitsiMeetJS.analytics.sendEvent(
  1121. 'conference.sharingDesktop.stop');
  1122. logger.log('switched back to local video');
  1123. if (!localVideo && wasVideoMuted) {
  1124. return Promise.reject('No local video to be muted!');
  1125. } else if (wasVideoMuted && localVideo) {
  1126. return localVideo.mute();
  1127. }
  1128. })
  1129. .catch(error => {
  1130. logger.error('failed to switch back to local video', error);
  1131. return this.useVideoStream(null).then(() => {
  1132. // Still fail with the original err
  1133. return Promise.reject(error);
  1134. });
  1135. });
  1136. } else {
  1137. promise = this.useVideoStream(null);
  1138. }
  1139. return promise.then(
  1140. () => {
  1141. this.videoSwitchInProgress = false;
  1142. },
  1143. error => {
  1144. this.videoSwitchInProgress = false;
  1145. throw error;
  1146. });
  1147. },
  1148. /**
  1149. * Toggles between screensharing and camera video.
  1150. * @param {Object} [options] - Screen sharing options that will be passed to
  1151. * createLocalTracks.
  1152. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1153. * sources that have to be displayed in the desktop picker window ('screen',
  1154. * 'window', etc.).
  1155. * @return {Promise.<T>}
  1156. */
  1157. toggleScreenSharing(options = {}) {
  1158. if (this.videoSwitchInProgress) {
  1159. return Promise.reject('Switch in progress.');
  1160. }
  1161. if (!this.isDesktopSharingEnabled) {
  1162. return Promise.reject(
  1163. 'Cannot toggle screen sharing: not supported.');
  1164. }
  1165. if (this.isAudioOnly()) {
  1166. this._displayAudioOnlyTooltip('screenShare');
  1167. return Promise.reject('No screensharing in audio only mode');
  1168. }
  1169. if (!this._untoggleScreenSharing) {
  1170. return this._switchToScreenSharing(options);
  1171. } else {
  1172. return this._untoggleScreenSharing();
  1173. }
  1174. },
  1175. /**
  1176. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1177. * @param {Object} [options] - Screen sharing options that will be passed to
  1178. * createLocalTracks.
  1179. *
  1180. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1181. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1182. * {@link JitsiTrackError}.
  1183. *
  1184. * @private
  1185. */
  1186. _createDesktopTrack(options = {}) {
  1187. let externalInstallation = false;
  1188. let DSExternalInstallationInProgress = false;
  1189. const didHaveVideo = Boolean(localVideo);
  1190. const wasVideoMuted = this.videoMuted;
  1191. return createLocalTracks({
  1192. desktopSharingSources: options.desktopSharingSources,
  1193. devices: ['desktop'],
  1194. desktopSharingExtensionExternalInstallation: {
  1195. interval: 500,
  1196. checkAgain: () => {
  1197. return DSExternalInstallationInProgress;
  1198. },
  1199. listener: (status, url) => {
  1200. switch(status) {
  1201. case "waitingForExtension": {
  1202. DSExternalInstallationInProgress = true;
  1203. externalInstallation = true;
  1204. const listener = () => {
  1205. // Wait a little bit more just to be sure that
  1206. // we won't miss the extension installation
  1207. setTimeout(
  1208. () => {
  1209. DSExternalInstallationInProgress = false;
  1210. }, 500);
  1211. APP.UI.removeListener(
  1212. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1213. listener);
  1214. };
  1215. APP.UI.addListener(
  1216. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1217. listener);
  1218. APP.UI.showExtensionExternalInstallationDialog(url);
  1219. break;
  1220. }
  1221. case "extensionFound": {
  1222. if (externalInstallation) { //close the dialog
  1223. $.prompt.close();
  1224. }
  1225. break;
  1226. }
  1227. default: {
  1228. //Unknown status
  1229. }
  1230. }
  1231. }
  1232. }
  1233. }).then(([desktopStream]) => {
  1234. // Stores the "untoggle" handler which remembers whether was
  1235. // there any video before and whether was it muted.
  1236. this._untoggleScreenSharing
  1237. = this._turnScreenSharingOff
  1238. .bind(this, didHaveVideo, wasVideoMuted);
  1239. desktopStream.on(
  1240. TrackEvents.LOCAL_TRACK_STOPPED,
  1241. () => {
  1242. // If the stream was stopped during screen sharing
  1243. // session then we should switch back to video.
  1244. if (this.isSharingScreen) {
  1245. this._untoggleScreenSharing
  1246. && this._untoggleScreenSharing();
  1247. }
  1248. }
  1249. );
  1250. // close external installation dialog on success.
  1251. if (externalInstallation) {
  1252. $.prompt.close();
  1253. }
  1254. return desktopStream;
  1255. }, error => {
  1256. DSExternalInstallationInProgress = false;
  1257. // close external installation dialog on success.
  1258. if (externalInstallation) {
  1259. $.prompt.close();
  1260. }
  1261. throw error;
  1262. });
  1263. },
  1264. /**
  1265. * Tries to switch to the screenshairng mode by disposing camera stream and
  1266. * replacing it with a desktop one.
  1267. *
  1268. * @param {Object} [options] - Screen sharing options that will be passed to
  1269. * createLocalTracks.
  1270. *
  1271. * @return {Promise} - A Promise resolved if the operation succeeds or
  1272. * rejected with some unknown type of error in case it fails. Promise will
  1273. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1274. *
  1275. * @private
  1276. */
  1277. _switchToScreenSharing(options = {}) {
  1278. if (this.videoSwitchInProgress) {
  1279. return Promise.reject('Switch in progress.');
  1280. }
  1281. this.videoSwitchInProgress = true;
  1282. return this._createDesktopTrack(options).then(stream => {
  1283. return this.useVideoStream(stream);
  1284. }).then(() => {
  1285. this.videoSwitchInProgress = false;
  1286. JitsiMeetJS.analytics.sendEvent('conference.sharingDesktop.start');
  1287. logger.log('sharing local desktop');
  1288. }).catch(error => {
  1289. this.videoSwitchInProgress = false;
  1290. // Pawel: With this call I'm trying to preserve the original
  1291. // behaviour although it is not clear why would we "untoggle"
  1292. // on failure. I suppose it was to restore video in case there
  1293. // was some problem during "this.useVideoStream(desktopStream)".
  1294. // It's important to note that the handler will not be available
  1295. // if we fail early on trying to get desktop media (which makes
  1296. // sense, because the camera video is still being used, so
  1297. // nothing to "untoggle").
  1298. if (this._untoggleScreenSharing) {
  1299. this._untoggleScreenSharing();
  1300. }
  1301. // FIXME the code inside of _handleScreenSharingError is
  1302. // asynchronous, but does not return a Promise and is not part of
  1303. // the current Promise chain.
  1304. this._handleScreenSharingError(error);
  1305. });
  1306. },
  1307. /**
  1308. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1309. * trying to create screensharing track. It will either do nothing if
  1310. * the dialog was canceled on user's request or display inline installation
  1311. * dialog and ask the user to install the extension, once the extension is
  1312. * installed it will switch the conference to screensharing. The last option
  1313. * is that an unrecoverable error dialog will be displayed.
  1314. * @param {JitsiTrackError} error - The error returned by
  1315. * {@link _createDesktopTrack} Promise.
  1316. * @private
  1317. */
  1318. _handleScreenSharingError(error) {
  1319. if (error.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1320. return;
  1321. }
  1322. logger.error('failed to share local desktop', error);
  1323. if (error.name === TrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1324. // If start with screen sharing the extension will fail to install
  1325. // (if not found), because the request has been triggered by the
  1326. // script. Show a dialog which asks user to click "install" and try
  1327. // again switching to the screen sharing.
  1328. APP.UI.showExtensionInlineInstallationDialog(
  1329. () => {
  1330. this.toggleScreenSharing();
  1331. }
  1332. );
  1333. return;
  1334. } else if (error.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1335. APP.UI.showExtensionRequiredDialog(
  1336. config.desktopSharingFirefoxExtensionURL
  1337. );
  1338. return;
  1339. }
  1340. // Handling:
  1341. // TrackErrors.PERMISSION_DENIED
  1342. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1343. // TrackErrors.GENERAL
  1344. // and any other
  1345. let dialogTxt;
  1346. let dialogTitleKey;
  1347. if (error.name === TrackErrors.PERMISSION_DENIED) {
  1348. dialogTxt = APP.translation.generateTranslationHTML(
  1349. "dialog.screenSharingPermissionDeniedError");
  1350. dialogTitleKey = "dialog.error";
  1351. } else {
  1352. dialogTxt = APP.translation.generateTranslationHTML(
  1353. "dialog.failtoinstall");
  1354. dialogTitleKey = "dialog.permissionDenied";
  1355. }
  1356. APP.UI.messageHandler.openDialog(dialogTitleKey, dialogTxt, false);
  1357. },
  1358. /**
  1359. * Setup interaction between conference and UI.
  1360. */
  1361. _setupListeners() {
  1362. // add local streams when joined to the conference
  1363. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1364. APP.store.dispatch(conferenceJoined(room));
  1365. APP.UI.mucJoined();
  1366. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1367. APP.UI.markVideoInterrupted(false);
  1368. });
  1369. room.on(
  1370. ConferenceEvents.CONFERENCE_LEFT,
  1371. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1372. room.on(
  1373. ConferenceEvents.AUTH_STATUS_CHANGED,
  1374. (authEnabled, authLogin) =>
  1375. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1376. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1377. user => APP.UI.onUserFeaturesChanged(user));
  1378. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1379. if (user.isHidden())
  1380. return;
  1381. APP.store.dispatch(participantJoined({
  1382. id,
  1383. name: user.getDisplayName(),
  1384. role: user.getRole()
  1385. }));
  1386. logger.log('USER %s connnected', id, user);
  1387. APP.API.notifyUserJoined(id);
  1388. APP.UI.addUser(user);
  1389. // check the roles for the new user and reflect them
  1390. APP.UI.updateUserRole(user);
  1391. updateRemoteThumbnailsVisibility();
  1392. });
  1393. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1394. APP.store.dispatch(participantLeft(id, user));
  1395. logger.log('USER %s LEFT', id, user);
  1396. APP.API.notifyUserLeft(id);
  1397. APP.UI.removeUser(id, user.getDisplayName());
  1398. APP.UI.onSharedVideoStop(id);
  1399. updateRemoteThumbnailsVisibility();
  1400. });
  1401. room.on(ConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1402. let user = room.getParticipantById(id);
  1403. if (user) {
  1404. APP.UI.updateUserStatus(user, status);
  1405. }
  1406. });
  1407. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1408. if (this.isLocalId(id)) {
  1409. logger.info(`My role changed, new role: ${role}`);
  1410. APP.store.dispatch(localParticipantRoleChanged(role));
  1411. if (this.isModerator !== room.isModerator()) {
  1412. this.isModerator = room.isModerator();
  1413. APP.UI.updateLocalRole(room.isModerator());
  1414. }
  1415. } else {
  1416. APP.store.dispatch(participantRoleChanged(id, role));
  1417. let user = room.getParticipantById(id);
  1418. if (user) {
  1419. APP.UI.updateUserRole(user);
  1420. }
  1421. }
  1422. });
  1423. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1424. if(!track || track.isLocal())
  1425. return;
  1426. APP.store.dispatch(trackAdded(track));
  1427. });
  1428. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1429. if(!track || track.isLocal())
  1430. return;
  1431. APP.store.dispatch(trackRemoved(track));
  1432. });
  1433. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1434. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1435. lvl = 0;
  1436. }
  1437. if(config.debug)
  1438. {
  1439. this.audioLevelsMap[id] = lvl;
  1440. if(config.debugAudioLevels)
  1441. logger.log("AudioLevel:" + id + "/" + lvl);
  1442. }
  1443. APP.UI.setAudioLevel(id, lvl);
  1444. });
  1445. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1446. APP.UI.showToolbar(6000);
  1447. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1448. });
  1449. room.on(
  1450. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1451. (leavingIds, enteringIds) => {
  1452. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1453. });
  1454. room.on(
  1455. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1456. id => {
  1457. APP.UI.participantConnectionStatusChanged(id);
  1458. });
  1459. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1460. if (this.isLocalId(id)) {
  1461. this.isDominantSpeaker = true;
  1462. this.setRaisedHand(false);
  1463. } else {
  1464. this.isDominantSpeaker = false;
  1465. var participant = room.getParticipantById(id);
  1466. if (participant) {
  1467. APP.UI.setRaisedHandStatus(participant, false);
  1468. }
  1469. }
  1470. APP.UI.markDominantSpeaker(id);
  1471. });
  1472. if (!interfaceConfig.filmStripOnly) {
  1473. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1474. APP.UI.markVideoInterrupted(true);
  1475. });
  1476. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1477. APP.UI.markVideoInterrupted(false);
  1478. });
  1479. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1480. let nick = getDisplayName(id);
  1481. APP.API.notifyReceivedChatMessage({
  1482. id,
  1483. nick,
  1484. body,
  1485. ts
  1486. });
  1487. APP.UI.addMessage(id, nick, body, ts);
  1488. });
  1489. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1490. APP.API.notifySendingChatMessage(message);
  1491. room.sendTextMessage(message);
  1492. });
  1493. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1494. try {
  1495. // do not try to select participant if there is none (we
  1496. // are alone in the room), otherwise an error will be
  1497. // thrown cause reporting mechanism is not available
  1498. // (datachannels currently)
  1499. if (room.getParticipants().length === 0)
  1500. return;
  1501. room.selectParticipant(id);
  1502. } catch (e) {
  1503. JitsiMeetJS.analytics.sendEvent(
  1504. 'selectParticipant.failed');
  1505. reportError(e);
  1506. }
  1507. });
  1508. APP.UI.addListener(
  1509. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1510. () => this._displayAudioOnlyTooltip('videoMute'));
  1511. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1512. (smallVideo, isPinned) => {
  1513. let smallVideoId = smallVideo.getId();
  1514. let isLocal = APP.conference.isLocalId(smallVideoId);
  1515. let eventName
  1516. = (isPinned ? "pinned" : "unpinned") + "." +
  1517. (isLocal ? "local" : "remote");
  1518. let participantCount = room.getParticipantCount();
  1519. JitsiMeetJS.analytics.sendEvent(
  1520. eventName,
  1521. { value: participantCount });
  1522. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1523. // the participant is on the large video ?
  1524. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1525. && !isLocal) {
  1526. // When the library starts supporting multiple pins we
  1527. // would pass the isPinned parameter together with the
  1528. // identifier, but currently we send null to indicate that
  1529. // we unpin the last pinned.
  1530. try {
  1531. room.pinParticipant(isPinned ? smallVideoId : null);
  1532. } catch (e) {
  1533. reportError(e);
  1534. }
  1535. }
  1536. updateRemoteThumbnailsVisibility();
  1537. });
  1538. }
  1539. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1540. APP.UI.showLocalConnectionInterrupted(true);
  1541. });
  1542. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1543. APP.UI.showLocalConnectionInterrupted(false);
  1544. });
  1545. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1546. const formattedDisplayName
  1547. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1548. APP.store.dispatch(participantUpdated({
  1549. id,
  1550. name: formattedDisplayName
  1551. }));
  1552. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1553. APP.UI.changeDisplayName(id, formattedDisplayName);
  1554. });
  1555. room.on(
  1556. ConferenceEvents.LOCK_STATE_CHANGED,
  1557. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1558. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1559. (participant, name, oldValue, newValue) => {
  1560. if (name === "raisedHand") {
  1561. APP.UI.setRaisedHandStatus(participant, newValue);
  1562. }
  1563. });
  1564. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1565. logger.log("Received recorder status change: ", status, error);
  1566. APP.UI.updateRecordingState(status);
  1567. });
  1568. room.on(ConferenceEvents.KICKED, () => {
  1569. APP.UI.hideStats();
  1570. APP.UI.notifyKicked();
  1571. // FIXME close
  1572. });
  1573. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1574. APP.store.dispatch(suspendDetected());
  1575. // After wake up, we will be in a state where conference is left
  1576. // there will be dialog shown to user.
  1577. // We do not want video/audio as we show an overlay and after it
  1578. // user need to rejoin or close, while waking up we can detect
  1579. // camera wakeup as a problem with device.
  1580. // We also do not care about device change, which happens
  1581. // on resume after suspending PC.
  1582. if (this.deviceChangeListener)
  1583. JitsiMeetJS.mediaDevices.removeEventListener(
  1584. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1585. this.deviceChangeListener);
  1586. // stop local video
  1587. if (localVideo) {
  1588. localVideo.dispose();
  1589. }
  1590. // stop local audio
  1591. if (localAudio) {
  1592. localAudio.dispose();
  1593. }
  1594. });
  1595. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1596. APP.UI.updateDTMFSupport(isDTMFSupported);
  1597. });
  1598. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1599. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1600. if (this.isAudioOnly() && !muted) {
  1601. this._displayAudioOnlyTooltip('videoMute');
  1602. } else if (!localVideo && this.videoMuted && !muted) {
  1603. // Maybe try to create local video if there wasn't any ?
  1604. // This handles the case when user joined with no video
  1605. // (dismissed screen sharing screen), but decided to add it
  1606. // later on by clicking on muted video icon.
  1607. createLocalTracks({ devices: ['video'] }, false)
  1608. .then(([videoTrack]) => {
  1609. APP.conference.useVideoStream(videoTrack);
  1610. })
  1611. .catch(error => {
  1612. APP.UI.showDeviceErrorDialog(null, error);
  1613. });
  1614. } else {
  1615. muteLocalVideo(muted);
  1616. }
  1617. });
  1618. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1619. (stats) => {
  1620. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1621. });
  1622. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1623. (id, stats) => {
  1624. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1625. });
  1626. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1627. APP.UI.initEtherpad(value);
  1628. });
  1629. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1630. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1631. APP.store.dispatch(participantUpdated({
  1632. id: from,
  1633. email: data.value
  1634. }));
  1635. APP.UI.setUserEmail(from, data.value);
  1636. });
  1637. room.addCommandListener(
  1638. this.commands.defaults.AVATAR_URL,
  1639. (data, from) => {
  1640. APP.store.dispatch(
  1641. participantUpdated({
  1642. id: from,
  1643. avatarURL: data.value
  1644. }));
  1645. APP.UI.setUserAvatarUrl(from, data.value);
  1646. });
  1647. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1648. (data, from) => {
  1649. APP.store.dispatch(
  1650. participantUpdated({
  1651. id: from,
  1652. avatarID: data.value
  1653. }));
  1654. APP.UI.setUserAvatarID(from, data.value);
  1655. });
  1656. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1657. this.changeLocalDisplayName.bind(this));
  1658. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1659. (startAudioMuted, startVideoMuted) => {
  1660. room.setStartMutedPolicy({
  1661. audio: startAudioMuted,
  1662. video: startVideoMuted
  1663. });
  1664. }
  1665. );
  1666. room.on(
  1667. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1668. ({ audio, video }) => {
  1669. APP.UI.onStartMutedChanged(audio, video);
  1670. }
  1671. );
  1672. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1673. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1674. && APP.UI.notifyInitiallyMuted();
  1675. });
  1676. room.on(
  1677. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1678. APP.UI.updateDevicesAvailability(id, devices);
  1679. }
  1680. );
  1681. // call hangup
  1682. APP.UI.addListener(UIEvents.HANGUP, () => {
  1683. this.hangup(true);
  1684. });
  1685. // logout
  1686. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1687. AuthHandler.logout(room).then(url => {
  1688. if (url) {
  1689. UIUtil.redirect(url);
  1690. } else {
  1691. this.hangup(true);
  1692. }
  1693. });
  1694. });
  1695. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1696. (id, oldResolution, newResolution, delay) => {
  1697. var logObject = {
  1698. id: "resolution_change",
  1699. participant: id,
  1700. oldValue: oldResolution,
  1701. newValue: newResolution,
  1702. delay: delay
  1703. };
  1704. room.sendApplicationLog(JSON.stringify(logObject));
  1705. // We only care about the delay between simulcast streams.
  1706. // Longer delays will be caused by something else and will just
  1707. // poison the data.
  1708. if (delay < 2000) {
  1709. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1710. {value: delay});
  1711. }
  1712. });
  1713. // Starts or stops the recording for the conference.
  1714. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1715. room.toggleRecording(options);
  1716. });
  1717. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1718. room.setSubject(topic);
  1719. });
  1720. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1721. APP.UI.setSubject(subject);
  1722. });
  1723. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1724. room.kickParticipant(id);
  1725. });
  1726. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1727. room.muteParticipant(id);
  1728. });
  1729. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1730. AuthHandler.authenticate(room);
  1731. });
  1732. APP.UI.addListener(
  1733. UIEvents.VIDEO_DEVICE_CHANGED,
  1734. (cameraDeviceId) => {
  1735. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1736. createLocalTracks({
  1737. devices: ['video'],
  1738. cameraDeviceId: cameraDeviceId,
  1739. micDeviceId: null
  1740. })
  1741. .then(([stream]) => {
  1742. if (this.isAudioOnly()) {
  1743. return stream.mute()
  1744. .then(() => stream);
  1745. }
  1746. return stream;
  1747. })
  1748. .then(stream => {
  1749. this.useVideoStream(stream);
  1750. logger.log('switched local video device');
  1751. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1752. })
  1753. .catch((err) => {
  1754. APP.UI.showDeviceErrorDialog(null, err);
  1755. });
  1756. }
  1757. );
  1758. APP.UI.addListener(
  1759. UIEvents.AUDIO_DEVICE_CHANGED,
  1760. (micDeviceId) => {
  1761. JitsiMeetJS.analytics.sendEvent(
  1762. 'settings.changeDevice.audioIn');
  1763. createLocalTracks({
  1764. devices: ['audio'],
  1765. cameraDeviceId: null,
  1766. micDeviceId: micDeviceId
  1767. })
  1768. .then(([stream]) => {
  1769. this.useAudioStream(stream);
  1770. logger.log('switched local audio device');
  1771. APP.settings.setMicDeviceId(micDeviceId, true);
  1772. })
  1773. .catch((err) => {
  1774. APP.UI.showDeviceErrorDialog(err, null);
  1775. });
  1776. }
  1777. );
  1778. APP.UI.addListener(
  1779. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1780. (audioOutputDeviceId) => {
  1781. JitsiMeetJS.analytics.sendEvent(
  1782. 'settings.changeDevice.audioOut');
  1783. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1784. .then(() => logger.log('changed audio output device'))
  1785. .catch((err) => {
  1786. logger.warn('Failed to change audio output device. ' +
  1787. 'Default or previously set audio output device ' +
  1788. 'will be used instead.', err);
  1789. });
  1790. }
  1791. );
  1792. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1793. muteLocalVideo(audioOnly);
  1794. // Immediately update the UI by having remote videos and the large
  1795. // video update themselves instead of waiting for some other event
  1796. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1797. // There is no guarantee another event will trigger the update
  1798. // immediately and in all situations, for example because a remote
  1799. // participant is having connection trouble so no status changes.
  1800. APP.UI.updateAllVideos();
  1801. });
  1802. APP.UI.addListener(
  1803. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1804. );
  1805. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1806. (url, state, time, isMuted, volume) => {
  1807. // send start and stop commands once, and remove any updates
  1808. // that had left
  1809. if (state === 'stop' || state === 'start' || state === 'playing') {
  1810. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1811. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1812. value: url,
  1813. attributes: {
  1814. state: state,
  1815. time: time,
  1816. muted: isMuted,
  1817. volume: volume
  1818. }
  1819. });
  1820. }
  1821. else {
  1822. // in case of paused, in order to allow late users to join
  1823. // paused
  1824. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1825. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1826. value: url,
  1827. attributes: {
  1828. state: state,
  1829. time: time,
  1830. muted: isMuted,
  1831. volume: volume
  1832. }
  1833. });
  1834. }
  1835. updateRemoteThumbnailsVisibility();
  1836. });
  1837. room.addCommandListener(
  1838. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1839. if (attributes.state === 'stop') {
  1840. APP.UI.onSharedVideoStop(id, attributes);
  1841. }
  1842. else if (attributes.state === 'start') {
  1843. APP.UI.onSharedVideoStart(id, value, attributes);
  1844. }
  1845. else if (attributes.state === 'playing'
  1846. || attributes.state === 'pause') {
  1847. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1848. }
  1849. });
  1850. function updateRemoteThumbnailsVisibility() {
  1851. const localUserId = APP.conference.getMyUserId();
  1852. const remoteParticipantsCount = room.getParticipantCount() - 1;
  1853. // Get the remote thumbnail count for cases where there are
  1854. // non-participants displaying video, such as with video sharing.
  1855. const remoteVideosCount = APP.UI.getRemoteVideosCount();
  1856. const shouldShowRemoteThumbnails = interfaceConfig.filmStripOnly
  1857. || (APP.UI.isPinned(localUserId) && remoteVideosCount)
  1858. || remoteVideosCount > 1
  1859. || remoteParticipantsCount !== remoteVideosCount;
  1860. APP.UI.setRemoteThumbnailsVisibility(
  1861. Boolean(shouldShowRemoteThumbnails));
  1862. }
  1863. },
  1864. /**
  1865. * Adds any room listener.
  1866. * @param {string} eventName one of the ConferenceEvents
  1867. * @param {Function} listener the function to be called when the event
  1868. * occurs
  1869. */
  1870. addConferenceListener(eventName, listener) {
  1871. room.on(eventName, listener);
  1872. },
  1873. /**
  1874. * Removes any room listener.
  1875. * @param {string} eventName one of the ConferenceEvents
  1876. * @param {Function} listener the listener to be removed.
  1877. */
  1878. removeConferenceListener(eventName, listener) {
  1879. room.off(eventName, listener);
  1880. },
  1881. /**
  1882. * Inits list of current devices and event listener for device change.
  1883. * @private
  1884. */
  1885. _initDeviceList() {
  1886. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  1887. .then(isDeviceListAvailable => {
  1888. if (isDeviceListAvailable
  1889. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1890. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1891. // Ugly way to synchronize real device IDs with local
  1892. // storage and settings menu. This is a workaround until
  1893. // getConstraints() method will be implemented
  1894. // in browsers.
  1895. if (localAudio) {
  1896. APP.settings.setMicDeviceId(
  1897. localAudio.getDeviceId(), false);
  1898. }
  1899. if (localVideo) {
  1900. APP.settings.setCameraDeviceId(
  1901. localVideo.getDeviceId(), false);
  1902. }
  1903. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1904. APP.UI.onAvailableDevicesChanged(devices);
  1905. APP.store.dispatch(updateDeviceList(devices));
  1906. this.updateVideoIconEnabled();
  1907. });
  1908. this.deviceChangeListener = (devices) =>
  1909. window.setTimeout(
  1910. () => this._onDeviceListChanged(devices), 0);
  1911. JitsiMeetJS.mediaDevices.addEventListener(
  1912. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1913. this.deviceChangeListener);
  1914. }
  1915. })
  1916. .catch((error) => {
  1917. logger.warn(`Error getting device list: ${error}`);
  1918. });
  1919. },
  1920. /**
  1921. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1922. * handle change of available media devices.
  1923. * @private
  1924. * @param {MediaDeviceInfo[]} devices
  1925. * @returns {Promise}
  1926. */
  1927. _onDeviceListChanged(devices) {
  1928. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1929. // Event handler can be fired before direct
  1930. // enumerateDevices() call, so handle this situation here.
  1931. if (!currentDevices.audioinput &&
  1932. !currentDevices.videoinput &&
  1933. !currentDevices.audiooutput) {
  1934. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1935. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1936. }
  1937. let newDevices =
  1938. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1939. devices, this.isSharingScreen, localVideo, localAudio);
  1940. let promises = [];
  1941. let audioWasMuted = this.audioMuted;
  1942. let videoWasMuted = this.videoMuted;
  1943. let availableAudioInputDevices =
  1944. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1945. let availableVideoInputDevices =
  1946. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1947. if (typeof newDevices.audiooutput !== 'undefined') {
  1948. // Just ignore any errors in catch block.
  1949. promises.push(APP.settings
  1950. .setAudioOutputDeviceId(newDevices.audiooutput)
  1951. .catch());
  1952. }
  1953. promises.push(
  1954. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1955. createLocalTracks,
  1956. newDevices.videoinput,
  1957. newDevices.audioinput)
  1958. .then(tracks =>
  1959. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1960. .then(() => {
  1961. // If audio was muted before, or we unplugged current device
  1962. // and selected new one, then mute new audio track.
  1963. if (audioWasMuted ||
  1964. currentDevices.audioinput.length >
  1965. availableAudioInputDevices.length) {
  1966. muteLocalAudio(true);
  1967. }
  1968. // If video was muted before, or we unplugged current device
  1969. // and selected new one, then mute new video track.
  1970. if (!this.isSharingScreen &&
  1971. (videoWasMuted ||
  1972. currentDevices.videoinput.length >
  1973. availableVideoInputDevices.length)) {
  1974. muteLocalVideo(true);
  1975. }
  1976. }));
  1977. return Promise.all(promises)
  1978. .then(() => {
  1979. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1980. APP.UI.onAvailableDevicesChanged(devices);
  1981. this.updateVideoIconEnabled();
  1982. });
  1983. },
  1984. /**
  1985. * Determines whether or not the video button should be enabled.
  1986. */
  1987. updateVideoIconEnabled() {
  1988. const videoMediaDevices
  1989. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  1990. const videoDeviceCount
  1991. = videoMediaDevices ? videoMediaDevices.length : 0;
  1992. // The video functionality is considered available if there are any
  1993. // video devices detected or if there is local video stream already
  1994. // active which could be either screensharing stream or a video track
  1995. // created before the permissions were rejected (through browser
  1996. // config).
  1997. const available = videoDeviceCount > 0 || Boolean(localVideo);
  1998. logger.debug(
  1999. 'Camera button enabled: ' + available,
  2000. 'local video: ' + localVideo,
  2001. 'video devices: ' + videoMediaDevices,
  2002. 'device count: ' + videoDeviceCount);
  2003. APP.store.dispatch(setVideoAvailable(available));
  2004. },
  2005. /**
  2006. * Toggles the local "raised hand" status.
  2007. */
  2008. maybeToggleRaisedHand() {
  2009. this.setRaisedHand(!this.isHandRaised);
  2010. },
  2011. /**
  2012. * Sets the local "raised hand" status to a particular value.
  2013. */
  2014. setRaisedHand(raisedHand) {
  2015. if (raisedHand !== this.isHandRaised)
  2016. {
  2017. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2018. this.isHandRaised = raisedHand;
  2019. // Advertise the updated status
  2020. room.setLocalParticipantProperty("raisedHand", raisedHand);
  2021. // Update the view
  2022. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2023. }
  2024. },
  2025. /**
  2026. * Log event to callstats and analytics.
  2027. * @param {string} name the event name
  2028. * @param {int} value the value (it's int because google analytics supports
  2029. * only int).
  2030. * @param {string} label short text which provides more info about the event
  2031. * which allows to distinguish between few event cases of the same name
  2032. * NOTE: Should be used after conference.init
  2033. */
  2034. logEvent(name, value, label) {
  2035. if(JitsiMeetJS.analytics) {
  2036. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  2037. }
  2038. if(room) {
  2039. room.sendApplicationLog(JSON.stringify({name, value, label}));
  2040. }
  2041. },
  2042. /**
  2043. * Methods logs an application event given in the JSON format.
  2044. * @param {string} logJSON an event to be logged in JSON format
  2045. */
  2046. logJSON(logJSON) {
  2047. if (room) {
  2048. room.sendApplicationLog(logJSON);
  2049. }
  2050. },
  2051. /**
  2052. * Disconnect from the conference and optionally request user feedback.
  2053. * @param {boolean} [requestFeedback=false] if user feedback should be
  2054. * requested
  2055. */
  2056. hangup(requestFeedback = false) {
  2057. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2058. let requestFeedbackPromise = requestFeedback
  2059. ? APP.UI.requestFeedbackOnHangup()
  2060. // false - because the thank you dialog shouldn't be displayed
  2061. .catch(() => Promise.resolve(false))
  2062. : Promise.resolve(true);// true - because the thank you dialog
  2063. //should be displayed
  2064. // All promises are returning Promise.resolve to make Promise.all to
  2065. // be resolved when both Promises are finished. Otherwise Promise.all
  2066. // will reject on first rejected Promise and we can redirect the page
  2067. // before all operations are done.
  2068. Promise.all([
  2069. requestFeedbackPromise,
  2070. room.leave().then(disconnect, disconnect)
  2071. ]).then(values => {
  2072. APP.API.notifyReadyToClose();
  2073. maybeRedirectToWelcomePage(values[0]);
  2074. });
  2075. },
  2076. /**
  2077. * Changes the email for the local user
  2078. * @param email {string} the new email
  2079. */
  2080. changeLocalEmail(email = '') {
  2081. email = String(email).trim();
  2082. if (email === APP.settings.getEmail()) {
  2083. return;
  2084. }
  2085. const localId = room ? room.myUserId() : undefined;
  2086. APP.store.dispatch(participantUpdated({
  2087. id: localId,
  2088. local: true,
  2089. email
  2090. }));
  2091. APP.settings.setEmail(email);
  2092. APP.UI.setUserEmail(localId, email);
  2093. sendData(commands.EMAIL, email);
  2094. },
  2095. /**
  2096. * Changes the avatar url for the local user
  2097. * @param url {string} the new url
  2098. */
  2099. changeLocalAvatarUrl(url = '') {
  2100. url = String(url).trim();
  2101. if (url === APP.settings.getAvatarUrl()) {
  2102. return;
  2103. }
  2104. const localId = room ? room.myUserId() : undefined;
  2105. APP.store.dispatch(participantUpdated({
  2106. id: localId,
  2107. local: true,
  2108. avatarURL: url
  2109. }));
  2110. APP.settings.setAvatarUrl(url);
  2111. APP.UI.setUserAvatarUrl(localId, url);
  2112. sendData(commands.AVATAR_URL, url);
  2113. },
  2114. /**
  2115. * Sends a message via the data channel.
  2116. * @param {string} to the id of the endpoint that should receive the
  2117. * message. If "" - the message will be sent to all participants.
  2118. * @param {object} payload the payload of the message.
  2119. * @throws NetworkError or InvalidStateError or Error if the operation
  2120. * fails.
  2121. */
  2122. sendEndpointMessage(to, payload) {
  2123. room.sendEndpointMessage(to, payload);
  2124. },
  2125. /**
  2126. * Adds new listener.
  2127. * @param {String} eventName the name of the event
  2128. * @param {Function} listener the listener.
  2129. */
  2130. addListener(eventName, listener) {
  2131. eventEmitter.addListener(eventName, listener);
  2132. },
  2133. /**
  2134. * Removes listener.
  2135. * @param {String} eventName the name of the event that triggers the
  2136. * listener
  2137. * @param {Function} listener the listener.
  2138. */
  2139. removeListener(eventName, listener) {
  2140. eventEmitter.removeListener(eventName, listener);
  2141. },
  2142. /**
  2143. * Changes the display name for the local user
  2144. * @param nickname {string} the new display name
  2145. */
  2146. changeLocalDisplayName(nickname = '') {
  2147. const formattedNickname
  2148. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2149. if (formattedNickname === APP.settings.getDisplayName()) {
  2150. return;
  2151. }
  2152. APP.store.dispatch(participantUpdated({
  2153. id: this.getMyUserId(),
  2154. local: true,
  2155. name: formattedNickname
  2156. }));
  2157. APP.settings.setDisplayName(formattedNickname);
  2158. if (room) {
  2159. room.setDisplayName(formattedNickname);
  2160. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  2161. }
  2162. },
  2163. /**
  2164. * Returns the desktop sharing source id or undefined if the desktop sharing
  2165. * is not active at the moment.
  2166. *
  2167. * @returns {string|undefined} - The source id. If the track is not desktop
  2168. * track or the source id is not available, undefined will be returned.
  2169. */
  2170. getDesktopSharingSourceId() {
  2171. return localVideo.sourceId;
  2172. },
  2173. /**
  2174. * Returns the desktop sharing source type or undefined if the desktop
  2175. * sharing is not active at the moment.
  2176. *
  2177. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2178. * not desktop track or the source type is not available, undefined will be
  2179. * returned.
  2180. */
  2181. getDesktopSharingSourceType() {
  2182. return localVideo.sourceType;
  2183. }
  2184. };