Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 84KB

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