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

conference.js 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. //FIXME:
  4. import createRoomLocker from './modules/UI/authentication/RoomLocker';
  5. //FIXME:
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import ConnectionQuality from './modules/connectionquality/connectionquality';
  8. import Recorder from './modules/recorder/Recorder';
  9. import CQEvents from './service/connectionquality/CQEvents';
  10. import UIEvents from './service/UI/UIEvents';
  11. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  12. const ConnectionEvents = JitsiMeetJS.events.connection;
  13. const ConnectionErrors = JitsiMeetJS.errors.connection;
  14. const ConferenceEvents = JitsiMeetJS.events.conference;
  15. const ConferenceErrors = JitsiMeetJS.errors.conference;
  16. const TrackEvents = JitsiMeetJS.events.track;
  17. const TrackErrors = JitsiMeetJS.errors.track;
  18. let room, connection, localAudio, localVideo, roomLocker;
  19. /**
  20. * Indicates whether the connection is interrupted or not.
  21. */
  22. let connectionIsInterrupted = false;
  23. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  24. /**
  25. * Known custom conference commands.
  26. */
  27. const commands = {
  28. CONNECTION_QUALITY: "stats",
  29. EMAIL: "email",
  30. AVATAR_URL: "avatar-url",
  31. ETHERPAD: "etherpad",
  32. SHARED_VIDEO: "shared-video",
  33. CUSTOM_ROLE: "custom-role"
  34. };
  35. /**
  36. * Open Connection. When authentication failed it shows auth dialog.
  37. * @param roomName the room name to use
  38. * @returns Promise<JitsiConnection>
  39. */
  40. function connect(roomName) {
  41. return openConnection({retry: true, roomName: roomName})
  42. .catch(function (err) {
  43. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  44. APP.UI.notifyTokenAuthFailed();
  45. } else {
  46. APP.UI.notifyConnectionFailed(err);
  47. }
  48. throw err;
  49. });
  50. }
  51. /**
  52. * Creates local media tracks and connects to room. Will show error
  53. * dialogs in case if accessing local microphone and/or camera failed. Will
  54. * show guidance overlay for users on how to give access to camera and/or
  55. * microphone,
  56. * @param {string} roomName
  57. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  58. */
  59. function createInitialLocalTracksAndConnect(roomName) {
  60. let audioAndVideoError,
  61. audioOnlyError;
  62. JitsiMeetJS.mediaDevices.addEventListener(
  63. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  64. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  65. // First try to retrieve both audio and video.
  66. let tryCreateLocalTracks = createLocalTracks(
  67. { devices: ['audio', 'video'] }, true)
  68. .catch(err => {
  69. // If failed then try to retrieve only audio.
  70. audioAndVideoError = err;
  71. return createLocalTracks({ devices: ['audio'] }, true);
  72. })
  73. .catch(err => {
  74. // If audio failed too then just return empty array for tracks.
  75. audioOnlyError = err;
  76. return [];
  77. });
  78. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  79. .then(([tracks, con]) => {
  80. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  81. if (audioAndVideoError) {
  82. if (audioOnlyError) {
  83. // If both requests for 'audio' + 'video' and 'audio' only
  84. // failed, we assume that there is some problems with user's
  85. // microphone and show corresponding dialog.
  86. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  87. } else {
  88. // If request for 'audio' + 'video' failed, but request for
  89. // 'audio' only was OK, we assume that we had problems with
  90. // camera and show corresponding dialog.
  91. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  92. }
  93. }
  94. return [tracks, con];
  95. });
  96. }
  97. /**
  98. * Share data to other users.
  99. * @param command the command
  100. * @param {string} value new value
  101. */
  102. function sendData (command, value) {
  103. room.removeCommand(command);
  104. room.sendCommand(command, {value: value});
  105. }
  106. /**
  107. * Get user nickname by user id.
  108. * @param {string} id user id
  109. * @returns {string?} user nickname or undefined if user is unknown.
  110. */
  111. function getDisplayName (id) {
  112. if (APP.conference.isLocalId(id)) {
  113. return APP.settings.getDisplayName();
  114. }
  115. let participant = room.getParticipantById(id);
  116. if (participant && participant.getDisplayName()) {
  117. return participant.getDisplayName();
  118. }
  119. }
  120. /**
  121. * Mute or unmute local audio stream if it exists.
  122. * @param {boolean} muted if audio stream should be muted or unmuted.
  123. * @param {boolean} indicates if this local audio mute was a result of user
  124. * interaction
  125. *
  126. */
  127. function muteLocalAudio (muted, userInteraction) {
  128. if (!localAudio) {
  129. return;
  130. }
  131. if (muted) {
  132. localAudio.mute().then(function(value) {},
  133. function(value) {
  134. console.warn('Audio Mute was rejected:', value);
  135. }
  136. );
  137. } else {
  138. localAudio.unmute().then(function(value) {},
  139. function(value) {
  140. console.warn('Audio unmute was rejected:', value);
  141. }
  142. );
  143. }
  144. }
  145. /**
  146. * Mute or unmute local video stream if it exists.
  147. * @param {boolean} muted if video stream should be muted or unmuted.
  148. */
  149. function muteLocalVideo (muted) {
  150. if (!localVideo) {
  151. return;
  152. }
  153. if (muted) {
  154. localVideo.mute().then(function(value) {},
  155. function(value) {
  156. console.warn('Video mute was rejected:', value);
  157. }
  158. );
  159. } else {
  160. localVideo.unmute().then(function(value) {},
  161. function(value) {
  162. console.warn('Video unmute was rejected:', value);
  163. }
  164. );
  165. }
  166. }
  167. /**
  168. * Check if the welcome page is enabled and redirects to it.
  169. */
  170. function maybeRedirectToWelcomePage() {
  171. if (!config.enableWelcomePage) {
  172. return;
  173. }
  174. // redirect to welcome page
  175. setTimeout(() => {
  176. APP.settings.setWelcomePageEnabled(true);
  177. window.location.pathname = "/";
  178. }, 3000);
  179. }
  180. /**
  181. * Executes connection.disconnect and shows the feedback dialog
  182. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  183. * @returns Promise.
  184. */
  185. function disconnectAndShowFeedback(requestFeedback) {
  186. APP.UI.hideRingOverLay();
  187. connection.disconnect();
  188. APP.API.notifyConferenceLeft(APP.conference.roomName);
  189. if (requestFeedback) {
  190. return APP.UI.requestFeedback();
  191. } else {
  192. return Promise.resolve();
  193. }
  194. }
  195. /**
  196. * Disconnect from the conference and optionally request user feedback.
  197. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  198. */
  199. function hangup (requestFeedback = false) {
  200. const errCallback = (f, err) => {
  201. console.error('Error occurred during hanging up: ', err);
  202. return f();
  203. };
  204. const disconnect = disconnectAndShowFeedback.bind(null, requestFeedback);
  205. APP.conference._room.leave()
  206. .then(disconnect)
  207. .catch(errCallback.bind(null, disconnect))
  208. .then(maybeRedirectToWelcomePage)
  209. .catch(errCallback.bind(null, maybeRedirectToWelcomePage));
  210. }
  211. /**
  212. * Create local tracks of specified types.
  213. * @param {Object} options
  214. * @param {string[]} options.devices - required track types
  215. * ('audio', 'video' etc.)
  216. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  217. * undefined - one from settings will be used
  218. * @param {string|null} (options.micDeviceId) - microphone device id, if
  219. * undefined - one from settings will be used
  220. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  221. * for gUM permission prompt
  222. * @returns {Promise<JitsiLocalTrack[]>}
  223. */
  224. function createLocalTracks (options, checkForPermissionPrompt) {
  225. options || (options = {});
  226. return JitsiMeetJS
  227. .createLocalTracks({
  228. // copy array to avoid mutations inside library
  229. devices: options.devices.slice(0),
  230. resolution: config.resolution,
  231. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  232. options.cameraDeviceId === null
  233. ? APP.settings.getCameraDeviceId()
  234. : options.cameraDeviceId,
  235. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  236. options.micDeviceId === null
  237. ? APP.settings.getMicDeviceId()
  238. : options.micDeviceId,
  239. // adds any ff fake device settings if any
  240. firefox_fake_device: config.firefox_fake_device
  241. }, checkForPermissionPrompt)
  242. .catch(function (err) {
  243. console.error(
  244. 'failed to create local tracks', options.devices, err);
  245. return Promise.reject(err);
  246. });
  247. }
  248. /**
  249. * Changes the email for the local user
  250. * @param email {string} the new email
  251. */
  252. function changeLocalEmail(email = '') {
  253. email = email.trim();
  254. if (email === APP.settings.getEmail()) {
  255. return;
  256. }
  257. APP.settings.setEmail(email);
  258. APP.UI.setUserEmail(room.myUserId(), email);
  259. sendData(commands.EMAIL, email);
  260. }
  261. /**
  262. * Changes the local avatar url for the local user
  263. * @param avatarUrl {string} the new avatar url
  264. */
  265. function changeLocalAvatarUrl(avatarUrl = '') {
  266. avatarUrl = avatarUrl.trim();
  267. if (avatarUrl === APP.settings.getAvatarUrl()) {
  268. return;
  269. }
  270. APP.settings.setAvatarUrl(avatarUrl);
  271. APP.UI.setUserAvatarUrl(room.myUserId(), avatarUrl);
  272. sendData(commands.AVATAR_URL, avatarUrl);
  273. }
  274. /**
  275. * Changes the display name for the local user
  276. * @param nickname {string} the new display name
  277. */
  278. function changeLocalDisplayName(nickname = '') {
  279. nickname = nickname.trim();
  280. if (nickname === APP.settings.getDisplayName()) {
  281. return;
  282. }
  283. APP.settings.setDisplayName(nickname);
  284. room.setDisplayName(nickname);
  285. APP.UI.changeDisplayName(APP.conference.getMyUserId(), nickname);
  286. }
  287. class ConferenceConnector {
  288. constructor(resolve, reject) {
  289. this._resolve = resolve;
  290. this._reject = reject;
  291. this.reconnectTimeout = null;
  292. room.on(ConferenceEvents.CONFERENCE_JOINED,
  293. this._handleConferenceJoined.bind(this));
  294. room.on(ConferenceEvents.CONFERENCE_FAILED,
  295. this._onConferenceFailed.bind(this));
  296. room.on(ConferenceEvents.CONFERENCE_ERROR,
  297. this._onConferenceError.bind(this));
  298. }
  299. _handleConferenceFailed(err, msg) {
  300. this._unsubscribe();
  301. this._reject(err);
  302. }
  303. _onConferenceFailed(err, ...params) {
  304. console.error('CONFERENCE FAILED:', err, ...params);
  305. APP.UI.hideRingOverLay();
  306. switch (err) {
  307. // room is locked by the password
  308. case ConferenceErrors.PASSWORD_REQUIRED:
  309. APP.UI.markRoomLocked(true);
  310. roomLocker.requirePassword().then(function () {
  311. room.join(roomLocker.password);
  312. });
  313. break;
  314. case ConferenceErrors.CONNECTION_ERROR:
  315. {
  316. let [msg] = params;
  317. APP.UI.notifyConnectionFailed(msg);
  318. }
  319. break;
  320. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  321. APP.UI.notifyBridgeDown();
  322. break;
  323. // not enough rights to create conference
  324. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  325. // schedule reconnect to check if someone else created the room
  326. this.reconnectTimeout = setTimeout(function () {
  327. room.join();
  328. }, 5000);
  329. // notify user that auth is required
  330. AuthHandler.requireAuth(room, roomLocker.password);
  331. break;
  332. case ConferenceErrors.RESERVATION_ERROR:
  333. {
  334. let [code, msg] = params;
  335. APP.UI.notifyReservationError(code, msg);
  336. }
  337. break;
  338. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  339. APP.UI.notifyGracefulShutdown();
  340. break;
  341. case ConferenceErrors.JINGLE_FATAL_ERROR:
  342. APP.UI.notifyInternalError();
  343. break;
  344. case ConferenceErrors.CONFERENCE_DESTROYED:
  345. {
  346. let [reason] = params;
  347. APP.UI.hideStats();
  348. APP.UI.notifyConferenceDestroyed(reason);
  349. }
  350. break;
  351. case ConferenceErrors.FOCUS_DISCONNECTED:
  352. {
  353. let [focus, retrySec] = params;
  354. APP.UI.notifyFocusDisconnected(focus, retrySec);
  355. }
  356. break;
  357. case ConferenceErrors.FOCUS_LEFT:
  358. room.leave().then(() => connection.disconnect());
  359. APP.UI.notifyFocusLeft();
  360. break;
  361. case ConferenceErrors.CONFERENCE_MAX_USERS:
  362. connection.disconnect();
  363. APP.UI.notifyMaxUsersLimitReached();
  364. break;
  365. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  366. window.location.reload();
  367. break;
  368. default:
  369. this._handleConferenceFailed(err, ...params);
  370. }
  371. }
  372. _onConferenceError(err, ...params) {
  373. console.error('CONFERENCE Error:', err, params);
  374. switch (err) {
  375. case ConferenceErrors.CHAT_ERROR:
  376. {
  377. let [code, msg] = params;
  378. APP.UI.showChatError(code, msg);
  379. }
  380. break;
  381. default:
  382. console.error("Unknown error.");
  383. }
  384. }
  385. _unsubscribe() {
  386. room.off(
  387. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  388. room.off(
  389. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  390. if (this.reconnectTimeout !== null) {
  391. clearTimeout(this.reconnectTimeout);
  392. }
  393. AuthHandler.closeAuth();
  394. }
  395. _handleConferenceJoined() {
  396. this._unsubscribe();
  397. this._resolve();
  398. }
  399. connect() {
  400. room.join();
  401. }
  402. }
  403. export default {
  404. isModerator: false,
  405. audioMuted: false,
  406. videoMuted: false,
  407. isSharingScreen: false,
  408. isDesktopSharingEnabled: false,
  409. /*
  410. * Whether the local "raisedHand" flag is on.
  411. */
  412. isHandRaised: false,
  413. /*
  414. * Whether the local participant is the dominant speaker in the conference.
  415. */
  416. isDominantSpeaker: false,
  417. /**
  418. * Open new connection and join to the conference.
  419. * @param {object} options
  420. * @param {string} roomName name of the conference
  421. * @returns {Promise}
  422. */
  423. init(options) {
  424. this.roomName = options.roomName;
  425. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  426. // attaches global error handler, if there is already one, respect it
  427. if(JitsiMeetJS.getGlobalOnErrorHandler){
  428. var oldOnErrorHandler = window.onerror;
  429. window.onerror = function (message, source, lineno, colno, error) {
  430. JitsiMeetJS.getGlobalOnErrorHandler(
  431. message, source, lineno, colno, error);
  432. if(oldOnErrorHandler)
  433. oldOnErrorHandler(message, source, lineno, colno, error);
  434. };
  435. var oldOnUnhandledRejection = window.onunhandledrejection;
  436. window.onunhandledrejection = function(event) {
  437. JitsiMeetJS.getGlobalOnErrorHandler(
  438. null, null, null, null, event.reason);
  439. if(oldOnUnhandledRejection)
  440. oldOnUnhandledRejection(event);
  441. };
  442. }
  443. return JitsiMeetJS.init(config)
  444. .then(() => createInitialLocalTracksAndConnect(options.roomName))
  445. .then(([tracks, con]) => {
  446. console.log('initialized with %s local tracks', tracks.length);
  447. APP.connection = connection = con;
  448. this._createRoom(tracks);
  449. this.isDesktopSharingEnabled =
  450. JitsiMeetJS.isDesktopSharingEnabled();
  451. // if user didn't give access to mic or camera or doesn't have
  452. // them at all, we disable corresponding toolbar buttons
  453. if (!tracks.find((t) => t.isAudioTrack())) {
  454. APP.UI.disableMicrophoneButton();
  455. }
  456. if (!tracks.find((t) => t.isVideoTrack())) {
  457. APP.UI.disableCameraButton();
  458. }
  459. this._initDeviceList();
  460. if (config.iAmRecorder)
  461. this.recorder = new Recorder();
  462. // XXX The API will take care of disconnecting from the XMPP
  463. // server (and, thus, leaving the room) on unload.
  464. return new Promise((resolve, reject) => {
  465. (new ConferenceConnector(resolve, reject)).connect();
  466. });
  467. });
  468. },
  469. /**
  470. * Check if id is id of the local user.
  471. * @param {string} id id to check
  472. * @returns {boolean}
  473. */
  474. isLocalId (id) {
  475. return this.getMyUserId() === id;
  476. },
  477. /**
  478. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  479. * @param mute true for mute and false for unmute.
  480. */
  481. muteAudio (mute) {
  482. muteLocalAudio(mute);
  483. },
  484. /**
  485. * Returns whether local audio is muted or not.
  486. * @returns {boolean}
  487. */
  488. isLocalAudioMuted() {
  489. return this.audioMuted;
  490. },
  491. /**
  492. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  493. */
  494. toggleAudioMuted () {
  495. this.muteAudio(!this.audioMuted);
  496. },
  497. /**
  498. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  499. * @param mute true for mute and false for unmute.
  500. */
  501. muteVideo (mute) {
  502. muteLocalVideo(mute);
  503. },
  504. /**
  505. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  506. */
  507. toggleVideoMuted () {
  508. this.muteVideo(!this.videoMuted);
  509. },
  510. /**
  511. * Retrieve list of conference participants (without local user).
  512. * @returns {JitsiParticipant[]}
  513. */
  514. listMembers () {
  515. return room.getParticipants();
  516. },
  517. /**
  518. * Retrieve list of ids of conference participants (without local user).
  519. * @returns {string[]}
  520. */
  521. listMembersIds () {
  522. return room.getParticipants().map(p => p.getId());
  523. },
  524. /**
  525. * Checks whether the participant identified by id is a moderator.
  526. * @id id to search for participant
  527. * @return {boolean} whether the participant is moderator
  528. */
  529. isParticipantModerator (id) {
  530. let user = room.getParticipantById(id);
  531. return user && user.isModerator();
  532. },
  533. /**
  534. * Check if SIP is supported.
  535. * @returns {boolean}
  536. */
  537. sipGatewayEnabled () {
  538. return room.isSIPCallingSupported();
  539. },
  540. get membersCount () {
  541. return room.getParticipants().length + 1;
  542. },
  543. /**
  544. * Returns true if the callstats integration is enabled, otherwise returns
  545. * false.
  546. *
  547. * @returns true if the callstats integration is enabled, otherwise returns
  548. * false.
  549. */
  550. isCallstatsEnabled () {
  551. return room.isCallstatsEnabled();
  552. },
  553. /**
  554. * Sends the given feedback through CallStats if enabled.
  555. *
  556. * @param overallFeedback an integer between 1 and 5 indicating the
  557. * user feedback
  558. * @param detailedFeedback detailed feedback from the user. Not yet used
  559. */
  560. sendFeedback (overallFeedback, detailedFeedback) {
  561. return room.sendFeedback (overallFeedback, detailedFeedback);
  562. },
  563. // used by torture currently
  564. isJoined () {
  565. return this._room
  566. && this._room.isJoined();
  567. },
  568. getConnectionState () {
  569. return this._room
  570. && this._room.getConnectionState();
  571. },
  572. getMyUserId () {
  573. return this._room
  574. && this._room.myUserId();
  575. },
  576. /**
  577. * Indicates if recording is supported in this conference.
  578. */
  579. isRecordingSupported() {
  580. return this._room && this._room.isRecordingSupported();
  581. },
  582. /**
  583. * Returns the recording state or undefined if the room is not defined.
  584. */
  585. getRecordingState() {
  586. return (this._room) ? this._room.getRecordingState() : undefined;
  587. },
  588. /**
  589. * Will be filled with values only when config.debug is enabled.
  590. * Its used by torture to check audio levels.
  591. */
  592. audioLevelsMap: {},
  593. /**
  594. * Returns the stored audio level (stored only if config.debug is enabled)
  595. * @param id the id for the user audio level to return (the id value is
  596. * returned for the participant using getMyUserId() method)
  597. */
  598. getPeerSSRCAudioLevel (id) {
  599. return this.audioLevelsMap[id];
  600. },
  601. /**
  602. * @return {number} the number of participants in the conference with at
  603. * least one track.
  604. */
  605. getNumberOfParticipantsWithTracks() {
  606. return this._room.getParticipants()
  607. .filter((p) => p.getTracks().length > 0)
  608. .length;
  609. },
  610. /**
  611. * Returns the stats.
  612. */
  613. getStats() {
  614. return ConnectionQuality.getStats();
  615. },
  616. // end used by torture
  617. getLogs () {
  618. return room.getLogs();
  619. },
  620. /**
  621. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  622. * desire to keep room private to this instance and (2) the need of other
  623. * modules to send and receive commands to and from participants.
  624. * Eventually, this instance remains in control with respect to the
  625. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  626. * JitsiConference) is to be used in the implementation of the Command(s)
  627. * API of this instance.
  628. */
  629. commands: {
  630. /**
  631. * Known custom conference commands.
  632. */
  633. defaults: commands,
  634. /**
  635. * Receives notifications from other participants about commands aka
  636. * custom events (sent by sendCommand or sendCommandOnce methods).
  637. * @param command {String} the name of the command
  638. * @param handler {Function} handler for the command
  639. */
  640. addCommandListener () {
  641. room.addCommandListener.apply(room, arguments);
  642. },
  643. /**
  644. * Removes command.
  645. * @param name {String} the name of the command.
  646. */
  647. removeCommand () {
  648. room.removeCommand.apply(room, arguments);
  649. },
  650. /**
  651. * Sends command.
  652. * @param name {String} the name of the command.
  653. * @param values {Object} with keys and values that will be sent.
  654. */
  655. sendCommand () {
  656. room.sendCommand.apply(room, arguments);
  657. },
  658. /**
  659. * Sends command one time.
  660. * @param name {String} the name of the command.
  661. * @param values {Object} with keys and values that will be sent.
  662. */
  663. sendCommandOnce () {
  664. room.sendCommandOnce.apply(room, arguments);
  665. }
  666. },
  667. _createRoom (localTracks) {
  668. room = connection.initJitsiConference(APP.conference.roomName,
  669. this._getConferenceOptions());
  670. this._setLocalAudioVideoStreams(localTracks);
  671. roomLocker = createRoomLocker(room);
  672. this._room = room; // FIXME do not use this
  673. let email = APP.settings.getEmail();
  674. email && sendData(this.commands.defaults.EMAIL, email);
  675. let avatarUrl = APP.settings.getAvatarUrl();
  676. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  677. avatarUrl);
  678. let nick = APP.settings.getDisplayName();
  679. if (config.useNicks && !nick) {
  680. nick = APP.UI.askForNickname();
  681. APP.settings.setDisplayName(nick);
  682. }
  683. nick && room.setDisplayName(nick);
  684. this._setupListeners();
  685. },
  686. /**
  687. * Sets local video and audio streams.
  688. * @param {JitsiLocalTrack[]} tracks=[]
  689. * @returns {Promise[]}
  690. * @private
  691. */
  692. _setLocalAudioVideoStreams(tracks = []) {
  693. return tracks.map(track => {
  694. if (track.isAudioTrack()) {
  695. return this.useAudioStream(track);
  696. } else if (track.isVideoTrack()) {
  697. return this.useVideoStream(track);
  698. } else {
  699. console.error(
  700. "Ignored not an audio nor a video track: ", track);
  701. return Promise.resolve();
  702. }
  703. });
  704. },
  705. _getConferenceOptions() {
  706. let options = config;
  707. if(config.enableRecording && !config.recordingType) {
  708. options.recordingType = (config.hosts &&
  709. (typeof config.hosts.jirecon != "undefined"))?
  710. "jirecon" : "colibri";
  711. }
  712. return options;
  713. },
  714. /**
  715. * Start using provided video stream.
  716. * Stops previous video stream.
  717. * @param {JitsiLocalTrack} [stream] new stream to use or null
  718. * @returns {Promise}
  719. */
  720. useVideoStream (stream) {
  721. let promise = Promise.resolve();
  722. if (localVideo) {
  723. // this calls room.removeTrack internally
  724. // so we don't need to remove it manually
  725. promise = localVideo.dispose();
  726. }
  727. localVideo = stream;
  728. return promise.then(function () {
  729. if (stream) {
  730. return room.addTrack(stream);
  731. }
  732. }).then(() => {
  733. if (stream) {
  734. this.videoMuted = stream.isMuted();
  735. this.isSharingScreen = stream.videoType === 'desktop';
  736. APP.UI.addLocalStream(stream);
  737. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  738. } else {
  739. this.videoMuted = false;
  740. this.isSharingScreen = false;
  741. }
  742. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  743. APP.UI.updateDesktopSharingButtons();
  744. });
  745. },
  746. /**
  747. * Start using provided audio stream.
  748. * Stops previous audio stream.
  749. * @param {JitsiLocalTrack} [stream] new stream to use or null
  750. * @returns {Promise}
  751. */
  752. useAudioStream (stream) {
  753. let promise = Promise.resolve();
  754. if (localAudio) {
  755. // this calls room.removeTrack internally
  756. // so we don't need to remove it manually
  757. promise = localAudio.dispose();
  758. }
  759. localAudio = stream;
  760. return promise.then(function () {
  761. if (stream) {
  762. return room.addTrack(stream);
  763. }
  764. }).then(() => {
  765. if (stream) {
  766. this.audioMuted = stream.isMuted();
  767. APP.UI.addLocalStream(stream);
  768. } else {
  769. this.audioMuted = false;
  770. }
  771. APP.UI.enableMicrophoneButton();
  772. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  773. });
  774. },
  775. videoSwitchInProgress: false,
  776. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  777. if (this.videoSwitchInProgress) {
  778. console.warn("Switch in progress.");
  779. return;
  780. }
  781. if (!this.isDesktopSharingEnabled) {
  782. console.warn("Cannot toggle screen sharing: not supported.");
  783. return;
  784. }
  785. this.videoSwitchInProgress = true;
  786. if (shareScreen) {
  787. createLocalTracks({ devices: ['desktop'] }).then(([stream]) => {
  788. stream.on(
  789. TrackEvents.LOCAL_TRACK_STOPPED,
  790. () => {
  791. // if stream was stopped during screensharing session
  792. // then we should switch to video
  793. // otherwise we stopped it because we already switched
  794. // to video, so nothing to do here
  795. if (this.isSharingScreen) {
  796. this.toggleScreenSharing(false);
  797. }
  798. }
  799. );
  800. return this.useVideoStream(stream);
  801. }).then(() => {
  802. this.videoSwitchInProgress = false;
  803. console.log('sharing local desktop');
  804. }).catch((err) => {
  805. this.videoSwitchInProgress = false;
  806. this.toggleScreenSharing(false);
  807. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  808. return;
  809. }
  810. console.error('failed to share local desktop', err);
  811. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  812. APP.UI.showExtensionRequiredDialog(
  813. config.desktopSharingFirefoxExtensionURL
  814. );
  815. return;
  816. }
  817. // Handling:
  818. // TrackErrors.PERMISSION_DENIED
  819. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  820. // TrackErrors.GENERAL
  821. // and any other
  822. let dialogTxt;
  823. let dialogTitle;
  824. if (err.name === TrackErrors.PERMISSION_DENIED) {
  825. dialogTxt = APP.translation.generateTranslationHTML(
  826. "dialog.screenSharingPermissionDeniedError");
  827. dialogTitle = APP.translation.generateTranslationHTML(
  828. "dialog.error");
  829. } else {
  830. dialogTxt = APP.translation.generateTranslationHTML(
  831. "dialog.failtoinstall");
  832. dialogTitle = APP.translation.generateTranslationHTML(
  833. "dialog.permissionDenied");
  834. }
  835. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  836. });
  837. } else {
  838. createLocalTracks({ devices: ['video'] }).then(
  839. ([stream]) => this.useVideoStream(stream)
  840. ).then(() => {
  841. this.videoSwitchInProgress = false;
  842. console.log('sharing local video');
  843. }).catch((err) => {
  844. this.useVideoStream(null);
  845. this.videoSwitchInProgress = false;
  846. console.error('failed to share local video', err);
  847. });
  848. }
  849. },
  850. /**
  851. * Setup interaction between conference and UI.
  852. */
  853. _setupListeners () {
  854. // add local streams when joined to the conference
  855. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  856. APP.UI.mucJoined();
  857. APP.API.notifyConferenceJoined(APP.conference.roomName);
  858. connectionIsInterrupted = false;
  859. APP.UI.markVideoInterrupted(false);
  860. });
  861. room.on(
  862. ConferenceEvents.AUTH_STATUS_CHANGED,
  863. function (authEnabled, authLogin) {
  864. APP.UI.updateAuthInfo(authEnabled, authLogin);
  865. }
  866. );
  867. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  868. if (user.isHidden())
  869. return;
  870. console.log('USER %s connnected', id, user);
  871. APP.API.notifyUserJoined(id);
  872. APP.UI.addUser(id, user.getDisplayName());
  873. // check the roles for the new user and reflect them
  874. APP.UI.updateUserRole(user);
  875. });
  876. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  877. console.log('USER %s LEFT', id, user);
  878. APP.API.notifyUserLeft(id);
  879. APP.UI.removeUser(id, user.getDisplayName());
  880. APP.UI.onSharedVideoStop(id);
  881. });
  882. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  883. if (this.isLocalId(id)) {
  884. console.info(`My role changed, new role: ${role}`);
  885. this.isModerator = room.isModerator();
  886. APP.UI.updateLocalRole(room.isModerator());
  887. } else {
  888. let user = room.getParticipantById(id);
  889. if (user) {
  890. APP.UI.updateUserRole(user);
  891. }
  892. }
  893. });
  894. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  895. if(!track || track.isLocal())
  896. return;
  897. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  898. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  899. });
  900. APP.UI.addRemoteStream(track);
  901. });
  902. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  903. if(!track || track.isLocal())
  904. return;
  905. APP.UI.removeRemoteStream(track);
  906. });
  907. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  908. if(!track)
  909. return;
  910. const handler = (track.getType() === "audio")?
  911. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  912. let id;
  913. const mute = track.isMuted();
  914. if(track.isLocal()){
  915. id = APP.conference.getMyUserId();
  916. if(track.getType() === "audio") {
  917. this.audioMuted = mute;
  918. } else {
  919. this.videoMuted = mute;
  920. }
  921. } else {
  922. id = track.getParticipantId();
  923. }
  924. handler(id , mute);
  925. });
  926. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  927. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  928. lvl = 0;
  929. }
  930. if(config.debug)
  931. {
  932. this.audioLevelsMap[id] = lvl;
  933. if(config.debugAudioLevels)
  934. console.log("AudioLevel:" + id + "/" + lvl);
  935. }
  936. APP.UI.setAudioLevel(id, lvl);
  937. });
  938. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  939. //FIXME
  940. if (config.muteLocalVideoIfNotInLastN) {
  941. // TODO mute or unmute if required
  942. // mark video on UI
  943. // APP.UI.markVideoMuted(true/false);
  944. }
  945. });
  946. room.on(
  947. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  948. APP.UI.handleLastNEndpoints(ids, enteringIds);
  949. });
  950. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  951. if (this.isLocalId(id)) {
  952. this.isDominantSpeaker = true;
  953. this.setRaisedHand(false);
  954. } else {
  955. this.isDominantSpeaker = false;
  956. var participant = room.getParticipantById(id);
  957. if (participant) {
  958. APP.UI.setRaisedHandStatus(participant, false);
  959. }
  960. }
  961. APP.UI.markDominantSpeaker(id);
  962. });
  963. if (!interfaceConfig.filmStripOnly) {
  964. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  965. APP.UI.markVideoInterrupted(true);
  966. });
  967. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  968. APP.UI.markVideoInterrupted(false);
  969. });
  970. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  971. let nick = getDisplayName(id);
  972. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  973. APP.UI.addMessage(id, nick, text, ts);
  974. });
  975. }
  976. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  977. connectionIsInterrupted = true;
  978. ConnectionQuality.updateLocalConnectionQuality(0);
  979. });
  980. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  981. connectionIsInterrupted = false;
  982. });
  983. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  984. APP.API.notifyDisplayNameChanged(id, displayName);
  985. APP.UI.changeDisplayName(id, displayName);
  986. });
  987. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  988. (participant, name, oldValue, newValue) => {
  989. if (name === "raisedHand") {
  990. APP.UI.setRaisedHandStatus(participant, newValue);
  991. }
  992. });
  993. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  994. console.log("Received recorder status change: ", status, error);
  995. APP.UI.updateRecordingState(status);
  996. });
  997. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  998. APP.UI.updateUserStatus(id, status);
  999. });
  1000. room.on(ConferenceEvents.KICKED, () => {
  1001. APP.UI.hideStats();
  1002. APP.UI.notifyKicked();
  1003. // FIXME close
  1004. });
  1005. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1006. APP.UI.updateDTMFSupport(isDTMFSupported);
  1007. });
  1008. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1009. if (room.isModerator()) {
  1010. let promise = roomLocker.isLocked
  1011. ? roomLocker.askToUnlock()
  1012. : roomLocker.askToLock();
  1013. promise.then(() => {
  1014. APP.UI.markRoomLocked(roomLocker.isLocked);
  1015. });
  1016. } else {
  1017. roomLocker.notifyModeratorRequired();
  1018. }
  1019. });
  1020. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1021. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1022. if (!interfaceConfig.filmStripOnly) {
  1023. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1024. APP.API.notifySendingChatMessage(message);
  1025. room.sendTextMessage(message);
  1026. });
  1027. }
  1028. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1029. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1030. });
  1031. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1032. (percent, stats) => {
  1033. APP.UI.updateLocalStats(percent, stats);
  1034. room.broadcastEndpointMessage({
  1035. type: this.commands.defaults.CONNECTION_QUALITY,
  1036. values: stats });
  1037. });
  1038. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1039. (participant, payload) => {
  1040. switch(payload.type) {
  1041. case this.commands.defaults.CONNECTION_QUALITY:
  1042. ConnectionQuality.updateRemoteStats(participant.getId(),
  1043. payload.values);
  1044. break;
  1045. default:
  1046. console.warn("Unknown datachannel message", payload);
  1047. }
  1048. });
  1049. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1050. (id, percent, stats) => {
  1051. APP.UI.updateRemoteStats(id, percent, stats);
  1052. });
  1053. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1054. APP.UI.initEtherpad(value);
  1055. });
  1056. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1057. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1058. APP.UI.setUserEmail(from, data.value);
  1059. });
  1060. APP.UI.addListener(UIEvents.AVATAR_URL_CHANGED, changeLocalAvatarUrl);
  1061. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1062. (data, from) => {
  1063. APP.UI.setUserAvatarUrl(from, data.value);
  1064. });
  1065. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1066. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1067. (startAudioMuted, startVideoMuted) => {
  1068. room.setStartMutedPolicy({
  1069. audio: startAudioMuted,
  1070. video: startVideoMuted
  1071. });
  1072. }
  1073. );
  1074. room.on(
  1075. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1076. ({ audio, video }) => {
  1077. APP.UI.onStartMutedChanged(audio, video);
  1078. }
  1079. );
  1080. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1081. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1082. && APP.UI.notifyInitiallyMuted();
  1083. });
  1084. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1085. APP.UI.inviteParticipants(
  1086. roomUrl,
  1087. APP.conference.roomName,
  1088. roomLocker.password,
  1089. APP.settings.getDisplayName()
  1090. );
  1091. });
  1092. room.on(
  1093. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1094. APP.UI.updateDevicesAvailability(id, devices);
  1095. }
  1096. );
  1097. // call hangup
  1098. APP.UI.addListener(UIEvents.HANGUP, () => {
  1099. hangup(true);
  1100. });
  1101. // logout
  1102. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1103. AuthHandler.logout(room).then(function (url) {
  1104. if (url) {
  1105. window.location.href = url;
  1106. } else {
  1107. hangup(true);
  1108. }
  1109. });
  1110. });
  1111. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1112. room.dial(sipNumber);
  1113. });
  1114. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1115. (id, oldResolution, newResolution, delay) => {
  1116. room.sendApplicationLog("Resolution change id=" + id
  1117. + " old=" + oldResolution + " new=" + newResolution
  1118. + " delay=" + delay);
  1119. });
  1120. // Starts or stops the recording for the conference.
  1121. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1122. room.toggleRecording(options);
  1123. });
  1124. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1125. room.setSubject(topic);
  1126. });
  1127. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1128. APP.UI.setSubject(subject);
  1129. });
  1130. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1131. room.kickParticipant(id);
  1132. });
  1133. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1134. room.muteParticipant(id);
  1135. });
  1136. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1137. AuthHandler.authenticate(room);
  1138. });
  1139. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1140. room.selectParticipant(id);
  1141. });
  1142. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1143. var smallVideoId = smallVideo.getId();
  1144. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1145. && !APP.conference.isLocalId(smallVideoId))
  1146. if (isPinned)
  1147. room.pinParticipant(smallVideoId);
  1148. // When the library starts supporting multiple pins we would
  1149. // pass the isPinned parameter together with the identifier,
  1150. // but currently we send null to indicate that we unpin the
  1151. // last pinned.
  1152. else
  1153. room.pinParticipant(null);
  1154. });
  1155. APP.UI.addListener(
  1156. UIEvents.VIDEO_DEVICE_CHANGED,
  1157. (cameraDeviceId) => {
  1158. createLocalTracks({
  1159. devices: ['video'],
  1160. cameraDeviceId: cameraDeviceId,
  1161. micDeviceId: null
  1162. })
  1163. .then(([stream]) => {
  1164. this.useVideoStream(stream);
  1165. console.log('switched local video device');
  1166. APP.settings.setCameraDeviceId(cameraDeviceId);
  1167. })
  1168. .catch((err) => {
  1169. APP.UI.showDeviceErrorDialog(null, err);
  1170. APP.UI.setSelectedCameraFromSettings();
  1171. });
  1172. }
  1173. );
  1174. APP.UI.addListener(
  1175. UIEvents.AUDIO_DEVICE_CHANGED,
  1176. (micDeviceId) => {
  1177. createLocalTracks({
  1178. devices: ['audio'],
  1179. cameraDeviceId: null,
  1180. micDeviceId: micDeviceId
  1181. })
  1182. .then(([stream]) => {
  1183. this.useAudioStream(stream);
  1184. console.log('switched local audio device');
  1185. APP.settings.setMicDeviceId(micDeviceId);
  1186. })
  1187. .catch((err) => {
  1188. APP.UI.showDeviceErrorDialog(err, null);
  1189. APP.UI.setSelectedMicFromSettings();
  1190. });
  1191. }
  1192. );
  1193. APP.UI.addListener(
  1194. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1195. (audioOutputDeviceId) => {
  1196. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1197. .then(() => console.log('changed audio output device'))
  1198. .catch((err) => {
  1199. console.warn('Failed to change audio output device. ' +
  1200. 'Default or previously set audio output device ' +
  1201. 'will be used instead.', err);
  1202. APP.UI.setSelectedAudioOutputFromSettings();
  1203. });
  1204. }
  1205. );
  1206. APP.UI.addListener(
  1207. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1208. );
  1209. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1210. (url, state, time, isMuted, volume) => {
  1211. // send start and stop commands once, and remove any updates
  1212. // that had left
  1213. if (state === 'stop' || state === 'start' || state === 'playing') {
  1214. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1215. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1216. value: url,
  1217. attributes: {
  1218. state: state,
  1219. time: time,
  1220. muted: isMuted,
  1221. volume: volume
  1222. }
  1223. });
  1224. }
  1225. else {
  1226. // in case of paused, in order to allow late users to join
  1227. // paused
  1228. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1229. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1230. value: url,
  1231. attributes: {
  1232. state: state,
  1233. time: time,
  1234. muted: isMuted,
  1235. volume: volume
  1236. }
  1237. });
  1238. }
  1239. });
  1240. room.addCommandListener(
  1241. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1242. if (attributes.state === 'stop') {
  1243. APP.UI.onSharedVideoStop(id, attributes);
  1244. }
  1245. else if (attributes.state === 'start') {
  1246. APP.UI.onSharedVideoStart(id, value, attributes);
  1247. }
  1248. else if (attributes.state === 'playing'
  1249. || attributes.state === 'pause') {
  1250. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1251. }
  1252. });
  1253. },
  1254. /**
  1255. * Adds any room listener.
  1256. * @param eventName one of the ConferenceEvents
  1257. * @param callBack the function to be called when the event occurs
  1258. */
  1259. addConferenceListener(eventName, callBack) {
  1260. room.on(eventName, callBack);
  1261. },
  1262. /**
  1263. * Inits list of current devices and event listener for device change.
  1264. * @private
  1265. */
  1266. _initDeviceList() {
  1267. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1268. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1269. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1270. // Ugly way to synchronize real device IDs with local
  1271. // storage and settings menu. This is a workaround until
  1272. // getConstraints() method will be implemented in browsers.
  1273. if (localAudio) {
  1274. localAudio._setRealDeviceIdFromDeviceList(devices);
  1275. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  1276. }
  1277. if (localVideo) {
  1278. localVideo._setRealDeviceIdFromDeviceList(devices);
  1279. APP.settings.setCameraDeviceId(localVideo.getDeviceId());
  1280. }
  1281. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1282. APP.UI.onAvailableDevicesChanged(devices);
  1283. });
  1284. JitsiMeetJS.mediaDevices.addEventListener(
  1285. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1286. (devices) =>
  1287. window.setTimeout(
  1288. () => this._onDeviceListChanged(devices), 0));
  1289. }
  1290. },
  1291. /**
  1292. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1293. * handle change of available media devices.
  1294. * @private
  1295. * @param {MediaDeviceInfo[]} devices
  1296. * @returns {Promise}
  1297. */
  1298. _onDeviceListChanged(devices) {
  1299. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1300. // Event handler can be fired before direct
  1301. // enumerateDevices() call, so handle this situation here.
  1302. if (!currentDevices.audioinput &&
  1303. !currentDevices.videoinput &&
  1304. !currentDevices.audiooutput) {
  1305. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1306. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1307. }
  1308. let newDevices =
  1309. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1310. devices, this.isSharingScreen, localVideo, localAudio);
  1311. let promises = [];
  1312. let audioWasMuted = this.audioMuted;
  1313. let videoWasMuted = this.videoMuted;
  1314. let availableAudioInputDevices =
  1315. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1316. let availableVideoInputDevices =
  1317. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1318. if (typeof newDevices.audiooutput !== 'undefined') {
  1319. // Just ignore any errors in catch block.
  1320. promises.push(APP.settings
  1321. .setAudioOutputDeviceId(newDevices.audiooutput)
  1322. .catch());
  1323. }
  1324. promises.push(
  1325. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1326. createLocalTracks,
  1327. newDevices.videoinput,
  1328. newDevices.audioinput)
  1329. .then(tracks =>
  1330. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1331. .then(() => {
  1332. // If audio was muted before, or we unplugged current device
  1333. // and selected new one, then mute new audio track.
  1334. if (audioWasMuted ||
  1335. currentDevices.audioinput.length >
  1336. availableAudioInputDevices.length) {
  1337. muteLocalAudio(true);
  1338. }
  1339. // If video was muted before, or we unplugged current device
  1340. // and selected new one, then mute new video track.
  1341. if (videoWasMuted ||
  1342. currentDevices.videoinput.length >
  1343. availableVideoInputDevices.length) {
  1344. muteLocalVideo(true);
  1345. }
  1346. }));
  1347. return Promise.all(promises)
  1348. .then(() => {
  1349. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1350. APP.UI.onAvailableDevicesChanged(devices);
  1351. });
  1352. },
  1353. /**
  1354. * Toggles the local "raised hand" status, if the current state allows
  1355. * toggling.
  1356. */
  1357. maybeToggleRaisedHand() {
  1358. // If we are the dominant speaker, we don't enable "raise hand".
  1359. if (this.isHandRaised || !this.isDominantSpeaker) {
  1360. this.setRaisedHand(!this.isHandRaised);
  1361. }
  1362. },
  1363. /**
  1364. * Sets the local "raised hand" status to a particular value.
  1365. */
  1366. setRaisedHand(raisedHand) {
  1367. if (raisedHand !== this.isHandRaised)
  1368. {
  1369. this.isHandRaised = raisedHand;
  1370. // Advertise the updated status
  1371. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1372. // Update the view
  1373. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1374. }
  1375. }
  1376. };