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

conference.js 84KB

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