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

conference.js 95KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import { openConnection } from './connection';
  3. import AuthHandler from './modules/UI/authentication/AuthHandler';
  4. import Recorder from './modules/recorder/Recorder';
  5. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  6. import * as RemoteControlEvents
  7. from './service/remotecontrol/RemoteControlEvents';
  8. import UIEvents from './service/UI/UIEvents';
  9. import UIUtil from './modules/UI/util/UIUtil';
  10. import { createTaskQueue } from './modules/util/helpers';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import {
  13. createDeviceChangedEvent,
  14. createStartSilentEvent,
  15. createScreenSharingEvent,
  16. createStreamSwitchDelayEvent,
  17. createTrackMutedEvent,
  18. sendAnalytics
  19. } from './react/features/analytics';
  20. import {
  21. maybeRedirectToWelcomePage,
  22. redirectToStaticPage,
  23. reloadWithStoredParams
  24. } from './react/features/app';
  25. import EventEmitter from 'events';
  26. import {
  27. AVATAR_ID_COMMAND,
  28. AVATAR_URL_COMMAND,
  29. EMAIL_COMMAND,
  30. authStatusChanged,
  31. commonUserJoinedHandling,
  32. commonUserLeftHandling,
  33. conferenceFailed,
  34. conferenceJoined,
  35. conferenceLeft,
  36. conferenceSubjectChanged,
  37. conferenceWillJoin,
  38. conferenceWillLeave,
  39. dataChannelOpened,
  40. kickedOut,
  41. lockStateChanged,
  42. onStartMutedPolicyChanged,
  43. p2pStatusChanged,
  44. sendLocalParticipant,
  45. setDesktopSharingEnabled
  46. } from './react/features/base/conference';
  47. import {
  48. checkAndNotifyForNewDevice,
  49. getAvailableDevices,
  50. notifyCameraError,
  51. notifyMicError,
  52. setAudioOutputDeviceId,
  53. updateDeviceList
  54. } from './react/features/base/devices';
  55. import {
  56. isFatalJitsiConnectionError,
  57. JitsiConferenceErrors,
  58. JitsiConferenceEvents,
  59. JitsiConnectionErrors,
  60. JitsiConnectionEvents,
  61. JitsiMediaDevicesEvents,
  62. JitsiParticipantConnectionStatus,
  63. JitsiTrackErrors,
  64. JitsiTrackEvents
  65. } from './react/features/base/lib-jitsi-meet';
  66. import {
  67. isVideoMutedByUser,
  68. MEDIA_TYPE,
  69. setAudioAvailable,
  70. setAudioMuted,
  71. setVideoAvailable,
  72. setVideoMuted
  73. } from './react/features/base/media';
  74. import { showNotification } from './react/features/notifications';
  75. import {
  76. dominantSpeakerChanged,
  77. getLocalParticipant,
  78. getNormalizedDisplayName,
  79. getParticipantById,
  80. localParticipantConnectionStatusChanged,
  81. localParticipantRoleChanged,
  82. participantConnectionStatusChanged,
  83. participantKicked,
  84. participantMutedUs,
  85. participantPresenceChanged,
  86. participantRoleChanged,
  87. participantUpdated
  88. } from './react/features/base/participants';
  89. import { updateSettings } from './react/features/base/settings';
  90. import {
  91. createLocalTracksF,
  92. destroyLocalTracks,
  93. isLocalTrackMuted,
  94. isUserInteractionRequiredForUnmute,
  95. replaceLocalTrack,
  96. trackAdded,
  97. trackRemoved
  98. } from './react/features/base/tracks';
  99. import { getJitsiMeetGlobalNS } from './react/features/base/util';
  100. import { showDesktopPicker } from './react/features/desktop-picker';
  101. import { appendSuffix } from './react/features/display-name';
  102. import {
  103. maybeOpenFeedbackDialog,
  104. submitFeedback
  105. } from './react/features/feedback';
  106. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay';
  107. import { suspendDetected } from './react/features/power-monitor';
  108. import { setSharedVideoStatus } from './react/features/shared-video';
  109. import { endpointMessageReceived } from './react/features/subtitles';
  110. const logger = require('jitsi-meet-logger').getLogger(__filename);
  111. const eventEmitter = new EventEmitter();
  112. let room;
  113. let connection;
  114. /*
  115. * Logic to open a desktop picker put on the window global for
  116. * lib-jitsi-meet to detect and invoke
  117. */
  118. window.JitsiMeetScreenObtainer = {
  119. openDesktopPicker(options, onSourceChoose) {
  120. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  121. }
  122. };
  123. /**
  124. * Known custom conference commands.
  125. */
  126. const commands = {
  127. AVATAR_ID: AVATAR_ID_COMMAND,
  128. AVATAR_URL: AVATAR_URL_COMMAND,
  129. CUSTOM_ROLE: 'custom-role',
  130. EMAIL: EMAIL_COMMAND,
  131. ETHERPAD: 'etherpad',
  132. SHARED_VIDEO: 'shared-video'
  133. };
  134. /**
  135. * Open Connection. When authentication failed it shows auth dialog.
  136. * @param roomName the room name to use
  137. * @returns Promise<JitsiConnection>
  138. */
  139. function connect(roomName) {
  140. return openConnection({
  141. retry: true,
  142. roomName
  143. })
  144. .catch(err => {
  145. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  146. APP.UI.notifyTokenAuthFailed();
  147. } else {
  148. APP.UI.notifyConnectionFailed(err);
  149. }
  150. throw err;
  151. });
  152. }
  153. /**
  154. * Share data to other users.
  155. * @param command the command
  156. * @param {string} value new value
  157. */
  158. function sendData(command, value) {
  159. if (!room) {
  160. return;
  161. }
  162. room.removeCommand(command);
  163. room.sendCommand(command, { value });
  164. }
  165. /**
  166. * Get user nickname by user id.
  167. * @param {string} id user id
  168. * @returns {string?} user nickname or undefined if user is unknown.
  169. */
  170. function getDisplayName(id) {
  171. const participant = getParticipantById(APP.store.getState(), id);
  172. return participant && participant.name;
  173. }
  174. /**
  175. * Mute or unmute local audio stream if it exists.
  176. * @param {boolean} muted - if audio stream should be muted or unmuted.
  177. */
  178. function muteLocalAudio(muted) {
  179. APP.store.dispatch(setAudioMuted(muted));
  180. }
  181. /**
  182. * Mute or unmute local video stream if it exists.
  183. * @param {boolean} muted if video stream should be muted or unmuted.
  184. *
  185. */
  186. function muteLocalVideo(muted) {
  187. APP.store.dispatch(setVideoMuted(muted));
  188. }
  189. /**
  190. * A queue for the async replaceLocalTrack action so that multiple audio
  191. * replacements cannot happen simultaneously. This solves the issue where
  192. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  193. * multiple local tracks of the same type to be used.
  194. *
  195. * @private
  196. * @type {Object}
  197. */
  198. const _replaceLocalAudioTrackQueue = createTaskQueue();
  199. /**
  200. * A task queue for replacement local video tracks. This separate queue exists
  201. * so video replacement is not blocked by audio replacement tasks in the queue
  202. * {@link _replaceLocalAudioTrackQueue}.
  203. *
  204. * @private
  205. * @type {Object}
  206. */
  207. const _replaceLocalVideoTrackQueue = createTaskQueue();
  208. /**
  209. *
  210. */
  211. class ConferenceConnector {
  212. /**
  213. *
  214. */
  215. constructor(resolve, reject) {
  216. this._resolve = resolve;
  217. this._reject = reject;
  218. this.reconnectTimeout = null;
  219. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  220. this._handleConferenceJoined.bind(this));
  221. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  222. this._onConferenceFailed.bind(this));
  223. }
  224. /**
  225. *
  226. */
  227. _handleConferenceFailed(err) {
  228. this._unsubscribe();
  229. this._reject(err);
  230. }
  231. /**
  232. *
  233. */
  234. _onConferenceFailed(err, ...params) {
  235. APP.store.dispatch(conferenceFailed(room, err, ...params));
  236. logger.error('CONFERENCE FAILED:', err, ...params);
  237. switch (err) {
  238. case JitsiConferenceErrors.CONNECTION_ERROR: {
  239. const [ msg ] = params;
  240. APP.UI.notifyConnectionFailed(msg);
  241. break;
  242. }
  243. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  244. // let's show some auth not allowed page
  245. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  246. break;
  247. }
  248. // not enough rights to create conference
  249. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  250. // Schedule reconnect to check if someone else created the room.
  251. this.reconnectTimeout = setTimeout(() => {
  252. APP.store.dispatch(conferenceWillJoin(room));
  253. room.join();
  254. }, 5000);
  255. const { password }
  256. = APP.store.getState()['features/base/conference'];
  257. AuthHandler.requireAuth(room, password);
  258. break;
  259. }
  260. case JitsiConferenceErrors.RESERVATION_ERROR: {
  261. const [ code, msg ] = params;
  262. APP.UI.notifyReservationError(code, msg);
  263. break;
  264. }
  265. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  266. APP.UI.notifyGracefulShutdown();
  267. break;
  268. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  269. const [ reason ] = params;
  270. APP.UI.hideStats();
  271. APP.UI.notifyConferenceDestroyed(reason);
  272. break;
  273. }
  274. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  275. // What really happens there is that the library is not ready yet,
  276. // because Jicofo is not available, but it is going to give it another
  277. // try.
  278. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  279. const [ focus, retrySec ] = params;
  280. APP.UI.notifyFocusDisconnected(focus, retrySec);
  281. break;
  282. }
  283. case JitsiConferenceErrors.FOCUS_LEFT:
  284. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  285. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  286. APP.store.dispatch(conferenceWillLeave(room));
  287. // FIXME the conference should be stopped by the library and not by
  288. // the app. Both the errors above are unrecoverable from the library
  289. // perspective.
  290. room.leave().then(() => connection.disconnect());
  291. break;
  292. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  293. connection.disconnect();
  294. APP.UI.notifyMaxUsersLimitReached();
  295. break;
  296. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  297. APP.store.dispatch(reloadWithStoredParams());
  298. break;
  299. default:
  300. this._handleConferenceFailed(err, ...params);
  301. }
  302. }
  303. /**
  304. *
  305. */
  306. _unsubscribe() {
  307. room.off(
  308. JitsiConferenceEvents.CONFERENCE_JOINED,
  309. this._handleConferenceJoined);
  310. room.off(
  311. JitsiConferenceEvents.CONFERENCE_FAILED,
  312. this._onConferenceFailed);
  313. if (this.reconnectTimeout !== null) {
  314. clearTimeout(this.reconnectTimeout);
  315. }
  316. AuthHandler.closeAuth();
  317. }
  318. /**
  319. *
  320. */
  321. _handleConferenceJoined() {
  322. this._unsubscribe();
  323. this._resolve();
  324. }
  325. /**
  326. *
  327. */
  328. connect() {
  329. room.join();
  330. }
  331. }
  332. /**
  333. * Disconnects the connection.
  334. * @returns resolved Promise. We need this in order to make the Promise.all
  335. * call in hangup() to resolve when all operations are finished.
  336. */
  337. function disconnect() {
  338. const onDisconnected = () => {
  339. APP.API.notifyConferenceLeft(APP.conference.roomName);
  340. return Promise.resolve();
  341. };
  342. return connection.disconnect().then(onDisconnected, onDisconnected);
  343. }
  344. /**
  345. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  346. *
  347. * @param {JitsiConnectionError} error - The reported error.
  348. * @returns {void}
  349. * @private
  350. */
  351. function _connectionFailedHandler(error) {
  352. if (isFatalJitsiConnectionError(error)) {
  353. APP.connection.removeEventListener(
  354. JitsiConnectionEvents.CONNECTION_FAILED,
  355. _connectionFailedHandler);
  356. if (room) {
  357. APP.store.dispatch(conferenceWillLeave(room));
  358. room.leave();
  359. }
  360. }
  361. }
  362. export default {
  363. /**
  364. * Flag used to delay modification of the muted status of local media tracks
  365. * until those are created (or not, but at that point it's certain that
  366. * the tracks won't exist).
  367. */
  368. _localTracksInitialized: false,
  369. isModerator: false,
  370. isSharingScreen: false,
  371. /**
  372. * Indicates if the desktop sharing functionality has been enabled.
  373. * It takes into consideration the status returned by
  374. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  375. * either if the desktop sharing is not supported by the current browser
  376. * or if it was disabled through lib-jitsi-meet specific options (check
  377. * config.js for listed options).
  378. */
  379. isDesktopSharingEnabled: false,
  380. /**
  381. * The local audio track (if any).
  382. * FIXME tracks from redux store should be the single source of truth
  383. * @type {JitsiLocalTrack|null}
  384. */
  385. localAudio: null,
  386. /**
  387. * The local video track (if any).
  388. * FIXME tracks from redux store should be the single source of truth, but
  389. * more refactoring is required around screen sharing ('localVideo' usages).
  390. * @type {JitsiLocalTrack|null}
  391. */
  392. localVideo: null,
  393. /**
  394. * Creates local media tracks and connects to a room. Will show error
  395. * dialogs in case accessing the local microphone and/or camera failed. Will
  396. * show guidance overlay for users on how to give access to camera and/or
  397. * microphone.
  398. * @param {string} roomName
  399. * @param {object} options
  400. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  401. * only audio track will be created and the audio only mode will be turned
  402. * on.
  403. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  404. * should start with screensharing instead of camera video.
  405. * @param {boolean} options.startWithAudioMuted - will start the conference
  406. * without any audio tracks.
  407. * @param {boolean} options.startWithVideoMuted - will start the conference
  408. * without any video tracks.
  409. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  410. */
  411. createInitialLocalTracksAndConnect(roomName, options = {}) {
  412. let audioAndVideoError,
  413. audioOnlyError,
  414. screenSharingError,
  415. videoOnlyError;
  416. const initialDevices = [];
  417. let requestedAudio = false;
  418. let requestedVideo = false;
  419. if (!options.startWithAudioMuted) {
  420. initialDevices.push('audio');
  421. requestedAudio = true;
  422. }
  423. if (!options.startWithVideoMuted
  424. && !options.startAudioOnly
  425. && !options.startScreenSharing) {
  426. initialDevices.push('video');
  427. requestedVideo = true;
  428. }
  429. JitsiMeetJS.mediaDevices.addEventListener(
  430. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  431. browser =>
  432. APP.store.dispatch(
  433. mediaPermissionPromptVisibilityChanged(true, browser))
  434. );
  435. let tryCreateLocalTracks;
  436. // FIXME is there any simpler way to rewrite this spaghetti below ?
  437. if (options.startScreenSharing) {
  438. tryCreateLocalTracks = this._createDesktopTrack()
  439. .then(desktopStream => {
  440. if (!requestedAudio) {
  441. return [ desktopStream ];
  442. }
  443. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  444. .then(([ audioStream ]) =>
  445. [ desktopStream, audioStream ])
  446. .catch(error => {
  447. audioOnlyError = error;
  448. return [ desktopStream ];
  449. });
  450. })
  451. .catch(error => {
  452. logger.error('Failed to obtain desktop stream', error);
  453. screenSharingError = error;
  454. return requestedAudio
  455. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  456. : [];
  457. })
  458. .catch(error => {
  459. audioOnlyError = error;
  460. return [];
  461. });
  462. } else if (!requestedAudio && !requestedVideo) {
  463. // Resolve with no tracks
  464. tryCreateLocalTracks = Promise.resolve([]);
  465. } else {
  466. tryCreateLocalTracks = createLocalTracksF({ devices: initialDevices }, true)
  467. .catch(err => {
  468. if (requestedAudio && requestedVideo) {
  469. // Try audio only...
  470. audioAndVideoError = err;
  471. return (
  472. createLocalTracksF({ devices: [ 'audio' ] }, true));
  473. } else if (requestedAudio && !requestedVideo) {
  474. audioOnlyError = err;
  475. return [];
  476. } else if (requestedVideo && !requestedAudio) {
  477. videoOnlyError = err;
  478. return [];
  479. }
  480. logger.error('Should never happen');
  481. })
  482. .catch(err => {
  483. // Log this just in case...
  484. if (!requestedAudio) {
  485. logger.error('The impossible just happened', err);
  486. }
  487. audioOnlyError = err;
  488. // Try video only...
  489. return requestedVideo
  490. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  491. : [];
  492. })
  493. .catch(err => {
  494. // Log this just in case...
  495. if (!requestedVideo) {
  496. logger.error('The impossible just happened', err);
  497. }
  498. videoOnlyError = err;
  499. return [];
  500. });
  501. }
  502. // Hide the permissions prompt/overlay as soon as the tracks are
  503. // created. Don't wait for the connection to be made, since in some
  504. // cases, when auth is rquired, for instance, that won't happen until
  505. // the user inputs their credentials, but the dialog would be
  506. // overshadowed by the overlay.
  507. tryCreateLocalTracks.then(() =>
  508. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false)));
  509. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  510. .then(([ tracks, con ]) => {
  511. // FIXME If there will be microphone error it will cover any
  512. // screensharing dialog, but it's still better than in
  513. // the reverse order where the screensharing dialog will
  514. // sometimes be closing the microphone alert ($.prompt.close();
  515. // is called). Need to figure out dialogs chaining to fix that.
  516. if (screenSharingError) {
  517. this._handleScreenSharingError(screenSharingError);
  518. }
  519. if (audioAndVideoError || audioOnlyError) {
  520. if (audioOnlyError || videoOnlyError) {
  521. // If both requests for 'audio' + 'video' and 'audio'
  522. // only failed, we assume that there are some problems
  523. // with user's microphone and show corresponding dialog.
  524. APP.store.dispatch(notifyMicError(audioOnlyError));
  525. APP.store.dispatch(notifyCameraError(videoOnlyError));
  526. } else {
  527. // If request for 'audio' + 'video' failed, but request
  528. // for 'audio' only was OK, we assume that we had
  529. // problems with camera and show corresponding dialog.
  530. APP.store.dispatch(
  531. notifyCameraError(audioAndVideoError));
  532. }
  533. }
  534. return [ tracks, con ];
  535. });
  536. },
  537. /**
  538. * Open new connection and join to the conference.
  539. * @param {object} options
  540. * @param {string} roomName - The name of the conference.
  541. * @returns {Promise}
  542. */
  543. init(options) {
  544. this.roomName = options.roomName;
  545. return (
  546. // Initialize the device list first. This way, when creating tracks
  547. // based on preferred devices, loose label matching can be done in
  548. // cases where the exact ID match is no longer available, such as
  549. // when the camera device has switched USB ports.
  550. // when in startSilent mode we want to start with audio muted
  551. this._initDeviceList()
  552. .catch(error => logger.warn(
  553. 'initial device list initialization failed', error))
  554. .then(() => this.createInitialLocalTracksAndConnect(
  555. options.roomName, {
  556. startAudioOnly: config.startAudioOnly,
  557. startScreenSharing: config.startScreenSharing,
  558. startWithAudioMuted: config.startWithAudioMuted
  559. || config.startSilent
  560. || isUserInteractionRequiredForUnmute(APP.store.getState()),
  561. startWithVideoMuted: config.startWithVideoMuted
  562. || isUserInteractionRequiredForUnmute(APP.store.getState())
  563. }))
  564. .then(([ tracks, con ]) => {
  565. tracks.forEach(track => {
  566. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  567. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  568. const mediaType = track.getType();
  569. sendAnalytics(
  570. createTrackMutedEvent(mediaType, 'initial mute'));
  571. logger.log(`${mediaType} mute: initially muted.`);
  572. track.mute();
  573. }
  574. });
  575. logger.log(`initialized with ${tracks.length} local tracks`);
  576. this._localTracksInitialized = true;
  577. con.addEventListener(
  578. JitsiConnectionEvents.CONNECTION_FAILED,
  579. _connectionFailedHandler);
  580. APP.connection = connection = con;
  581. // Desktop sharing related stuff:
  582. this.isDesktopSharingEnabled
  583. = JitsiMeetJS.isDesktopSharingEnabled();
  584. eventEmitter.emit(
  585. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  586. this.isDesktopSharingEnabled);
  587. APP.store.dispatch(
  588. setDesktopSharingEnabled(this.isDesktopSharingEnabled));
  589. this._createRoom(tracks);
  590. APP.remoteControl.init();
  591. // if user didn't give access to mic or camera or doesn't have
  592. // them at all, we mark corresponding toolbar buttons as muted,
  593. // so that the user can try unmute later on and add audio/video
  594. // to the conference
  595. if (!tracks.find(t => t.isAudioTrack())) {
  596. this.setAudioMuteStatus(true);
  597. }
  598. if (!tracks.find(t => t.isVideoTrack())) {
  599. this.setVideoMuteStatus(true);
  600. }
  601. // Initialize device list a second time to ensure device labels
  602. // get populated in case of an initial gUM acceptance; otherwise
  603. // they may remain as empty strings.
  604. this._initDeviceList(true);
  605. if (config.iAmRecorder) {
  606. this.recorder = new Recorder();
  607. }
  608. if (config.startSilent) {
  609. sendAnalytics(createStartSilentEvent());
  610. APP.store.dispatch(showNotification({
  611. descriptionKey: 'notify.startSilentDescription',
  612. titleKey: 'notify.startSilentTitle'
  613. }));
  614. }
  615. // XXX The API will take care of disconnecting from the XMPP
  616. // server (and, thus, leaving the room) on unload.
  617. return new Promise((resolve, reject) => {
  618. (new ConferenceConnector(resolve, reject)).connect();
  619. });
  620. })
  621. );
  622. },
  623. /**
  624. * Check if id is id of the local user.
  625. * @param {string} id id to check
  626. * @returns {boolean}
  627. */
  628. isLocalId(id) {
  629. return this.getMyUserId() === id;
  630. },
  631. /**
  632. * Tells whether the local video is muted or not.
  633. * @return {boolean}
  634. */
  635. isLocalVideoMuted() {
  636. // If the tracks are not ready, read from base/media state
  637. return this._localTracksInitialized
  638. ? isLocalTrackMuted(
  639. APP.store.getState()['features/base/tracks'],
  640. MEDIA_TYPE.VIDEO)
  641. : isVideoMutedByUser(APP.store);
  642. },
  643. /**
  644. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  645. * @param {boolean} mute true for mute and false for unmute.
  646. * @param {boolean} [showUI] when set to false will not display any error
  647. * dialogs in case of media permissions error.
  648. */
  649. muteAudio(mute, showUI = true) {
  650. if (!mute
  651. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  652. logger.error('Unmuting audio requires user interaction');
  653. return;
  654. }
  655. // Not ready to modify track's state yet
  656. if (!this._localTracksInitialized) {
  657. // This will only modify base/media.audio.muted which is then synced
  658. // up with the track at the end of local tracks initialization.
  659. muteLocalAudio(mute);
  660. this.setAudioMuteStatus(mute);
  661. return;
  662. } else if (this.isLocalAudioMuted() === mute) {
  663. // NO-OP
  664. return;
  665. }
  666. if (!this.localAudio && !mute) {
  667. const maybeShowErrorDialog = error => {
  668. showUI && APP.store.dispatch(notifyMicError(error));
  669. };
  670. createLocalTracksF({ devices: [ 'audio' ] }, false)
  671. .then(([ audioTrack ]) => audioTrack)
  672. .catch(error => {
  673. maybeShowErrorDialog(error);
  674. // Rollback the audio muted status by using null track
  675. return null;
  676. })
  677. .then(audioTrack => this.useAudioStream(audioTrack));
  678. } else {
  679. muteLocalAudio(mute);
  680. }
  681. },
  682. /**
  683. * Returns whether local audio is muted or not.
  684. * @returns {boolean}
  685. */
  686. isLocalAudioMuted() {
  687. // If the tracks are not ready, read from base/media state
  688. return this._localTracksInitialized
  689. ? isLocalTrackMuted(
  690. APP.store.getState()['features/base/tracks'],
  691. MEDIA_TYPE.AUDIO)
  692. : Boolean(
  693. APP.store.getState()['features/base/media'].audio.muted);
  694. },
  695. /**
  696. * Simulates toolbar button click for audio mute. Used by shortcuts
  697. * and API.
  698. * @param {boolean} [showUI] when set to false will not display any error
  699. * dialogs in case of media permissions error.
  700. */
  701. toggleAudioMuted(showUI = true) {
  702. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  703. },
  704. /**
  705. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  706. * @param mute true for mute and false for unmute.
  707. * @param {boolean} [showUI] when set to false will not display any error
  708. * dialogs in case of media permissions error.
  709. */
  710. muteVideo(mute, showUI = true) {
  711. if (!mute
  712. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  713. logger.error('Unmuting video requires user interaction');
  714. return;
  715. }
  716. // If not ready to modify track's state yet adjust the base/media
  717. if (!this._localTracksInitialized) {
  718. // This will only modify base/media.video.muted which is then synced
  719. // up with the track at the end of local tracks initialization.
  720. muteLocalVideo(mute);
  721. this.setVideoMuteStatus(mute);
  722. return;
  723. } else if (this.isLocalVideoMuted() === mute) {
  724. // NO-OP
  725. return;
  726. }
  727. if (!this.localVideo && !mute) {
  728. const maybeShowErrorDialog = error => {
  729. showUI && APP.store.dispatch(notifyCameraError(error));
  730. };
  731. // Try to create local video if there wasn't any.
  732. // This handles the case when user joined with no video
  733. // (dismissed screen sharing screen or in audio only mode), but
  734. // decided to add it later on by clicking on muted video icon or
  735. // turning off the audio only mode.
  736. //
  737. // FIXME when local track creation is moved to react/redux
  738. // it should take care of the use case described above
  739. createLocalTracksF({ devices: [ 'video' ] }, false)
  740. .then(([ videoTrack ]) => videoTrack)
  741. .catch(error => {
  742. // FIXME should send some feedback to the API on error ?
  743. maybeShowErrorDialog(error);
  744. // Rollback the video muted status by using null track
  745. return null;
  746. })
  747. .then(videoTrack => this.useVideoStream(videoTrack));
  748. } else {
  749. // FIXME show error dialog if it fails (should be handled by react)
  750. muteLocalVideo(mute);
  751. }
  752. },
  753. /**
  754. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  755. * @param {boolean} [showUI] when set to false will not display any error
  756. * dialogs in case of media permissions error.
  757. */
  758. toggleVideoMuted(showUI = true) {
  759. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  760. },
  761. /**
  762. * Retrieve list of conference participants (without local user).
  763. * @returns {JitsiParticipant[]}
  764. */
  765. listMembers() {
  766. return room.getParticipants();
  767. },
  768. /**
  769. * Retrieve list of ids of conference participants (without local user).
  770. * @returns {string[]}
  771. */
  772. listMembersIds() {
  773. return room.getParticipants().map(p => p.getId());
  774. },
  775. /**
  776. * Checks whether the participant identified by id is a moderator.
  777. * @id id to search for participant
  778. * @return {boolean} whether the participant is moderator
  779. */
  780. isParticipantModerator(id) {
  781. const user = room.getParticipantById(id);
  782. return user && user.isModerator();
  783. },
  784. get membersCount() {
  785. return room.getParticipants().length + 1;
  786. },
  787. /**
  788. * Returns true if the callstats integration is enabled, otherwise returns
  789. * false.
  790. *
  791. * @returns true if the callstats integration is enabled, otherwise returns
  792. * false.
  793. */
  794. isCallstatsEnabled() {
  795. return room && room.isCallstatsEnabled();
  796. },
  797. /**
  798. * Sends the given feedback through CallStats if enabled.
  799. *
  800. * @param overallFeedback an integer between 1 and 5 indicating the
  801. * user feedback
  802. * @param detailedFeedback detailed feedback from the user. Not yet used
  803. */
  804. sendFeedback(overallFeedback, detailedFeedback) {
  805. return room.sendFeedback(overallFeedback, detailedFeedback);
  806. },
  807. /**
  808. * Get speaker stats that track total dominant speaker time.
  809. *
  810. * @returns {object} A hash with keys being user ids and values being the
  811. * library's SpeakerStats model used for calculating time as dominant
  812. * speaker.
  813. */
  814. getSpeakerStats() {
  815. return room.getSpeakerStats();
  816. },
  817. /**
  818. * Returns the connection times stored in the library.
  819. */
  820. getConnectionTimes() {
  821. return room.getConnectionTimes();
  822. },
  823. // used by torture currently
  824. isJoined() {
  825. return room && room.isJoined();
  826. },
  827. getConnectionState() {
  828. return room && room.getConnectionState();
  829. },
  830. /**
  831. * Obtains current P2P ICE connection state.
  832. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  833. * P2P connection
  834. */
  835. getP2PConnectionState() {
  836. return room && room.getP2PConnectionState();
  837. },
  838. /**
  839. * Starts P2P (for tests only)
  840. * @private
  841. */
  842. _startP2P() {
  843. try {
  844. room && room.startP2PSession();
  845. } catch (error) {
  846. logger.error('Start P2P failed', error);
  847. throw error;
  848. }
  849. },
  850. /**
  851. * Stops P2P (for tests only)
  852. * @private
  853. */
  854. _stopP2P() {
  855. try {
  856. room && room.stopP2PSession();
  857. } catch (error) {
  858. logger.error('Stop P2P failed', error);
  859. throw error;
  860. }
  861. },
  862. /**
  863. * Checks whether or not our connection is currently in interrupted and
  864. * reconnect attempts are in progress.
  865. *
  866. * @returns {boolean} true if the connection is in interrupted state or
  867. * false otherwise.
  868. */
  869. isConnectionInterrupted() {
  870. return room.isConnectionInterrupted();
  871. },
  872. /**
  873. * Obtains the local display name.
  874. * @returns {string|undefined}
  875. */
  876. getLocalDisplayName() {
  877. return getDisplayName(this.getMyUserId());
  878. },
  879. /**
  880. * Finds JitsiParticipant for given id.
  881. *
  882. * @param {string} id participant's identifier(MUC nickname).
  883. *
  884. * @returns {JitsiParticipant|null} participant instance for given id or
  885. * null if not found.
  886. */
  887. getParticipantById(id) {
  888. return room ? room.getParticipantById(id) : null;
  889. },
  890. /**
  891. * Get participant connection status for the participant.
  892. *
  893. * @param {string} id participant's identifier(MUC nickname)
  894. *
  895. * @returns {ParticipantConnectionStatus|null} the status of the participant
  896. * or null if no such participant is found or participant is the local user.
  897. */
  898. getParticipantConnectionStatus(id) {
  899. const participant = this.getParticipantById(id);
  900. return participant ? participant.getConnectionStatus() : null;
  901. },
  902. /**
  903. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  904. * the given <tt>id</tt>.
  905. *
  906. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  907. *
  908. * @return {string} the participant's display name or the default string if
  909. * absent.
  910. */
  911. getParticipantDisplayName(id) {
  912. const displayName = getDisplayName(id);
  913. if (displayName) {
  914. return displayName;
  915. }
  916. if (APP.conference.isLocalId(id)) {
  917. return APP.translation.generateTranslationHTML(
  918. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  919. }
  920. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  921. },
  922. getMyUserId() {
  923. return room && room.myUserId();
  924. },
  925. /**
  926. * Will be filled with values only when config.debug is enabled.
  927. * Its used by torture to check audio levels.
  928. */
  929. audioLevelsMap: {},
  930. /**
  931. * Returns the stored audio level (stored only if config.debug is enabled)
  932. * @param id the id for the user audio level to return (the id value is
  933. * returned for the participant using getMyUserId() method)
  934. */
  935. getPeerSSRCAudioLevel(id) {
  936. return this.audioLevelsMap[id];
  937. },
  938. /**
  939. * @return {number} the number of participants in the conference with at
  940. * least one track.
  941. */
  942. getNumberOfParticipantsWithTracks() {
  943. return room.getParticipants()
  944. .filter(p => p.getTracks().length > 0)
  945. .length;
  946. },
  947. /**
  948. * Returns the stats.
  949. */
  950. getStats() {
  951. return room.connectionQuality.getStats();
  952. },
  953. // end used by torture
  954. getLogs() {
  955. return room.getLogs();
  956. },
  957. /**
  958. * Download logs, a function that can be called from console while
  959. * debugging.
  960. * @param filename (optional) specify target filename
  961. */
  962. saveLogs(filename = 'meetlog.json') {
  963. // this can be called from console and will not have reference to this
  964. // that's why we reference the global var
  965. const logs = APP.conference.getLogs();
  966. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  967. const elem = document.createElement('a');
  968. elem.download = filename;
  969. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  970. elem.dataset.downloadurl
  971. = [ 'text/json', elem.download, elem.href ].join(':');
  972. elem.dispatchEvent(new MouseEvent('click', {
  973. view: window,
  974. bubbles: true,
  975. cancelable: false
  976. }));
  977. },
  978. /**
  979. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  980. * desire to keep room private to this instance and (2) the need of other
  981. * modules to send and receive commands to and from participants.
  982. * Eventually, this instance remains in control with respect to the
  983. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  984. * JitsiConference) is to be used in the implementation of the Command(s)
  985. * API of this instance.
  986. */
  987. commands: {
  988. /**
  989. * Known custom conference commands.
  990. */
  991. defaults: commands,
  992. /**
  993. * Receives notifications from other participants about commands aka
  994. * custom events (sent by sendCommand or sendCommandOnce methods).
  995. * @param command {String} the name of the command
  996. * @param handler {Function} handler for the command
  997. */
  998. addCommandListener() {
  999. // eslint-disable-next-line prefer-rest-params
  1000. room.addCommandListener(...arguments);
  1001. },
  1002. /**
  1003. * Removes command.
  1004. * @param name {String} the name of the command.
  1005. */
  1006. removeCommand() {
  1007. // eslint-disable-next-line prefer-rest-params
  1008. room.removeCommand(...arguments);
  1009. },
  1010. /**
  1011. * Sends command.
  1012. * @param name {String} the name of the command.
  1013. * @param values {Object} with keys and values that will be sent.
  1014. */
  1015. sendCommand() {
  1016. // eslint-disable-next-line prefer-rest-params
  1017. room.sendCommand(...arguments);
  1018. },
  1019. /**
  1020. * Sends command one time.
  1021. * @param name {String} the name of the command.
  1022. * @param values {Object} with keys and values that will be sent.
  1023. */
  1024. sendCommandOnce() {
  1025. // eslint-disable-next-line prefer-rest-params
  1026. room.sendCommandOnce(...arguments);
  1027. }
  1028. },
  1029. _createRoom(localTracks) {
  1030. room
  1031. = connection.initJitsiConference(
  1032. APP.conference.roomName,
  1033. this._getConferenceOptions());
  1034. APP.store.dispatch(conferenceWillJoin(room));
  1035. this._setLocalAudioVideoStreams(localTracks);
  1036. this._room = room; // FIXME do not use this
  1037. sendLocalParticipant(APP.store, room);
  1038. this._setupListeners();
  1039. },
  1040. /**
  1041. * Sets local video and audio streams.
  1042. * @param {JitsiLocalTrack[]} tracks=[]
  1043. * @returns {Promise[]}
  1044. * @private
  1045. */
  1046. _setLocalAudioVideoStreams(tracks = []) {
  1047. return tracks.map(track => {
  1048. if (track.isAudioTrack()) {
  1049. return this.useAudioStream(track);
  1050. } else if (track.isVideoTrack()) {
  1051. return this.useVideoStream(track);
  1052. }
  1053. logger.error(
  1054. 'Ignored not an audio nor a video track: ', track);
  1055. return Promise.resolve();
  1056. });
  1057. },
  1058. _getConferenceOptions() {
  1059. const options = config;
  1060. const nick = APP.store.getState()['features/base/settings'].displayName;
  1061. const { locationURL } = APP.store.getState()['features/base/connection'];
  1062. if (nick) {
  1063. options.displayName = nick;
  1064. }
  1065. options.applicationName = interfaceConfig.APP_NAME;
  1066. options.getWiFiStatsMethod = this._getWiFiStatsMethod;
  1067. options.confID = `${locationURL.host}${locationURL.pathname}`;
  1068. return options;
  1069. },
  1070. /**
  1071. * Returns the result of getWiFiStats from the global NS or does nothing
  1072. * (returns empty result).
  1073. * Fixes a concurrency problem where we need to pass a function when creating
  1074. * JitsiConference, but that method is added to the context later.
  1075. *
  1076. * @returns {Promise}
  1077. * @private
  1078. */
  1079. _getWiFiStatsMethod() {
  1080. const gloabalNS = getJitsiMeetGlobalNS();
  1081. return gloabalNS.getWiFiStats ? gloabalNS.getWiFiStats() : Promise.resolve('{}');
  1082. },
  1083. /**
  1084. * Start using provided video stream.
  1085. * Stops previous video stream.
  1086. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1087. * @returns {Promise}
  1088. */
  1089. useVideoStream(newStream) {
  1090. return new Promise((resolve, reject) => {
  1091. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1092. APP.store.dispatch(
  1093. replaceLocalTrack(this.localVideo, newStream, room))
  1094. .then(() => {
  1095. this.localVideo = newStream;
  1096. this._setSharingScreen(newStream);
  1097. if (newStream) {
  1098. APP.UI.addLocalVideoStream(newStream);
  1099. }
  1100. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1101. })
  1102. .then(resolve)
  1103. .catch(reject)
  1104. .then(onFinish);
  1105. });
  1106. });
  1107. },
  1108. /**
  1109. * Sets `this.isSharingScreen` depending on provided video stream.
  1110. * In case new screen sharing status is not equal previous one
  1111. * it updates desktop sharing buttons in UI
  1112. * and notifies external application.
  1113. *
  1114. * @param {JitsiLocalTrack} [newStream] new stream to use or null
  1115. * @private
  1116. * @returns {void}
  1117. */
  1118. _setSharingScreen(newStream) {
  1119. const wasSharingScreen = this.isSharingScreen;
  1120. this.isSharingScreen = newStream && newStream.videoType === 'desktop';
  1121. if (wasSharingScreen !== this.isSharingScreen) {
  1122. const details = {};
  1123. if (this.isSharingScreen) {
  1124. details.sourceType = newStream.sourceType;
  1125. }
  1126. APP.API.notifyScreenSharingStatusChanged(
  1127. this.isSharingScreen, details);
  1128. }
  1129. },
  1130. /**
  1131. * Start using provided audio stream.
  1132. * Stops previous audio stream.
  1133. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1134. * @returns {Promise}
  1135. */
  1136. useAudioStream(newStream) {
  1137. return new Promise((resolve, reject) => {
  1138. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1139. APP.store.dispatch(
  1140. replaceLocalTrack(this.localAudio, newStream, room))
  1141. .then(() => {
  1142. this.localAudio = newStream;
  1143. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1144. })
  1145. .then(resolve)
  1146. .catch(reject)
  1147. .then(onFinish);
  1148. });
  1149. });
  1150. },
  1151. /**
  1152. * Returns whether or not the conference is currently in audio only mode.
  1153. *
  1154. * @returns {boolean}
  1155. */
  1156. isAudioOnly() {
  1157. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1158. },
  1159. videoSwitchInProgress: false,
  1160. /**
  1161. * This fields stores a handler which will create a Promise which turns off
  1162. * the screen sharing and restores the previous video state (was there
  1163. * any video, before switching to screen sharing ? was it muted ?).
  1164. *
  1165. * Once called this fields is cleared to <tt>null</tt>.
  1166. * @type {Function|null}
  1167. */
  1168. _untoggleScreenSharing: null,
  1169. /**
  1170. * Creates a Promise which turns off the screen sharing and restores
  1171. * the previous state described by the arguments.
  1172. *
  1173. * This method is bound to the appropriate values, after switching to screen
  1174. * sharing and stored in {@link _untoggleScreenSharing}.
  1175. *
  1176. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1177. * used, before switching to screen sharing.
  1178. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1179. * switching to screen sharing.
  1180. * @return {Promise} resolved after the screen sharing is turned off, or
  1181. * rejected with some error (no idea what kind of error, possible GUM error)
  1182. * in case it fails.
  1183. * @private
  1184. */
  1185. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1186. this._untoggleScreenSharing = null;
  1187. this.videoSwitchInProgress = true;
  1188. const { receiver } = APP.remoteControl;
  1189. if (receiver) {
  1190. receiver.stop();
  1191. }
  1192. this._stopProxyConnection();
  1193. let promise = null;
  1194. if (didHaveVideo) {
  1195. promise = createLocalTracksF({ devices: [ 'video' ] })
  1196. .then(([ stream ]) => this.useVideoStream(stream))
  1197. .then(() => {
  1198. sendAnalytics(createScreenSharingEvent('stopped'));
  1199. logger.log('Screen sharing stopped, switching to video.');
  1200. if (!this.localVideo && wasVideoMuted) {
  1201. return Promise.reject('No local video to be muted!');
  1202. } else if (wasVideoMuted && this.localVideo) {
  1203. return this.localVideo.mute();
  1204. }
  1205. })
  1206. .catch(error => {
  1207. logger.error('failed to switch back to local video', error);
  1208. return this.useVideoStream(null).then(() =>
  1209. // Still fail with the original err
  1210. Promise.reject(error)
  1211. );
  1212. });
  1213. } else {
  1214. promise = this.useVideoStream(null);
  1215. }
  1216. return promise.then(
  1217. () => {
  1218. this.videoSwitchInProgress = false;
  1219. },
  1220. error => {
  1221. this.videoSwitchInProgress = false;
  1222. throw error;
  1223. });
  1224. },
  1225. /**
  1226. * Toggles between screen sharing and camera video if the toggle parameter
  1227. * is not specified and starts the procedure for obtaining new screen
  1228. * sharing/video track otherwise.
  1229. *
  1230. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1231. * obtained. If false - new video track will be obtain. If not specified -
  1232. * toggles between screen sharing and camera video.
  1233. * @param {Object} [options] - Screen sharing options that will be passed to
  1234. * createLocalTracks.
  1235. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1236. * sources that have to be displayed in the desktop picker window ('screen',
  1237. * 'window', etc.).
  1238. * @return {Promise.<T>}
  1239. */
  1240. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1241. if (this.videoSwitchInProgress) {
  1242. return Promise.reject('Switch in progress.');
  1243. }
  1244. if (!this.isDesktopSharingEnabled) {
  1245. return Promise.reject(
  1246. 'Cannot toggle screen sharing: not supported.');
  1247. }
  1248. if (this.isAudioOnly()) {
  1249. return Promise.reject('No screensharing in audio only mode');
  1250. }
  1251. if (toggle) {
  1252. return this._switchToScreenSharing(options);
  1253. }
  1254. return this._untoggleScreenSharing
  1255. ? this._untoggleScreenSharing()
  1256. : Promise.resolve();
  1257. },
  1258. /**
  1259. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1260. *
  1261. * @param {Object} [options] - Screen sharing options that will be passed to
  1262. * createLocalTracks.
  1263. * @param {Object} [options.desktopSharing]
  1264. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1265. * use instead of creating a new desktop stream.
  1266. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1267. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1268. * {@link JitsiTrackError}.
  1269. *
  1270. * @private
  1271. */
  1272. _createDesktopTrack(options = {}) {
  1273. let externalInstallation = false;
  1274. let DSExternalInstallationInProgress = false;
  1275. const didHaveVideo = Boolean(this.localVideo);
  1276. const wasVideoMuted = this.isLocalVideoMuted();
  1277. const getDesktopStreamPromise = options.desktopStream
  1278. ? Promise.resolve([ options.desktopStream ])
  1279. : createLocalTracksF({
  1280. desktopSharingSourceDevice: options.desktopSharingSources
  1281. ? null : config._desktopSharingSourceDevice,
  1282. desktopSharingSources: options.desktopSharingSources,
  1283. devices: [ 'desktop' ],
  1284. desktopSharingExtensionExternalInstallation: {
  1285. interval: 500,
  1286. checkAgain: () => DSExternalInstallationInProgress,
  1287. listener: (status, url) => {
  1288. switch (status) {
  1289. case 'waitingForExtension': {
  1290. DSExternalInstallationInProgress = true;
  1291. externalInstallation = true;
  1292. const listener = () => {
  1293. // Wait a little bit more just to be sure that
  1294. // we won't miss the extension installation
  1295. setTimeout(() => {
  1296. DSExternalInstallationInProgress = false;
  1297. },
  1298. 500);
  1299. APP.UI.removeListener(
  1300. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1301. listener);
  1302. };
  1303. APP.UI.addListener(
  1304. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1305. listener);
  1306. APP.UI.showExtensionExternalInstallationDialog(url);
  1307. break;
  1308. }
  1309. case 'extensionFound':
  1310. // Close the dialog.
  1311. externalInstallation && $.prompt.close();
  1312. break;
  1313. default:
  1314. // Unknown status
  1315. }
  1316. }
  1317. }
  1318. });
  1319. return getDesktopStreamPromise.then(([ desktopStream ]) => {
  1320. // Stores the "untoggle" handler which remembers whether was
  1321. // there any video before and whether was it muted.
  1322. this._untoggleScreenSharing
  1323. = this._turnScreenSharingOff
  1324. .bind(this, didHaveVideo, wasVideoMuted);
  1325. desktopStream.on(
  1326. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1327. () => {
  1328. // If the stream was stopped during screen sharing
  1329. // session then we should switch back to video.
  1330. this.isSharingScreen
  1331. && this._untoggleScreenSharing
  1332. && this._untoggleScreenSharing();
  1333. }
  1334. );
  1335. // close external installation dialog on success.
  1336. externalInstallation && $.prompt.close();
  1337. return desktopStream;
  1338. }, error => {
  1339. DSExternalInstallationInProgress = false;
  1340. // close external installation dialog on success.
  1341. externalInstallation && $.prompt.close();
  1342. throw error;
  1343. });
  1344. },
  1345. /**
  1346. * Tries to switch to the screensharing mode by disposing camera stream and
  1347. * replacing it with a desktop one.
  1348. *
  1349. * @param {Object} [options] - Screen sharing options that will be passed to
  1350. * createLocalTracks.
  1351. *
  1352. * @return {Promise} - A Promise resolved if the operation succeeds or
  1353. * rejected with some unknown type of error in case it fails. Promise will
  1354. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1355. *
  1356. * @private
  1357. */
  1358. _switchToScreenSharing(options = {}) {
  1359. if (this.videoSwitchInProgress) {
  1360. return Promise.reject('Switch in progress.');
  1361. }
  1362. this.videoSwitchInProgress = true;
  1363. return this._createDesktopTrack(options)
  1364. .then(stream => this.useVideoStream(stream))
  1365. .then(() => {
  1366. this.videoSwitchInProgress = false;
  1367. sendAnalytics(createScreenSharingEvent('started'));
  1368. logger.log('Screen sharing started');
  1369. })
  1370. .catch(error => {
  1371. this.videoSwitchInProgress = false;
  1372. // Pawel: With this call I'm trying to preserve the original
  1373. // behaviour although it is not clear why would we "untoggle"
  1374. // on failure. I suppose it was to restore video in case there
  1375. // was some problem during "this.useVideoStream(desktopStream)".
  1376. // It's important to note that the handler will not be available
  1377. // if we fail early on trying to get desktop media (which makes
  1378. // sense, because the camera video is still being used, so
  1379. // nothing to "untoggle").
  1380. if (this._untoggleScreenSharing) {
  1381. this._untoggleScreenSharing();
  1382. }
  1383. // FIXME the code inside of _handleScreenSharingError is
  1384. // asynchronous, but does not return a Promise and is not part
  1385. // of the current Promise chain.
  1386. this._handleScreenSharingError(error);
  1387. return Promise.reject(error);
  1388. });
  1389. },
  1390. /**
  1391. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1392. * trying to create screensharing track. It will either do nothing if
  1393. * the dialog was canceled on user's request or display inline installation
  1394. * dialog and ask the user to install the extension, once the extension is
  1395. * installed it will switch the conference to screensharing. The last option
  1396. * is that an unrecoverable error dialog will be displayed.
  1397. * @param {JitsiTrackError} error - The error returned by
  1398. * {@link _createDesktopTrack} Promise.
  1399. * @private
  1400. */
  1401. _handleScreenSharingError(error) {
  1402. if (error.name === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1403. return;
  1404. }
  1405. logger.error('failed to share local desktop', error);
  1406. if (error.name
  1407. === JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1408. // If start with screen sharing the extension will fail to install
  1409. // (if not found), because the request has been triggered by the
  1410. // script. Show a dialog which asks user to click "install" and try
  1411. // again switching to the screen sharing.
  1412. APP.UI.showExtensionInlineInstallationDialog(
  1413. () => {
  1414. // eslint-disable-next-line no-empty-function
  1415. this.toggleScreenSharing().catch(() => {});
  1416. }
  1417. );
  1418. return;
  1419. }
  1420. // Handling:
  1421. // JitsiTrackErrors.PERMISSION_DENIED
  1422. // JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1423. // JitsiTrackErrors.CONSTRAINT_FAILED
  1424. // JitsiTrackErrors.GENERAL
  1425. // and any other
  1426. let descriptionKey;
  1427. let titleKey;
  1428. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1429. // in FF the only option for user is to deny access temporary or
  1430. // permanently and we only receive permission_denied
  1431. // we always show some info cause in case of permanently, no info
  1432. // shown will be bad experience
  1433. //
  1434. // TODO: detect interval between requesting permissions and received
  1435. // error, this way we can detect user interaction which will have
  1436. // longer delay
  1437. if (JitsiMeetJS.util.browser.isFirefox()) {
  1438. descriptionKey
  1439. = 'dialog.screenSharingFirefoxPermissionDeniedError';
  1440. titleKey = 'dialog.screenSharingFirefoxPermissionDeniedTitle';
  1441. } else {
  1442. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1443. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1444. }
  1445. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1446. descriptionKey = 'dialog.cameraConstraintFailedError';
  1447. titleKey = 'deviceError.cameraError';
  1448. } else {
  1449. descriptionKey = 'dialog.screenSharingFailedToInstall';
  1450. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1451. }
  1452. APP.UI.messageHandler.showError({
  1453. descriptionKey,
  1454. titleKey
  1455. });
  1456. },
  1457. /**
  1458. * Setup interaction between conference and UI.
  1459. */
  1460. _setupListeners() {
  1461. // add local streams when joined to the conference
  1462. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1463. this._onConferenceJoined();
  1464. });
  1465. room.on(
  1466. JitsiConferenceEvents.CONFERENCE_LEFT,
  1467. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1468. room.on(
  1469. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1470. (authEnabled, authLogin) =>
  1471. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1472. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1473. user => APP.UI.onUserFeaturesChanged(user));
  1474. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1475. // The logic shared between RN and web.
  1476. commonUserJoinedHandling(APP.store, room, user);
  1477. if (user.isHidden()) {
  1478. return;
  1479. }
  1480. logger.log(`USER ${id} connnected:`, user);
  1481. APP.UI.addUser(user);
  1482. // check the roles for the new user and reflect them
  1483. APP.UI.updateUserRole(user);
  1484. });
  1485. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1486. // The logic shared between RN and web.
  1487. commonUserLeftHandling(APP.store, room, user);
  1488. if (user.isHidden()) {
  1489. return;
  1490. }
  1491. logger.log(`USER ${id} LEFT:`, user);
  1492. APP.UI.onSharedVideoStop(id);
  1493. });
  1494. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1495. APP.store.dispatch(participantPresenceChanged(id, status));
  1496. const user = room.getParticipantById(id);
  1497. if (user) {
  1498. APP.UI.updateUserStatus(user, status);
  1499. }
  1500. });
  1501. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1502. if (this.isLocalId(id)) {
  1503. logger.info(`My role changed, new role: ${role}`);
  1504. APP.store.dispatch(localParticipantRoleChanged(role));
  1505. if (this.isModerator !== room.isModerator()) {
  1506. this.isModerator = room.isModerator();
  1507. APP.UI.updateLocalRole(room.isModerator());
  1508. }
  1509. } else {
  1510. APP.store.dispatch(participantRoleChanged(id, role));
  1511. const user = room.getParticipantById(id);
  1512. if (user) {
  1513. APP.UI.updateUserRole(user);
  1514. }
  1515. }
  1516. });
  1517. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1518. if (!track || track.isLocal()) {
  1519. return;
  1520. }
  1521. APP.store.dispatch(trackAdded(track));
  1522. });
  1523. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1524. if (!track || track.isLocal()) {
  1525. return;
  1526. }
  1527. APP.store.dispatch(trackRemoved(track));
  1528. });
  1529. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1530. let newLvl = lvl;
  1531. if (this.isLocalId(id)
  1532. && this.localAudio && this.localAudio.isMuted()) {
  1533. newLvl = 0;
  1534. }
  1535. if (config.debug) {
  1536. this.audioLevelsMap[id] = newLvl;
  1537. if (config.debugAudioLevels) {
  1538. logger.log(`AudioLevel:${id}/${newLvl}`);
  1539. }
  1540. }
  1541. APP.UI.setAudioLevel(id, newLvl);
  1542. });
  1543. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1544. if (participantThatMutedUs) {
  1545. APP.store.dispatch(participantMutedUs(participantThatMutedUs));
  1546. }
  1547. });
  1548. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1549. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1550. room.on(
  1551. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1552. (leavingIds, enteringIds) =>
  1553. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1554. room.on(
  1555. JitsiConferenceEvents.P2P_STATUS,
  1556. (jitsiConference, p2p) =>
  1557. APP.store.dispatch(p2pStatusChanged(p2p)));
  1558. room.on(
  1559. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1560. (id, connectionStatus) => APP.store.dispatch(
  1561. participantConnectionStatusChanged(id, connectionStatus)));
  1562. room.on(
  1563. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1564. id => APP.store.dispatch(dominantSpeakerChanged(id, room)));
  1565. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1566. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1567. JitsiParticipantConnectionStatus.INTERRUPTED));
  1568. });
  1569. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1570. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1571. JitsiParticipantConnectionStatus.ACTIVE));
  1572. });
  1573. room.on(
  1574. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1575. (id, displayName) => {
  1576. const formattedDisplayName
  1577. = getNormalizedDisplayName(displayName);
  1578. APP.store.dispatch(participantUpdated({
  1579. conference: room,
  1580. id,
  1581. name: formattedDisplayName
  1582. }));
  1583. APP.API.notifyDisplayNameChanged(id, {
  1584. displayName: formattedDisplayName,
  1585. formattedDisplayName:
  1586. appendSuffix(
  1587. formattedDisplayName
  1588. || interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME)
  1589. });
  1590. APP.UI.changeDisplayName(id, formattedDisplayName);
  1591. }
  1592. );
  1593. room.on(
  1594. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1595. (id, botType) => {
  1596. APP.store.dispatch(participantUpdated({
  1597. conference: room,
  1598. id,
  1599. botType
  1600. }));
  1601. }
  1602. );
  1603. room.on(
  1604. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1605. (...args) => APP.store.dispatch(endpointMessageReceived(...args)));
  1606. room.on(
  1607. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1608. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1609. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1610. room.setLocalParticipantProperty(
  1611. 'remoteControlSessionStatus',
  1612. isActive
  1613. );
  1614. APP.UI.setLocalRemoteControlActiveChanged();
  1615. });
  1616. /* eslint-disable max-params */
  1617. room.on(
  1618. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1619. (participant, name, oldValue, newValue) => {
  1620. switch (name) {
  1621. case 'remoteControlSessionStatus':
  1622. APP.UI.setRemoteControlActiveStatus(
  1623. participant.getId(),
  1624. newValue);
  1625. break;
  1626. default:
  1627. // ignore
  1628. }
  1629. });
  1630. room.on(JitsiConferenceEvents.KICKED, participant => {
  1631. APP.UI.hideStats();
  1632. APP.store.dispatch(kickedOut(room, participant));
  1633. // FIXME close
  1634. });
  1635. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1636. APP.store.dispatch(participantKicked(kicker, kicked));
  1637. });
  1638. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1639. APP.store.dispatch(suspendDetected());
  1640. });
  1641. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1642. this.muteAudio(muted);
  1643. });
  1644. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1645. this.muteVideo(muted);
  1646. });
  1647. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1648. ({ value }) => {
  1649. APP.UI.initEtherpad(value);
  1650. }
  1651. );
  1652. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1653. this.changeLocalEmail.bind(this));
  1654. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1655. APP.store.dispatch(participantUpdated({
  1656. conference: room,
  1657. id: from,
  1658. email: data.value
  1659. }));
  1660. });
  1661. room.addCommandListener(
  1662. this.commands.defaults.AVATAR_URL,
  1663. (data, from) => {
  1664. APP.store.dispatch(
  1665. participantUpdated({
  1666. conference: room,
  1667. id: from,
  1668. avatarURL: data.value
  1669. }));
  1670. });
  1671. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1672. (data, from) => {
  1673. APP.store.dispatch(
  1674. participantUpdated({
  1675. conference: room,
  1676. id: from,
  1677. avatarID: data.value
  1678. }));
  1679. });
  1680. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1681. this.changeLocalDisplayName.bind(this));
  1682. room.on(
  1683. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1684. ({ audio, video }) => {
  1685. APP.store.dispatch(
  1686. onStartMutedPolicyChanged(audio, video));
  1687. }
  1688. );
  1689. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1690. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1691. && APP.UI.notifyInitiallyMuted();
  1692. });
  1693. room.on(
  1694. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1695. APP.store.dispatch(dataChannelOpened());
  1696. }
  1697. );
  1698. // call hangup
  1699. APP.UI.addListener(UIEvents.HANGUP, () => {
  1700. this.hangup(true);
  1701. });
  1702. // logout
  1703. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1704. AuthHandler.logout(room).then(url => {
  1705. if (url) {
  1706. UIUtil.redirect(url);
  1707. } else {
  1708. this.hangup(true);
  1709. }
  1710. });
  1711. });
  1712. /* eslint-disable max-params */
  1713. APP.UI.addListener(
  1714. UIEvents.RESOLUTION_CHANGED,
  1715. (id, oldResolution, newResolution, delay) => {
  1716. sendAnalytics(createStreamSwitchDelayEvent(
  1717. {
  1718. 'old_resolution': oldResolution,
  1719. 'new_resolution': newResolution,
  1720. value: delay
  1721. }));
  1722. });
  1723. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1724. AuthHandler.authenticate(room);
  1725. });
  1726. APP.UI.addListener(
  1727. UIEvents.VIDEO_DEVICE_CHANGED,
  1728. cameraDeviceId => {
  1729. const videoWasMuted = this.isLocalVideoMuted();
  1730. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1731. createLocalTracksF({
  1732. devices: [ 'video' ],
  1733. cameraDeviceId,
  1734. micDeviceId: null
  1735. })
  1736. .then(([ stream ]) => {
  1737. // if we are in audio only mode or video was muted before
  1738. // changing device, then mute
  1739. if (this.isAudioOnly() || videoWasMuted) {
  1740. return stream.mute()
  1741. .then(() => stream);
  1742. }
  1743. return stream;
  1744. })
  1745. .then(stream => {
  1746. // if we are screen sharing we do not want to stop it
  1747. if (this.isSharingScreen) {
  1748. return Promise.resolve();
  1749. }
  1750. return this.useVideoStream(stream);
  1751. })
  1752. .then(() => {
  1753. logger.log('switched local video device');
  1754. this._updateVideoDeviceId();
  1755. })
  1756. .catch(err => {
  1757. APP.store.dispatch(notifyCameraError(err));
  1758. });
  1759. }
  1760. );
  1761. APP.UI.addListener(
  1762. UIEvents.AUDIO_DEVICE_CHANGED,
  1763. micDeviceId => {
  1764. const audioWasMuted = this.isLocalAudioMuted();
  1765. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  1766. createLocalTracksF({
  1767. devices: [ 'audio' ],
  1768. cameraDeviceId: null,
  1769. micDeviceId
  1770. })
  1771. .then(([ stream ]) => {
  1772. // if audio was muted before changing the device, mute
  1773. // with the new device
  1774. if (audioWasMuted) {
  1775. return stream.mute()
  1776. .then(() => stream);
  1777. }
  1778. return stream;
  1779. })
  1780. .then(stream => this.useAudioStream(stream))
  1781. .then(() => {
  1782. logger.log('switched local audio device');
  1783. this._updateAudioDeviceId();
  1784. })
  1785. .catch(err => {
  1786. APP.store.dispatch(notifyMicError(err));
  1787. });
  1788. }
  1789. );
  1790. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1791. // FIXME On web video track is stored both in redux and in
  1792. // 'localVideo' field, video is attempted to be unmuted twice when
  1793. // turning off the audio only mode. This will crash the app with
  1794. // 'unmute operation is already in progress'.
  1795. // Because there's no logic in redux about creating new track in
  1796. // case unmute when not track exists the things have to go through
  1797. // muteVideo logic in such case.
  1798. const tracks = APP.store.getState()['features/base/tracks'];
  1799. const isTrackInRedux
  1800. = Boolean(
  1801. tracks.find(
  1802. track => track.jitsiTrack
  1803. && track.jitsiTrack.getType() === 'video'));
  1804. if (!isTrackInRedux) {
  1805. this.muteVideo(audioOnly);
  1806. }
  1807. // Immediately update the UI by having remote videos and the large
  1808. // video update themselves instead of waiting for some other event
  1809. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1810. // There is no guarantee another event will trigger the update
  1811. // immediately and in all situations, for example because a remote
  1812. // participant is having connection trouble so no status changes.
  1813. APP.UI.updateAllVideos();
  1814. });
  1815. APP.UI.addListener(
  1816. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1817. );
  1818. /* eslint-disable max-params */
  1819. APP.UI.addListener(
  1820. UIEvents.UPDATE_SHARED_VIDEO,
  1821. (url, state, time, isMuted, volume) => {
  1822. /* eslint-enable max-params */
  1823. // send start and stop commands once, and remove any updates
  1824. // that had left
  1825. if (state === 'stop'
  1826. || state === 'start'
  1827. || state === 'playing') {
  1828. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1829. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1830. value: url,
  1831. attributes: {
  1832. state,
  1833. time,
  1834. muted: isMuted,
  1835. volume
  1836. }
  1837. });
  1838. } else {
  1839. // in case of paused, in order to allow late users to join
  1840. // paused
  1841. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1842. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1843. value: url,
  1844. attributes: {
  1845. state,
  1846. time,
  1847. muted: isMuted,
  1848. volume
  1849. }
  1850. });
  1851. }
  1852. APP.store.dispatch(setSharedVideoStatus(state));
  1853. });
  1854. room.addCommandListener(
  1855. this.commands.defaults.SHARED_VIDEO,
  1856. ({ value, attributes }, id) => {
  1857. if (attributes.state === 'stop') {
  1858. APP.UI.onSharedVideoStop(id, attributes);
  1859. } else if (attributes.state === 'start') {
  1860. APP.UI.onSharedVideoStart(id, value, attributes);
  1861. } else if (attributes.state === 'playing'
  1862. || attributes.state === 'pause') {
  1863. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1864. }
  1865. });
  1866. },
  1867. /**
  1868. * Cleanups local conference on suspend.
  1869. */
  1870. onSuspendDetected() {
  1871. // After wake up, we will be in a state where conference is left
  1872. // there will be dialog shown to user.
  1873. // We do not want video/audio as we show an overlay and after it
  1874. // user need to rejoin or close, while waking up we can detect
  1875. // camera wakeup as a problem with device.
  1876. // We also do not care about device change, which happens
  1877. // on resume after suspending PC.
  1878. if (this.deviceChangeListener) {
  1879. JitsiMeetJS.mediaDevices.removeEventListener(
  1880. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1881. this.deviceChangeListener);
  1882. }
  1883. this.localVideo = null;
  1884. this.localAudio = null;
  1885. },
  1886. /**
  1887. * Callback invoked when the conference has been successfully joined.
  1888. * Initializes the UI and various other features.
  1889. *
  1890. * @private
  1891. * @returns {void}
  1892. */
  1893. _onConferenceJoined() {
  1894. APP.UI.initConference();
  1895. APP.keyboardshortcut.init();
  1896. APP.store.dispatch(conferenceJoined(room));
  1897. const displayName
  1898. = APP.store.getState()['features/base/settings'].displayName;
  1899. APP.UI.changeDisplayName('localVideoContainer', displayName);
  1900. },
  1901. /**
  1902. * Adds any room listener.
  1903. * @param {string} eventName one of the JitsiConferenceEvents
  1904. * @param {Function} listener the function to be called when the event
  1905. * occurs
  1906. */
  1907. addConferenceListener(eventName, listener) {
  1908. room.on(eventName, listener);
  1909. },
  1910. /**
  1911. * Removes any room listener.
  1912. * @param {string} eventName one of the JitsiConferenceEvents
  1913. * @param {Function} listener the listener to be removed.
  1914. */
  1915. removeConferenceListener(eventName, listener) {
  1916. room.off(eventName, listener);
  1917. },
  1918. /**
  1919. * Updates the list of current devices.
  1920. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  1921. * @private
  1922. * @returns {Promise}
  1923. */
  1924. _initDeviceList(setDeviceListChangeHandler = false) {
  1925. const { mediaDevices } = JitsiMeetJS;
  1926. if (mediaDevices.isDeviceListAvailable()
  1927. && mediaDevices.isDeviceChangeAvailable()) {
  1928. if (setDeviceListChangeHandler) {
  1929. this.deviceChangeListener = devices =>
  1930. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  1931. mediaDevices.addEventListener(
  1932. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1933. this.deviceChangeListener);
  1934. }
  1935. const { dispatch } = APP.store;
  1936. return dispatch(getAvailableDevices())
  1937. .then(devices => {
  1938. // Ugly way to synchronize real device IDs with local
  1939. // storage and settings menu. This is a workaround until
  1940. // getConstraints() method will be implemented in browsers.
  1941. this._updateAudioDeviceId();
  1942. this._updateVideoDeviceId();
  1943. APP.UI.onAvailableDevicesChanged(devices);
  1944. });
  1945. }
  1946. return Promise.resolve();
  1947. },
  1948. /**
  1949. * Updates the settings for the currently used video device, extracting
  1950. * the device id from the used track.
  1951. * @private
  1952. */
  1953. _updateVideoDeviceId() {
  1954. if (this.localVideo
  1955. && this.localVideo.videoType === 'camera') {
  1956. APP.store.dispatch(updateSettings({
  1957. cameraDeviceId: this.localVideo.getDeviceId()
  1958. }));
  1959. }
  1960. },
  1961. /**
  1962. * Updates the settings for the currently used audio device, extracting
  1963. * the device id from the used track.
  1964. * @private
  1965. */
  1966. _updateAudioDeviceId() {
  1967. if (this.localAudio) {
  1968. APP.store.dispatch(updateSettings({
  1969. micDeviceId: this.localAudio.getDeviceId()
  1970. }));
  1971. }
  1972. },
  1973. /**
  1974. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1975. * handle change of available media devices.
  1976. * @private
  1977. * @param {MediaDeviceInfo[]} devices
  1978. * @returns {Promise}
  1979. */
  1980. _onDeviceListChanged(devices) {
  1981. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1982. APP.store.dispatch(updateDeviceList(devices));
  1983. const newDevices
  1984. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1985. devices,
  1986. this.isSharingScreen,
  1987. this.localVideo,
  1988. this.localAudio);
  1989. const promises = [];
  1990. const audioWasMuted = this.isLocalAudioMuted();
  1991. const videoWasMuted = this.isLocalVideoMuted();
  1992. const requestedInput = {
  1993. audio: Boolean(newDevices.audioinput),
  1994. video: Boolean(newDevices.videoinput)
  1995. };
  1996. if (typeof newDevices.audiooutput !== 'undefined') {
  1997. const { dispatch } = APP.store;
  1998. const setAudioOutputPromise
  1999. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2000. .catch(); // Just ignore any errors in catch block.
  2001. promises.push(setAudioOutputPromise);
  2002. }
  2003. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2004. // simpler):
  2005. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2006. // will return a stream using the old default device.
  2007. if (requestedInput.audio && this.localAudio) {
  2008. this.localAudio.stopStream();
  2009. }
  2010. if (requestedInput.video && this.localVideo) {
  2011. this.localVideo.stopStream();
  2012. }
  2013. // Let's handle unknown/non-preferred devices
  2014. const newAvailDevices
  2015. = APP.store.getState()['features/base/devices'].availableDevices;
  2016. let newAudioDevices = [];
  2017. let oldAudioDevices = [];
  2018. if (typeof newDevices.audiooutput === 'undefined') {
  2019. newAudioDevices = newAvailDevices.audioOutput;
  2020. oldAudioDevices = oldDevices.audioOutput;
  2021. }
  2022. if (!requestedInput.audio) {
  2023. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2024. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2025. }
  2026. // check for audio
  2027. if (newAudioDevices.length > 0) {
  2028. APP.store.dispatch(
  2029. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2030. }
  2031. // check for video
  2032. if (!requestedInput.video) {
  2033. APP.store.dispatch(
  2034. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2035. }
  2036. promises.push(
  2037. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2038. createLocalTracksF,
  2039. newDevices.videoinput,
  2040. newDevices.audioinput)
  2041. .then(tracks => {
  2042. // If audio or video muted before, or we unplugged current
  2043. // device and selected new one, then mute new track.
  2044. const muteSyncPromises = tracks.map(track => {
  2045. if ((track.isVideoTrack() && videoWasMuted)
  2046. || (track.isAudioTrack() && audioWasMuted)) {
  2047. return track.mute();
  2048. }
  2049. return Promise.resolve();
  2050. });
  2051. return Promise.all(muteSyncPromises)
  2052. .then(() =>
  2053. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2054. if (requestedInput[mediaType]) {
  2055. const useStream
  2056. = mediaType === 'audio'
  2057. ? this.useAudioStream.bind(this)
  2058. : this.useVideoStream.bind(this);
  2059. // Use the new stream or null if we failed to obtain it.
  2060. return useStream(tracks.find(track => track.getType() === mediaType) || null)
  2061. .then(() => {
  2062. mediaType === 'audio'
  2063. ? this._updateAudioDeviceId()
  2064. : this._updateVideoDeviceId();
  2065. });
  2066. }
  2067. return Promise.resolve();
  2068. })));
  2069. })
  2070. .then(() => {
  2071. // Log and sync known mute state.
  2072. if (audioWasMuted) {
  2073. sendAnalytics(createTrackMutedEvent(
  2074. 'audio',
  2075. 'device list changed'));
  2076. logger.log('Audio mute: device list changed');
  2077. muteLocalAudio(true);
  2078. }
  2079. if (!this.isSharingScreen && videoWasMuted) {
  2080. sendAnalytics(createTrackMutedEvent(
  2081. 'video',
  2082. 'device list changed'));
  2083. logger.log('Video mute: device list changed');
  2084. muteLocalVideo(true);
  2085. }
  2086. }));
  2087. return Promise.all(promises)
  2088. .then(() => {
  2089. APP.UI.onAvailableDevicesChanged(devices);
  2090. });
  2091. },
  2092. /**
  2093. * Determines whether or not the audio button should be enabled.
  2094. */
  2095. updateAudioIconEnabled() {
  2096. const audioMediaDevices
  2097. = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2098. const audioDeviceCount
  2099. = audioMediaDevices ? audioMediaDevices.length : 0;
  2100. // The audio functionality is considered available if there are any
  2101. // audio devices detected or if the local audio stream already exists.
  2102. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2103. logger.debug(
  2104. `Microphone button enabled: ${available}`,
  2105. `local audio: ${this.localAudio}`,
  2106. `audio devices: ${audioMediaDevices}`,
  2107. `device count: ${audioDeviceCount}`);
  2108. APP.store.dispatch(setAudioAvailable(available));
  2109. APP.API.notifyAudioAvailabilityChanged(available);
  2110. },
  2111. /**
  2112. * Determines whether or not the video button should be enabled.
  2113. */
  2114. updateVideoIconEnabled() {
  2115. const videoMediaDevices
  2116. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2117. const videoDeviceCount
  2118. = videoMediaDevices ? videoMediaDevices.length : 0;
  2119. // The video functionality is considered available if there are any
  2120. // video devices detected or if there is local video stream already
  2121. // active which could be either screensharing stream or a video track
  2122. // created before the permissions were rejected (through browser
  2123. // config).
  2124. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2125. logger.debug(
  2126. `Camera button enabled: ${available}`,
  2127. `local video: ${this.localVideo}`,
  2128. `video devices: ${videoMediaDevices}`,
  2129. `device count: ${videoDeviceCount}`);
  2130. APP.store.dispatch(setVideoAvailable(available));
  2131. APP.API.notifyVideoAvailabilityChanged(available);
  2132. },
  2133. /**
  2134. * Disconnect from the conference and optionally request user feedback.
  2135. * @param {boolean} [requestFeedback=false] if user feedback should be
  2136. * requested
  2137. */
  2138. hangup(requestFeedback = false) {
  2139. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2140. this._stopProxyConnection();
  2141. APP.store.dispatch(destroyLocalTracks());
  2142. this._localTracksInitialized = false;
  2143. this.localVideo = null;
  2144. this.localAudio = null;
  2145. // Remove unnecessary event listeners from firing callbacks.
  2146. if (this.deviceChangeListener) {
  2147. JitsiMeetJS.mediaDevices.removeEventListener(
  2148. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2149. this.deviceChangeListener);
  2150. }
  2151. APP.UI.removeAllListeners();
  2152. APP.remoteControl.removeAllListeners();
  2153. let requestFeedbackPromise;
  2154. if (requestFeedback) {
  2155. requestFeedbackPromise
  2156. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2157. // false because the thank you dialog shouldn't be displayed
  2158. .catch(() => Promise.resolve(false));
  2159. } else {
  2160. requestFeedbackPromise = Promise.resolve(true);
  2161. }
  2162. // All promises are returning Promise.resolve to make Promise.all to
  2163. // be resolved when both Promises are finished. Otherwise Promise.all
  2164. // will reject on first rejected Promise and we can redirect the page
  2165. // before all operations are done.
  2166. Promise.all([
  2167. requestFeedbackPromise,
  2168. this.leaveRoomAndDisconnect()
  2169. ]).then(values => {
  2170. this._room = undefined;
  2171. room = undefined;
  2172. APP.API.notifyReadyToClose();
  2173. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2174. });
  2175. },
  2176. /**
  2177. * Leaves the room and calls JitsiConnection.disconnect.
  2178. *
  2179. * @returns {Promise}
  2180. */
  2181. leaveRoomAndDisconnect() {
  2182. APP.store.dispatch(conferenceWillLeave(room));
  2183. if (room.isJoined()) {
  2184. return room.leave().then(disconnect, disconnect);
  2185. }
  2186. return disconnect();
  2187. },
  2188. /**
  2189. * Changes the email for the local user
  2190. * @param email {string} the new email
  2191. */
  2192. changeLocalEmail(email = '') {
  2193. const localParticipant = getLocalParticipant(APP.store.getState());
  2194. const formattedEmail = String(email).trim();
  2195. if (formattedEmail === localParticipant.email) {
  2196. return;
  2197. }
  2198. const localId = localParticipant.id;
  2199. APP.store.dispatch(participantUpdated({
  2200. // XXX Only the local participant is allowed to update without
  2201. // stating the JitsiConference instance (i.e. participant property
  2202. // `conference` for a remote participant) because the local
  2203. // participant is uniquely identified by the very fact that there is
  2204. // only one local participant.
  2205. id: localId,
  2206. local: true,
  2207. email: formattedEmail
  2208. }));
  2209. APP.store.dispatch(updateSettings({
  2210. email: formattedEmail
  2211. }));
  2212. APP.API.notifyEmailChanged(localId, {
  2213. email: formattedEmail
  2214. });
  2215. sendData(commands.EMAIL, formattedEmail);
  2216. },
  2217. /**
  2218. * Changes the avatar url for the local user
  2219. * @param url {string} the new url
  2220. */
  2221. changeLocalAvatarUrl(url = '') {
  2222. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2223. const formattedUrl = String(url).trim();
  2224. if (formattedUrl === avatarURL) {
  2225. return;
  2226. }
  2227. APP.store.dispatch(participantUpdated({
  2228. // XXX Only the local participant is allowed to update without
  2229. // stating the JitsiConference instance (i.e. participant property
  2230. // `conference` for a remote participant) because the local
  2231. // participant is uniquely identified by the very fact that there is
  2232. // only one local participant.
  2233. id,
  2234. local: true,
  2235. avatarURL: formattedUrl
  2236. }));
  2237. APP.store.dispatch(updateSettings({
  2238. avatarURL: formattedUrl
  2239. }));
  2240. sendData(commands.AVATAR_URL, url);
  2241. },
  2242. /**
  2243. * Sends a message via the data channel.
  2244. * @param {string} to the id of the endpoint that should receive the
  2245. * message. If "" - the message will be sent to all participants.
  2246. * @param {object} payload the payload of the message.
  2247. * @throws NetworkError or InvalidStateError or Error if the operation
  2248. * fails.
  2249. */
  2250. sendEndpointMessage(to, payload) {
  2251. room.sendEndpointMessage(to, payload);
  2252. },
  2253. /**
  2254. * Adds new listener.
  2255. * @param {String} eventName the name of the event
  2256. * @param {Function} listener the listener.
  2257. */
  2258. addListener(eventName, listener) {
  2259. eventEmitter.addListener(eventName, listener);
  2260. },
  2261. /**
  2262. * Removes listener.
  2263. * @param {String} eventName the name of the event that triggers the
  2264. * listener
  2265. * @param {Function} listener the listener.
  2266. */
  2267. removeListener(eventName, listener) {
  2268. eventEmitter.removeListener(eventName, listener);
  2269. },
  2270. /**
  2271. * Changes the display name for the local user
  2272. * @param nickname {string} the new display name
  2273. */
  2274. changeLocalDisplayName(nickname = '') {
  2275. const formattedNickname = getNormalizedDisplayName(nickname);
  2276. const { id, name } = getLocalParticipant(APP.store.getState());
  2277. if (formattedNickname === name) {
  2278. return;
  2279. }
  2280. APP.store.dispatch(participantUpdated({
  2281. // XXX Only the local participant is allowed to update without
  2282. // stating the JitsiConference instance (i.e. participant property
  2283. // `conference` for a remote participant) because the local
  2284. // participant is uniquely identified by the very fact that there is
  2285. // only one local participant.
  2286. id,
  2287. local: true,
  2288. name: formattedNickname
  2289. }));
  2290. APP.store.dispatch(updateSettings({
  2291. displayName: formattedNickname
  2292. }));
  2293. if (room) {
  2294. APP.UI.changeDisplayName(id, formattedNickname);
  2295. }
  2296. },
  2297. /**
  2298. * Returns the desktop sharing source id or undefined if the desktop sharing
  2299. * is not active at the moment.
  2300. *
  2301. * @returns {string|undefined} - The source id. If the track is not desktop
  2302. * track or the source id is not available, undefined will be returned.
  2303. */
  2304. getDesktopSharingSourceId() {
  2305. return this.localVideo.sourceId;
  2306. },
  2307. /**
  2308. * Returns the desktop sharing source type or undefined if the desktop
  2309. * sharing is not active at the moment.
  2310. *
  2311. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2312. * not desktop track or the source type is not available, undefined will be
  2313. * returned.
  2314. */
  2315. getDesktopSharingSourceType() {
  2316. return this.localVideo.sourceType;
  2317. },
  2318. /**
  2319. * Callback invoked by the external api create or update a direct connection
  2320. * from the local client to an external client.
  2321. *
  2322. * @param {Object} event - The object containing information that should be
  2323. * passed to the {@code ProxyConnectionService}.
  2324. * @returns {void}
  2325. */
  2326. onProxyConnectionEvent(event) {
  2327. if (!this._proxyConnection) {
  2328. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2329. /**
  2330. * Pass the {@code JitsiConnection} instance which will be used
  2331. * to fetch TURN credentials.
  2332. */
  2333. jitsiConnection: APP.connection,
  2334. /**
  2335. * The proxy connection feature is currently tailored towards
  2336. * taking a proxied video stream and showing it as a local
  2337. * desktop screen.
  2338. */
  2339. convertVideoToDesktop: true,
  2340. /**
  2341. * Callback invoked when the connection has been closed
  2342. * automatically. Triggers cleanup of screensharing if active.
  2343. *
  2344. * @returns {void}
  2345. */
  2346. onConnectionClosed: () => {
  2347. if (this._untoggleScreenSharing) {
  2348. this._untoggleScreenSharing();
  2349. }
  2350. },
  2351. /**
  2352. * Callback invoked to pass messages from the local client back
  2353. * out to the external client.
  2354. *
  2355. * @param {string} peerJid - The jid of the intended recipient
  2356. * of the message.
  2357. * @param {Object} data - The message that should be sent. For
  2358. * screensharing this is an iq.
  2359. * @returns {void}
  2360. */
  2361. onSendMessage: (peerJid, data) =>
  2362. APP.API.sendProxyConnectionEvent({
  2363. data,
  2364. to: peerJid
  2365. }),
  2366. /**
  2367. * Callback invoked when the remote peer of the proxy connection
  2368. * has provided a video stream, intended to be used as a local
  2369. * desktop stream.
  2370. *
  2371. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2372. * stream to use as a local desktop stream.
  2373. * @returns {void}
  2374. */
  2375. onRemoteStream: desktopStream => {
  2376. if (desktopStream.videoType !== 'desktop') {
  2377. logger.warn('Received a non-desktop stream to proxy.');
  2378. desktopStream.dispose();
  2379. return;
  2380. }
  2381. this.toggleScreenSharing(undefined, { desktopStream });
  2382. }
  2383. });
  2384. }
  2385. this._proxyConnection.processMessage(event);
  2386. },
  2387. /**
  2388. * Sets the video muted status.
  2389. *
  2390. * @param {boolean} muted - New muted status.
  2391. */
  2392. setVideoMuteStatus(muted) {
  2393. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2394. APP.API.notifyVideoMutedStatusChanged(muted);
  2395. },
  2396. /**
  2397. * Sets the audio muted status.
  2398. *
  2399. * @param {boolean} muted - New muted status.
  2400. */
  2401. setAudioMuteStatus(muted) {
  2402. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2403. APP.API.notifyAudioMutedStatusChanged(muted);
  2404. },
  2405. /**
  2406. * Dispatches the passed in feedback for submission. The submitted score
  2407. * should be a number inclusively between 1 through 5, or -1 for no score.
  2408. *
  2409. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2410. * score.
  2411. * @param {string} message - An optional message to attach to the feedback
  2412. * in addition to the score.
  2413. * @returns {void}
  2414. */
  2415. submitFeedback(score = -1, message = '') {
  2416. if (score === -1 || (score >= 1 && score <= 5)) {
  2417. APP.store.dispatch(submitFeedback(score, message, room));
  2418. }
  2419. },
  2420. /**
  2421. * Terminates any proxy screensharing connection that is active.
  2422. *
  2423. * @private
  2424. * @returns {void}
  2425. */
  2426. _stopProxyConnection() {
  2427. if (this._proxyConnection) {
  2428. this._proxyConnection.stop();
  2429. }
  2430. this._proxyConnection = null;
  2431. }
  2432. };