Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

actions.web.ts 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import { v4 as uuidv4 } from 'uuid';
  2. import { IStore } from '../app/types';
  3. import { updateConfig } from '../base/config/actions';
  4. import { getDialOutStatusUrl, getDialOutUrl } from '../base/config/functions';
  5. import { connect } from '../base/connection/actions';
  6. import { browser } from '../base/lib-jitsi-meet';
  7. import { createLocalTrack } from '../base/lib-jitsi-meet/functions';
  8. import { MEDIA_TYPE } from '../base/media/constants';
  9. import { isVideoMutedByUser } from '../base/media/functions';
  10. import { updateSettings } from '../base/settings/actions';
  11. import { replaceLocalTrack, trackAdded } from '../base/tracks/actions';
  12. import {
  13. createLocalTracksF,
  14. getLocalAudioTrack,
  15. getLocalTracks,
  16. getLocalVideoTrack
  17. } from '../base/tracks/functions';
  18. import { openURLInBrowser } from '../base/util/openURLInBrowser';
  19. import { executeDialOutRequest, executeDialOutStatusRequest, getDialInfoPageURL } from '../invite/functions';
  20. import { showErrorNotification } from '../notifications/actions';
  21. import { NOTIFICATION_TIMEOUT_TYPE } from '../notifications/constants';
  22. import { INotificationProps } from '../notifications/types';
  23. import {
  24. PREJOIN_INITIALIZED,
  25. PREJOIN_JOINING_IN_PROGRESS,
  26. SET_DEVICE_STATUS,
  27. SET_DIALOUT_COUNTRY,
  28. SET_DIALOUT_NUMBER,
  29. SET_DIALOUT_STATUS,
  30. SET_JOIN_BY_PHONE_DIALOG_VISIBLITY,
  31. SET_PRECALL_TEST_RESULTS,
  32. SET_PREJOIN_DEVICE_ERRORS,
  33. SET_PREJOIN_PAGE_VISIBILITY,
  34. SET_SKIP_PREJOIN_RELOAD
  35. } from './actionTypes';
  36. import {
  37. getDialOutConferenceUrl,
  38. getDialOutCountry,
  39. getFullDialOutNumber,
  40. isJoinByPhoneDialogVisible
  41. } from './functions';
  42. import logger from './logger';
  43. const dialOutStatusToKeyMap = {
  44. INITIATED: 'presenceStatus.calling',
  45. RINGING: 'presenceStatus.ringing'
  46. };
  47. const DIAL_OUT_STATUS = {
  48. INITIATED: 'INITIATED',
  49. RINGING: 'RINGING',
  50. CONNECTED: 'CONNECTED',
  51. DISCONNECTED: 'DISCONNECTED',
  52. FAILED: 'FAILED'
  53. };
  54. /**
  55. * The time interval used between requests while polling for dial out status.
  56. */
  57. const STATUS_REQ_FREQUENCY = 2000;
  58. /**
  59. * The maximum number of retries while polling for dial out status.
  60. */
  61. const STATUS_REQ_CAP = 45;
  62. /**
  63. * Polls for status change after dial out.
  64. * Changes dialog message based on response, closes the dialog if there is an error,
  65. * joins the meeting when CONNECTED.
  66. *
  67. * @param {string} reqId - The request id used to correlate the dial out request with this one.
  68. * @param {Function} onSuccess - Success handler.
  69. * @param {Function} onFail - Fail handler.
  70. * @param {number} count - The number of retried calls. When it hits STATUS_REQ_CAP it should no longer make requests.
  71. * @returns {Function}
  72. */
  73. function pollForStatus(
  74. reqId: string,
  75. onSuccess: Function,
  76. onFail: Function,
  77. count = 0) {
  78. return async function(dispatch: IStore['dispatch'], getState: IStore['getState']) {
  79. const state = getState();
  80. try {
  81. if (!isJoinByPhoneDialogVisible(state)) {
  82. return;
  83. }
  84. const res = await executeDialOutStatusRequest(getDialOutStatusUrl(state) ?? '', reqId);
  85. switch (res) {
  86. case DIAL_OUT_STATUS.INITIATED:
  87. case DIAL_OUT_STATUS.RINGING: {
  88. dispatch(setDialOutStatus(dialOutStatusToKeyMap[res as keyof typeof dialOutStatusToKeyMap]));
  89. if (count < STATUS_REQ_CAP) {
  90. return setTimeout(() => {
  91. dispatch(pollForStatus(reqId, onSuccess, onFail, count + 1));
  92. }, STATUS_REQ_FREQUENCY);
  93. }
  94. return onFail();
  95. }
  96. case DIAL_OUT_STATUS.CONNECTED: {
  97. return onSuccess();
  98. }
  99. case DIAL_OUT_STATUS.DISCONNECTED: {
  100. dispatch(showErrorNotification({
  101. titleKey: 'prejoin.errorDialOutDisconnected'
  102. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  103. return onFail();
  104. }
  105. case DIAL_OUT_STATUS.FAILED: {
  106. dispatch(showErrorNotification({
  107. titleKey: 'prejoin.errorDialOutFailed'
  108. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  109. return onFail();
  110. }
  111. }
  112. } catch (err) {
  113. dispatch(showErrorNotification({
  114. titleKey: 'prejoin.errorDialOutStatus'
  115. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  116. logger.error('Error getting dial out status', err);
  117. onFail();
  118. }
  119. };
  120. }
  121. /**
  122. * Action used for joining the meeting with phone audio.
  123. * A dial out connection is tried and a polling mechanism is used for getting the status.
  124. * If the connection succeeds the `onSuccess` callback is executed.
  125. * If the phone connection fails or the number is invalid the `onFail` callback is executed.
  126. *
  127. * @param {Function} onSuccess - Success handler.
  128. * @param {Function} onFail - Fail handler.
  129. * @returns {Function}
  130. */
  131. export function dialOut(onSuccess: Function, onFail: Function) {
  132. return async function(dispatch: IStore['dispatch'], getState: IStore['getState']) {
  133. const state = getState();
  134. const reqId = uuidv4();
  135. const url = getDialOutUrl(state) ?? '';
  136. const conferenceUrl = getDialOutConferenceUrl(state);
  137. const phoneNumber = getFullDialOutNumber(state);
  138. const countryCode = getDialOutCountry(state).code.toUpperCase();
  139. const body = {
  140. conferenceUrl,
  141. countryCode,
  142. name: phoneNumber,
  143. phoneNumber
  144. };
  145. try {
  146. await executeDialOutRequest(url, body, reqId);
  147. dispatch(pollForStatus(reqId, onSuccess, onFail));
  148. } catch (err: any) {
  149. const notification: INotificationProps = {
  150. titleKey: 'prejoin.errorDialOut',
  151. titleArguments: undefined
  152. };
  153. if (err.status) {
  154. if (err.messageKey === 'validation.failed') {
  155. notification.titleKey = 'prejoin.errorValidation';
  156. } else {
  157. notification.titleKey = 'prejoin.errorStatusCode';
  158. notification.titleArguments = { status: err.status };
  159. }
  160. }
  161. dispatch(showErrorNotification(notification, NOTIFICATION_TIMEOUT_TYPE.LONG));
  162. logger.error('Error dialing out', err);
  163. onFail();
  164. }
  165. };
  166. }
  167. /**
  168. * Adds all the newly created tracks to store on init.
  169. *
  170. * @param {Object[]} tracks - The newly created tracks.
  171. * @param {Object} errors - The errors from creating the tracks.
  172. *
  173. * @returns {Function}
  174. */
  175. export function initPrejoin(tracks: Object[], errors: Object) {
  176. return async function(dispatch: IStore['dispatch']) {
  177. dispatch(setPrejoinDeviceErrors(errors));
  178. dispatch(prejoinInitialized());
  179. tracks.forEach(track => dispatch(trackAdded(track)));
  180. };
  181. }
  182. /**
  183. * Action used to start the conference.
  184. *
  185. * @param {Object} options - The config options that override the default ones (if any).
  186. * @param {boolean} ignoreJoiningInProgress - If true we won't check the joiningInProgress flag.
  187. * @param {string?} jid - The XMPP user's ID (e.g. {@code user@server.com}).
  188. * @param {string?} password - The XMPP user's password.
  189. * @returns {Function}
  190. */
  191. export function joinConference(options?: Object, ignoreJoiningInProgress = false,
  192. jid?: string, password?: string) {
  193. return async function(dispatch: IStore['dispatch'], getState: IStore['getState']) {
  194. if (!ignoreJoiningInProgress) {
  195. const state = getState();
  196. const { joiningInProgress } = state['features/prejoin'];
  197. if (joiningInProgress) {
  198. return;
  199. }
  200. dispatch(setJoiningInProgress(true));
  201. }
  202. options && dispatch(updateConfig(options));
  203. dispatch(connect(jid, password)).then(async () => {
  204. // TODO keep this here till we move tracks and conference management from
  205. // conference.js to react.
  206. const state = getState();
  207. let localTracks = getLocalTracks(state['features/base/tracks']);
  208. // Do not signal audio/video tracks if the user joins muted.
  209. for (const track of localTracks) {
  210. // Always add the audio track on Safari because of a known issue where audio playout doesn't happen
  211. // if the user joins audio and video muted.
  212. if (track.muted && !(browser.isWebKitBased() && track.jitsiTrack
  213. && track.jitsiTrack.getType() === MEDIA_TYPE.AUDIO)) {
  214. try {
  215. await dispatch(replaceLocalTrack(track.jitsiTrack, null));
  216. } catch (error) {
  217. logger.error(`Failed to replace local track (${track.jitsiTrack}) with null: ${error}`);
  218. }
  219. }
  220. }
  221. // Re-fetch the local tracks after muted tracks have been removed above.
  222. // This is needed, because the tracks are effectively disposed by the replaceLocalTrack and should not be
  223. // used anymore.
  224. localTracks = getLocalTracks(getState()['features/base/tracks']);
  225. const jitsiTracks = localTracks.map((t: any) => t.jitsiTrack);
  226. APP.conference.startConference(jitsiTracks).catch(logger.error);
  227. })
  228. .catch(() => {
  229. // There is nothing to do here. This is handled and dispatched in base/connection/actions.
  230. });
  231. };
  232. }
  233. /**
  234. * Action used to set the flag for joining operation in progress.
  235. *
  236. * @param {boolean} value - The config options that override the default ones (if any).
  237. * @returns {Function}
  238. */
  239. export function setJoiningInProgress(value: boolean) {
  240. return {
  241. type: PREJOIN_JOINING_IN_PROGRESS,
  242. value
  243. };
  244. }
  245. /**
  246. * Joins the conference without audio.
  247. *
  248. * @returns {Function}
  249. */
  250. export function joinConferenceWithoutAudio() {
  251. return async function(dispatch: IStore['dispatch'], getState: IStore['getState']) {
  252. const state = getState();
  253. const { joiningInProgress } = state['features/prejoin'];
  254. if (joiningInProgress) {
  255. return;
  256. }
  257. dispatch(setJoiningInProgress(true));
  258. const tracks = state['features/base/tracks'];
  259. const audioTrack = getLocalAudioTrack(tracks)?.jitsiTrack;
  260. if (audioTrack) {
  261. try {
  262. await dispatch(replaceLocalTrack(audioTrack, null));
  263. } catch (error) {
  264. logger.error(`Failed to replace local audio with null: ${error}`);
  265. }
  266. }
  267. dispatch(joinConference({
  268. startSilent: true
  269. }, true));
  270. };
  271. }
  272. /**
  273. * Initializes the 'precallTest' and executes one test, storing the results.
  274. *
  275. * @param {Object} conferenceOptions - The conference options.
  276. * @returns {Function}
  277. */
  278. export function makePrecallTest(conferenceOptions: Object) {
  279. return async function(dispatch: IStore['dispatch']) {
  280. try {
  281. await JitsiMeetJS.precallTest.init(conferenceOptions);
  282. const results = await JitsiMeetJS.precallTest.execute();
  283. dispatch(setPrecallTestResults(results));
  284. } catch (error) {
  285. logger.debug('Failed to execute pre call test - ', error);
  286. }
  287. };
  288. }
  289. /**
  290. * Opens an external page with all the dial in numbers.
  291. *
  292. * @returns {Function}
  293. */
  294. export function openDialInPage() {
  295. return function(dispatch: IStore['dispatch'], getState: IStore['getState']) {
  296. const dialInPage = getDialInfoPageURL(getState());
  297. openURLInBrowser(dialInPage, true);
  298. };
  299. }
  300. /**
  301. * Action used to signal that the prejoin page has been initialized.
  302. *
  303. * @returns {Object}
  304. */
  305. function prejoinInitialized() {
  306. return {
  307. type: PREJOIN_INITIALIZED
  308. };
  309. }
  310. /**
  311. * Creates a new audio track based on a device id and replaces the current one.
  312. *
  313. * @param {string} deviceId - The deviceId of the microphone.
  314. * @returns {Function}
  315. */
  316. export function replaceAudioTrackById(deviceId: string) {
  317. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  318. try {
  319. const tracks = getState()['features/base/tracks'];
  320. const newTrack = await createLocalTrack('audio', deviceId);
  321. const oldTrack = getLocalAudioTrack(tracks)?.jitsiTrack;
  322. const micDeviceId = newTrack.getDeviceId();
  323. logger.info(`Switching audio input device to ${micDeviceId}`);
  324. dispatch(replaceLocalTrack(oldTrack, newTrack)).then(() => {
  325. dispatch(updateSettings({
  326. micDeviceId
  327. }));
  328. });
  329. } catch (err) {
  330. dispatch(setDeviceStatusWarning('prejoin.audioTrackError'));
  331. logger.log('Error replacing audio track', err);
  332. }
  333. };
  334. }
  335. /**
  336. * Creates a new video track based on a device id and replaces the current one.
  337. *
  338. * @param {string} deviceId - The deviceId of the camera.
  339. * @returns {Function}
  340. */
  341. export function replaceVideoTrackById(deviceId: string) {
  342. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  343. try {
  344. const tracks = getState()['features/base/tracks'];
  345. const wasVideoMuted = isVideoMutedByUser(getState());
  346. const [ newTrack ] = await createLocalTracksF(
  347. { cameraDeviceId: deviceId,
  348. devices: [ 'video' ] },
  349. { dispatch,
  350. getState }
  351. );
  352. const oldTrack = getLocalVideoTrack(tracks)?.jitsiTrack;
  353. const cameraDeviceId = newTrack.getDeviceId();
  354. logger.info(`Switching camera to ${cameraDeviceId}`);
  355. dispatch(replaceLocalTrack(oldTrack, newTrack)).then(() => {
  356. dispatch(updateSettings({
  357. cameraDeviceId
  358. }));
  359. });
  360. wasVideoMuted && newTrack.mute();
  361. } catch (err) {
  362. dispatch(setDeviceStatusWarning('prejoin.videoTrackError'));
  363. logger.log('Error replacing video track', err);
  364. }
  365. };
  366. }
  367. /**
  368. * Sets the device status as OK with the corresponding text.
  369. *
  370. * @param {string} deviceStatusText - The text to be set.
  371. * @returns {Object}
  372. */
  373. export function setDeviceStatusOk(deviceStatusText: string) {
  374. return {
  375. type: SET_DEVICE_STATUS,
  376. value: {
  377. deviceStatusText,
  378. deviceStatusType: 'ok'
  379. }
  380. };
  381. }
  382. /**
  383. * Sets the device status as 'warning' with the corresponding text.
  384. *
  385. * @param {string} deviceStatusText - The text to be set.
  386. * @returns {Object}
  387. */
  388. export function setDeviceStatusWarning(deviceStatusText: string) {
  389. return {
  390. type: SET_DEVICE_STATUS,
  391. value: {
  392. deviceStatusText,
  393. deviceStatusType: 'warning'
  394. }
  395. };
  396. }
  397. /**
  398. * Action used to set the dial out status.
  399. *
  400. * @param {string} value - The status.
  401. * @returns {Object}
  402. */
  403. function setDialOutStatus(value: string) {
  404. return {
  405. type: SET_DIALOUT_STATUS,
  406. value
  407. };
  408. }
  409. /**
  410. * Action used to set the dial out country.
  411. *
  412. * @param {{ name: string, dialCode: string, code: string }} value - The country.
  413. * @returns {Object}
  414. */
  415. export function setDialOutCountry(value: Object) {
  416. return {
  417. type: SET_DIALOUT_COUNTRY,
  418. value
  419. };
  420. }
  421. /**
  422. * Action used to set the dial out number.
  423. *
  424. * @param {string} value - The dial out number.
  425. * @returns {Object}
  426. */
  427. export function setDialOutNumber(value: string) {
  428. return {
  429. type: SET_DIALOUT_NUMBER,
  430. value
  431. };
  432. }
  433. /**
  434. * Sets the visibility of the prejoin page when a client reload
  435. * is triggered as a result of call migration initiated by Jicofo.
  436. *
  437. * @param {boolean} value - The visibility value.
  438. * @returns {Object}
  439. */
  440. export function setSkipPrejoinOnReload(value: boolean) {
  441. return {
  442. type: SET_SKIP_PREJOIN_RELOAD,
  443. value
  444. };
  445. }
  446. /**
  447. * Action used to set the visiblitiy of the 'JoinByPhoneDialog'.
  448. *
  449. * @param {boolean} value - The value.
  450. * @returns {Object}
  451. */
  452. export function setJoinByPhoneDialogVisiblity(value: boolean) {
  453. return {
  454. type: SET_JOIN_BY_PHONE_DIALOG_VISIBLITY,
  455. value
  456. };
  457. }
  458. /**
  459. * Action used to set data from precall test.
  460. *
  461. * @param {Object} value - The precall test results.
  462. * @returns {Object}
  463. */
  464. export function setPrecallTestResults(value: Object) {
  465. return {
  466. type: SET_PRECALL_TEST_RESULTS,
  467. value
  468. };
  469. }
  470. /**
  471. * Action used to set the initial errors after creating the tracks.
  472. *
  473. * @param {Object} value - The track errors.
  474. * @returns {Object}
  475. */
  476. export function setPrejoinDeviceErrors(value: Object) {
  477. return {
  478. type: SET_PREJOIN_DEVICE_ERRORS,
  479. value
  480. };
  481. }
  482. /**
  483. * Action used to set the visibility of the prejoin page.
  484. *
  485. * @param {boolean} value - The value.
  486. * @returns {Object}
  487. */
  488. export function setPrejoinPageVisibility(value: boolean) {
  489. return {
  490. type: SET_PREJOIN_PAGE_VISIBILITY,
  491. value
  492. };
  493. }