Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 53KB

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