Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 90KB

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