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

conference.js 96KB

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