Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@filerobot/explorer / lib / slices / sharebox.slice.js
Size: Mime:
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { createSlice } from '@reduxjs/toolkit';
import { PLUGINS_IDS, VIEW_IDS } from '@filerobot/utils/lib/constants';
import createThunk from '@filerobot/utils/lib/createThunk';
import addUrlParams from '@filerobot/utils/lib/addUrlParams';
import { changeView } from './views.slice';
import getNormalizedItems, { getItemKey } from '../utils/getNormalizedItems';
var slicePropName = 'sharebox';
var sliceName = "".concat(PLUGINS_IDS.EXPLORER, "/").concat(slicePropName);
var initialState = {
  loading: false,
  filesEntities: {},
  foldersEntities: {},
  currentViewedFoldersEntities: {},
  currentViewedFilesEntities: {},
  currentViewedFoldersUuids: [],
  currentViewedFilesUuids: [],
  foldersUuids: [],
  filesUuids: [],
  openedFolders: [],
  errored: false,
  stats: {
    totalFilesCount: 0,
    totalFoldersCount: 0
  }
};

/**
 * Generates and injects a UUID into an item object based on a given key.
 *
 * @param {object} item - The item object to inject the UUID into.
 * @param {string} key - The key used to generate the UUID.
 * @return {object} The item object with the UUID injected.
 */
var generateAndInjectItemUuid = function generateAndInjectItemUuid(item, key) {
  return _objectSpread(_objectSpread({}, item), {}, {
    uuid: getItemKey(key, item) || item[key]
  });
};

/**
 * Returns an array of all files in the given folder and its subfolders.
 *
 * @param {Object} folder - The root folder to start the recursive search.
 * @param {Array} folder.files - The files in the current folder.
 * @param {Array} folder.folders - The subfolders in the current folder.
 * @return {Array} An array containing all the files found recursively.
 */
var getFilesRecursively = function getFilesRecursively(folder) {
  var recursiveFiles = [];
  var getFolderChildrenFiles = function getFolderChildrenFiles() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      files = _ref.files,
      folders = _ref.folders;
    if (files) {
      recursiveFiles.push.apply(recursiveFiles, _toConsumableArray(files));
    }
    if (folders) {
      folders.forEach(getFolderChildrenFiles);
    }
  };
  getFolderChildrenFiles(folder);
  return recursiveFiles;
};
var generateVirtualFolderPath = function generateVirtualFolderPath(folder, parentPath) {
  return "".concat(parentPath || '', "/").concat(folder.name);
};

/**
 * Generates a payload for a folder, including its path, previews, and count of files.
 *
 * @param {string} parentPath - The parent path of the folder.
 * @return {function} A function that takes a folder as input and generates the payload for that folder.
 */
var generateFolderPayload = function generateFolderPayload(parentPath) {
  return function (folder) {
    var generatedPath = generateVirtualFolderPath(folder, parentPath);
    var recursiveFiles = getFilesRecursively(folder);
    var adaptedFolder = _objectSpread(_objectSpread({}, generateAndInjectItemUuid(folder, 'name')), {}, {
      path: generatedPath,
      previews: recursiveFiles,
      count: {
        files_direct: folder.files.length,
        files_recursive: recursiveFiles.length
      }
    });
    var folderSubFolders = _toConsumableArray(adaptedFolder.folders);
    if (folderSubFolders) {
      folderSubFolders = folderSubFolders.map(generateFolderPayload(generatedPath));
    }
    adaptedFolder = _objectSpread(_objectSpread({}, adaptedFolder), {}, {
      folders: folderSubFolders
    });
    return adaptedFolder;
  };
};
var getFoldersState = function getFoldersState(foldersPayload, state) {
  var folders = foldersPayload.map(generateFolderPayload());
  var _getNormalizedItems = getNormalizedItems(folders, {}, 'name'),
    normalizedSlices = _getNormalizedItems.normalizedSlices,
    foldersUuids = _getNormalizedItems.uuids;
  var foldersEntities = _objectSpread(_objectSpread({}, state.entities), normalizedSlices);
  var stats = _objectSpread(_objectSpread({}, state.stats), {}, {
    totalFoldersCount: foldersUuids.length
  });
  return {
    foldersEntities: foldersEntities,
    foldersUuids: foldersUuids,
    stats: stats
  };
};
var getFilesState = function getFilesState(filesPayload, state) {
  var files = filesPayload.map(function (file) {
    return generateAndInjectItemUuid(file, 'url.path');
  });
  var _getNormalizedItems2 = getNormalizedItems(files, {}, 'url.path'),
    normalizedSlices = _getNormalizedItems2.normalizedSlices,
    filesUuids = _getNormalizedItems2.uuids;
  var filesEntities = _objectSpread(_objectSpread({}, state.entities), normalizedSlices);
  var stats = _objectSpread(_objectSpread({}, state.stats), {}, {
    totalFilesCount: filesUuids.length
  });
  return {
    filesEntities: filesEntities,
    filesUuids: filesUuids,
    stats: stats
  };
};
var checkShareboxPasswordHandler = function checkShareboxPasswordHandler(_ref2) {
  var error = _ref2.error,
    filerobot = _ref2.filerobot,
    i18n = _ref2.i18n,
    shareboxPassword = _ref2.shareboxPassword;
  var isPasswordErrorCode = error.code === 401;
  if (!isPasswordErrorCode) {
    // Check the error is not produced due to wrong password
    filerobot.emit('sharebox-loading-error', error);
    return;
  }
  if (!shareboxPassword) {
    // Check if no password provided
    filerobot.emit('sharebox-requires-password');
    return;
  }
  filerobot.info(i18n('shareboxPasswordInfo'), 'error'); // Password provided but wrong!
  filerobot.emit('sharebox-wrong-password');
};
export var fetchShareboxFilesAndFolders = createThunk(async function (_, thunkApi) {
  var extra = thunkApi.extra;
  var get = extra.apiClient.get,
    filerobot = extra.filerobot;
  var _filerobot$opts = filerobot.opts,
    shareApiEndpoint = _filerobot$opts.shareApiEndpoint,
    container = _filerobot$opts.container;
  var _filerobot$getPlugin = filerobot.getPlugin(PLUGINS_IDS.EXPLORER),
    explorerOpts = _filerobot$getPlugin.opts,
    i18n = _filerobot$getPlugin.i18n;
  var shareboxPUID = explorerOpts.shareboxPUID,
    shareboxPassword = explorerOpts.shareboxPassword;
  var endpoint = "".concat(shareApiEndpoint, "/").concat(container, "/v4/share/").concat(shareboxPUID);
  if (shareboxPassword) endpoint = addUrlParams(endpoint, {
    password: shareboxPassword
  });
  try {
    var _await$get = await get(endpoint),
      files = _await$get.files,
      folders = _await$get.folders;
    filerobot.emit('sharebox-loaded');
    return {
      files: files,
      folders: folders,
      returnState: false
    };
  } catch (error) {
    checkShareboxPasswordHandler({
      error: error,
      filerobot: filerobot,
      i18n: i18n,
      shareboxPassword: shareboxPassword
    });
    return thunkApi.rejectWithValue(error.message);
  }
}, {
  actionType: "".concat(sliceName, "/fetchShareboxFilesAndFolders")
});
export var activateShareboxView = createThunk(async function () {
  var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
    _ref3$skipViewDispatc = _ref3.skipViewDispatch,
    skipViewDispatch = _ref3$skipViewDispatc === void 0 ? false : _ref3$skipViewDispatc;
  var thunkApi = arguments.length > 1 ? arguments[1] : undefined;
  var dispatch = thunkApi.dispatch;
  if (!skipViewDispatch) {
    dispatch(changeView({
      view: VIEW_IDS.SHAREBOX
    }));
  }
  await dispatch(fetchShareboxFilesAndFolders());
});
export var openShareboxFolder = createThunk(async function (folder, thunkApi) {
  var dispatch = thunkApi.dispatch;
  var _folder$folders = folder.folders,
    folders = _folder$folders === void 0 ? [] : _folder$folders,
    _folder$files = folder.files,
    files = _folder$files === void 0 ? [] : _folder$files;
  dispatch(openedFoldersUpdated(folder));
  dispatch(currentViewedFilesUpdated(files));
  dispatch(currentViewedFoldersUpdated(folders));
});
var shareboxSlice = createSlice({
  name: sliceName,
  initialState: initialState,
  reducers: {
    filesAdded: function filesAdded(state, action) {
      var _action$payload = action.payload,
        _action$payload$files = _action$payload.files,
        files = _action$payload$files === void 0 ? [] : _action$payload$files,
        _action$payload$retur = _action$payload.returnState,
        returnState = _action$payload$retur === void 0 ? true : _action$payload$retur;
      var _getFilesState = getFilesState(files, state),
        filesEntities = _getFilesState.filesEntities,
        filesUuids = _getFilesState.filesUuids,
        stats = _getFilesState.stats;
      return _objectSpread(_objectSpread({}, returnState ? state : {}), {}, {
        filesEntities: filesEntities,
        filesUuids: filesUuids,
        currentViewedFilesUuids: filesUuids,
        currentViewedFilesEntities: filesEntities,
        stats: stats
      });
    },
    foldersAdded: function foldersAdded(state, action) {
      var _action$payload2 = action.payload,
        _action$payload2$fold = _action$payload2.folders,
        folders = _action$payload2$fold === void 0 ? [] : _action$payload2$fold,
        _action$payload2$retu = _action$payload2.returnState,
        returnState = _action$payload2$retu === void 0 ? true : _action$payload2$retu;
      var _getFoldersState = getFoldersState(folders, state),
        foldersEntities = _getFoldersState.foldersEntities,
        foldersUuids = _getFoldersState.foldersUuids,
        stats = _getFoldersState.stats;
      return _objectSpread(_objectSpread({}, returnState ? state : {}), {}, {
        openedFolders: initialState.openedFolders,
        foldersEntities: foldersEntities,
        foldersUuids: foldersUuids,
        currentViewedFoldersEntities: foldersEntities,
        currentViewedFoldersUuids: foldersUuids,
        stats: stats
      });
    },
    errorUpdated: function errorUpdated(state, action) {
      return _objectSpread(_objectSpread({}, state), {}, {
        errored: !!action.payload
      });
    },
    currentViewedFoldersUpdated: function currentViewedFoldersUpdated(state, action) {
      var _getNormalizedItems3 = getNormalizedItems(action.payload),
        foldersEntities = _getNormalizedItems3.normalizedSlices,
        foldersUuids = _getNormalizedItems3.uuids;
      return _objectSpread(_objectSpread({}, state), {}, {
        currentViewedFoldersEntities: foldersEntities,
        currentViewedFoldersUuids: foldersUuids,
        stats: _objectSpread(_objectSpread({}, state.stats), {}, {
          totalFoldersCount: foldersUuids.length
        })
      });
    },
    openedFoldersUpdated: function openedFoldersUpdated(state, action) {
      var nextFolder = action.payload;
      var nextOpenedFolders = _toConsumableArray(state.openedFolders);
      var isAlreadyOpened = nextOpenedFolders.some(function (_ref4) {
        var path = _ref4.path;
        return path === nextFolder.path;
      });
      if (isAlreadyOpened) {
        nextOpenedFolders = nextOpenedFolders.filter(function (_ref5) {
          var path = _ref5.path;
          return path === nextFolder.path || !path.includes(nextFolder.path);
        });
      } else {
        nextOpenedFolders.push(action.payload);
      }
      return _objectSpread(_objectSpread({}, state), {}, {
        openedFolders: nextOpenedFolders
      });
    },
    currentViewedFilesUpdated: function currentViewedFilesUpdated(state, action) {
      var _getFilesState2 = getFilesState(action.payload, state),
        filesEntities = _getFilesState2.filesEntities,
        filesUuids = _getFilesState2.filesUuids,
        stats = _getFilesState2.stats;
      return _objectSpread(_objectSpread({}, state), {}, {
        currentViewedFilesEntities: filesEntities,
        currentViewedFilesUuids: filesUuids,
        stats: stats
      });
    }
  },
  extraReducers: function extraReducers(builder) {
    builder.addCase(fetchShareboxFilesAndFolders.pending, function (state) {
      return _objectSpread(_objectSpread({}, state), {}, {
        loading: true,
        errored: initialState.errored,
        openedFolders: initialState.openedFolders
      });
    }).addCase(fetchShareboxFilesAndFolders.fulfilled, function (state, action) {
      return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, state), shareboxSlice.caseReducers.filesAdded(state, action)), shareboxSlice.caseReducers.foldersAdded(state, action)), {}, {
        loading: false
      });
    }).addCase(fetchShareboxFilesAndFolders.rejected, function (state) {
      return _objectSpread(_objectSpread({}, state), {}, {
        loading: false,
        errored: true
      });
    });
  }
});
var _shareboxSlice$action = shareboxSlice.actions,
  filesAdded = _shareboxSlice$action.filesAdded,
  foldersAdded = _shareboxSlice$action.foldersAdded,
  currentViewedFoldersUpdated = _shareboxSlice$action.currentViewedFoldersUpdated,
  currentViewedFilesUpdated = _shareboxSlice$action.currentViewedFilesUpdated,
  openedFoldersUpdated = _shareboxSlice$action.openedFoldersUpdated,
  errorUpdated = _shareboxSlice$action.errorUpdated;
export { filesAdded, foldersAdded, currentViewedFoldersUpdated, currentViewedFilesUpdated, openedFoldersUpdated, errorUpdated };
export var selectShareboxState = function selectShareboxState(state) {
  return state[PLUGINS_IDS.EXPLORER][slicePropName];
};
export var selectShareboxFilesUuids = function selectShareboxFilesUuids(state) {
  return selectShareboxState(state).filesUuids;
};
export var selectShareboxFoldersUuids = function selectShareboxFoldersUuids(state) {
  return selectShareboxState(state).foldersUuids;
};
export var selectShareboxFiles = function selectShareboxFiles(state) {
  return selectShareboxState(state).filesEntities;
};
export var selectShareboxFolders = function selectShareboxFolders(state) {
  return selectShareboxState(state).foldersEntities;
};
export var selectCurrentViewedShareboxFoldersUuids = function selectCurrentViewedShareboxFoldersUuids(state) {
  return selectShareboxState(state).currentViewedFoldersUuids;
};
export var selectCurrentViewedShareboxFolders = function selectCurrentViewedShareboxFolders(state) {
  return selectShareboxState(state).currentViewedFoldersEntities;
};
export var selectCurrentViewedShareboxFiles = function selectCurrentViewedShareboxFiles(state) {
  return selectShareboxState(state).currentViewedFilesEntities;
};
export var selectCurrentViewedShareboxFilesUuids = function selectCurrentViewedShareboxFilesUuids(state) {
  return selectShareboxState(state).currentViewedFilesUuids;
};
export var selectShareboxFileByUuid = function selectShareboxFileByUuid(state, fileUuid) {
  return selectCurrentViewedShareboxFiles(state)[fileUuid];
};
export var selectShareboxFolderByUuid = function selectShareboxFolderByUuid(state, fileUuid) {
  return selectCurrentViewedShareboxFolders(state)[fileUuid];
};
export var selectShareboxOpenedFolders = function selectShareboxOpenedFolders(state) {
  return selectShareboxState(state).openedFolders;
};
export var selectIsShareboxLoading = function selectIsShareboxLoading(state) {
  return selectShareboxState(state).loading;
};
export default shareboxSlice.reducer;