DocSpace-client/packages/asc-web-common/utils/index.js

376 lines
8.6 KiB
JavaScript
Raw Normal View History

2020-12-04 08:38:15 +00:00
import { LANGUAGE } from "../constants";
import sjcl from "sjcl";
import { isMobile } from "react-device-detect";
Merge branch 'develop' into feature/workspaces # Conflicts: # packages/asc-web-common/src/components/FilterInput/FilterInput.js # packages/asc-web-common/src/components/FilterInput/sub-components/SortComboBox.js # packages/asc-web-common/src/components/PageLayout/index.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-body.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-header.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-main-button.js # packages/asc-web-common/src/components/PageLayout/sub-components/section-body.js # packages/asc-web-common/src/components/PageLayout/sub-components/section-header.js # packages/asc-web-common/src/components/PrivateRoute/PrivateRoute.js # products/ASC.Files/Client/package.json # products/ASC.Files/Client/src/components/Article/Body/TreeFolders.js # products/ASC.Files/Client/src/components/pages/DocEditor/index.js # products/ASC.Files/Client/src/components/pages/Home/Section/Filter/index.js # products/ASC.Files/Client/src/components/panels/OperationsPanel/index.js # products/ASC.Files/Client/src/components/panels/SharingPanel/SharingRow.js # products/ASC.Files/Client/src/components/panels/SharingPanel/index.js # products/ASC.Files/Client/src/index.js # products/ASC.Files/Client/src/store/files/actions.js # products/ASC.Files/Client/yarn.lock # products/ASC.People/Client/package.json # products/ASC.People/Client/src/components/pages/Home/Section/Body/index.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/ContactField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/DateField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/EmailField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/RadioField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/TextChangeField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/TextField.js # products/ASC.People/Client/src/index.js # products/ASC.People/Client/yarn.lock # web/ASC.Web.Client/package.json # web/ASC.Web.Client/src/App.js # web/ASC.Web.Client/src/components/pages/Confirm/index.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/activateEmail.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/changeEmail.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/changeOwner.js # web/ASC.Web.Client/src/helpers/confirmRoute.js # web/ASC.Web.Client/src/index.js # web/ASC.Web.Common/package.json # web/ASC.Web.Common/yarn.lock # web/ASC.Web.Components/package.json # web/ASC.Web.Components/yarn.lock # web/ASC.Web.Login/src/LoginContent.jsx # web/ASC.Web.Login/src/sub-components/register-container.js # yarn.lock
2020-12-15 15:40:27 +00:00
import history from "../history";
import TopLoaderService from "@appserver/components/top-loading-indicator";
export const toUrlParams = (obj, skipNull) => {
let str = "";
for (var key in obj) {
2021-04-15 07:27:23 +00:00
if (skipNull && !obj[key]) continue;
if (str !== "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
};
export function getObjectByLocation(location) {
if (!location.search || !location.search.length) return null;
const searchUrl = location.search.substring(1);
const decodedString = decodeURIComponent(searchUrl)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\\/g, "\\\\");
const object = JSON.parse(`{"${decodedString}"}`);
return object;
}
export function changeLanguage(
i18n,
currentLng = localStorage.getItem(LANGUAGE)
) {
return currentLng
? i18n.language !== currentLng
? i18n.changeLanguage(currentLng)
: Promise.resolve((...args) => i18n.t(...args))
: i18n.changeLanguage("en");
}
2020-09-30 21:44:49 +00:00
export function createPasswordHash(password, hashSettings) {
if (
!password ||
!hashSettings ||
typeof password !== "string" ||
typeof hashSettings !== "object" ||
!hashSettings.hasOwnProperty("salt") ||
!hashSettings.hasOwnProperty("size") ||
!hashSettings.hasOwnProperty("iterations") ||
typeof hashSettings.size !== "number" ||
typeof hashSettings.iterations !== "number" ||
typeof hashSettings.salt !== "string"
)
throw new Error("Invalid params.");
2020-09-30 21:44:49 +00:00
const { size, iterations, salt } = hashSettings;
let bits = sjcl.misc.pbkdf2(password, salt, iterations);
bits = bits.slice(0, size / 32);
const hash = sjcl.codec.hex.fromBits(bits);
return hash;
}
2020-12-07 08:11:04 +00:00
export function updateTempContent(isAuth = false) {
if (isAuth) {
2021-02-03 12:42:47 +00:00
const el = document.getElementById("burger-loader-svg");
if (el) {
el.style.display = "block";
}
const el1 = document.getElementById("logo-loader-svg");
if (el1) {
el1.style.display = "block";
}
2020-12-07 08:11:04 +00:00
2021-02-03 12:42:47 +00:00
const el2 = document.getElementById("avatar-loader-svg");
if (el2) {
el2.style.display = "block";
}
2020-12-07 08:11:04 +00:00
} else {
const tempElm = document.getElementById("temp-content");
if (tempElm) {
tempElm.outerHTML = "";
}
}
}
let timer = null;
export function hideLoader() {
if (isMobile) return;
if (timer) {
clearTimeout(timer);
timer = null;
}
TopLoaderService.end();
}
export function showLoader() {
if (isMobile) return;
hideLoader();
timer = setTimeout(() => TopLoaderService.start(), 500);
}
2020-11-17 03:29:24 +00:00
export { withLayoutSize } from "./withLayoutSize";
2020-12-04 11:21:51 +00:00
export function tryRedirectTo(page) {
2020-12-07 08:11:04 +00:00
if (
window.location.pathname === page ||
2020-12-07 08:11:04 +00:00
window.location.pathname.indexOf(page) !== -1
) {
2020-12-04 11:21:51 +00:00
return false;
}
2020-12-07 08:11:04 +00:00
//TODO: check if we already on default page
Merge branch 'develop' into feature/workspaces # Conflicts: # packages/asc-web-common/src/components/FilterInput/FilterInput.js # packages/asc-web-common/src/components/FilterInput/sub-components/SortComboBox.js # packages/asc-web-common/src/components/PageLayout/index.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-body.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-header.js # packages/asc-web-common/src/components/PageLayout/sub-components/article-main-button.js # packages/asc-web-common/src/components/PageLayout/sub-components/section-body.js # packages/asc-web-common/src/components/PageLayout/sub-components/section-header.js # packages/asc-web-common/src/components/PrivateRoute/PrivateRoute.js # products/ASC.Files/Client/package.json # products/ASC.Files/Client/src/components/Article/Body/TreeFolders.js # products/ASC.Files/Client/src/components/pages/DocEditor/index.js # products/ASC.Files/Client/src/components/pages/Home/Section/Filter/index.js # products/ASC.Files/Client/src/components/panels/OperationsPanel/index.js # products/ASC.Files/Client/src/components/panels/SharingPanel/SharingRow.js # products/ASC.Files/Client/src/components/panels/SharingPanel/index.js # products/ASC.Files/Client/src/index.js # products/ASC.Files/Client/src/store/files/actions.js # products/ASC.Files/Client/yarn.lock # products/ASC.People/Client/package.json # products/ASC.People/Client/src/components/pages/Home/Section/Body/index.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/ContactField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/DateField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/EmailField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/RadioField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/TextChangeField.js # products/ASC.People/Client/src/components/pages/ProfileAction/Section/Body/FormFields/TextField.js # products/ASC.People/Client/src/index.js # products/ASC.People/Client/yarn.lock # web/ASC.Web.Client/package.json # web/ASC.Web.Client/src/App.js # web/ASC.Web.Client/src/components/pages/Confirm/index.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/activateEmail.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/changeEmail.js # web/ASC.Web.Client/src/components/pages/Confirm/sub-components/changeOwner.js # web/ASC.Web.Client/src/helpers/confirmRoute.js # web/ASC.Web.Client/src/index.js # web/ASC.Web.Common/package.json # web/ASC.Web.Common/yarn.lock # web/ASC.Web.Components/package.json # web/ASC.Web.Components/yarn.lock # web/ASC.Web.Login/src/LoginContent.jsx # web/ASC.Web.Login/src/sub-components/register-container.js # yarn.lock
2020-12-15 15:40:27 +00:00
//window.location.replace(page);
history.push(page);
2020-12-04 11:21:51 +00:00
2020-12-07 08:11:04 +00:00
return true;
}
export function isMe(user, userName) {
return (
user && user.id && (userName === "@self" || user.userName === userName)
);
}
export function isAdmin(currentUser, currentProductId) {
let productName = null;
switch (currentProductId) {
case "f4d98afd-d336-4332-8778-3c6945c81ea0":
productName = "people";
break;
case "e67be73d-f9ae-4ce1-8fec-1880cb518cb4":
2021-04-30 13:47:47 +00:00
productName = "files";
break;
default:
break;
}
const isProductAdmin =
currentUser.listAdminModules && productName
? currentUser.listAdminModules.includes(productName)
: false;
return currentUser.isAdmin || currentUser.isOwner || isProductAdmin;
}
2021-03-22 14:35:33 +00:00
import combineUrlFunc from "./combineUrl";
export const combineUrl = combineUrlFunc;
2021-04-05 12:49:02 +00:00
export function getCookie(name) {
let matches = document.cookie.match(
new RegExp(
"(?:^|; )" +
name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, "\\$1") +
"=([^;]*)"
)
);
return matches ? decodeURIComponent(matches[1]) : undefined;
}
export function setCookie(name, value, options = {}) {
options = {
path: "/",
...options,
};
if (options.expires instanceof Date) {
options.expires = options.expires.toUTCString();
}
let updatedCookie =
encodeURIComponent(name) + "=" + encodeURIComponent(value);
for (let optionKey in options) {
updatedCookie += "; " + optionKey;
let optionValue = options[optionKey];
if (optionValue !== true) {
updatedCookie += "=" + optionValue;
}
}
document.cookie = updatedCookie;
}
export function deleteCookie(name) {
setCookie(name, "", {
"max-age": -1,
});
}
export function clickBackdrop() {
var elms = document.getElementsByClassName("backdrop-active");
if (elms && elms.length > 0) {
elms[0].click();
}
}
export function objectToGetParams(object) {
const params = Object.entries(object)
.filter(([, value]) => value !== undefined && value !== null)
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
);
return params.length > 0 ? `?${params.join("&")}` : "";
}
export function toCommunityHostname(hostname) {
let communityHostname;
try {
communityHostname =
hostname.indexOf("m.") > -1
? hostname.substring(2, hostname.length)
: hostname;
} catch (e) {
console.error(e);
communityHostname = hostname;
}
return communityHostname;
}
export function getProviderTranslation(provider, t) {
switch (provider) {
case "google":
return t("Common:SignInWithGoogle");
case "facebook":
return t("Common:SignInWithFacebook");
case "twitter":
return t("Common:SignInWithTwitter");
case "linkedin":
return t("Common:SignInWithLinkedIn");
2022-02-02 22:10:12 +00:00
case "sso":
return t("Common:SignInWithSso");
}
}
2021-09-07 15:34:30 +00:00
export function getLanguage(lng) {
try {
let language = lng == "en-US" || lng == "en-GB" ? "en" : lng;
const splitted = lng.split("-");
if (splitted.length == 2 && splitted[0] == splitted[1].toLowerCase()) {
language = splitted[0];
}
return language;
} catch (error) {
console.error(error);
}
return lng;
}
export function loadLanguagePath(homepage, fixedNS = null) {
return (lng, ns) => {
const language = getLanguage(lng instanceof Array ? lng[0] : lng);
if (ns.length > 0 && ns[0] === "Common") {
return `/static/locales/${language}/Common.json`;
}
return `${homepage}/locales/${language}/${fixedNS || ns}.json`;
};
}
export function loadScript(url, id, onLoad, onError) {
try {
const script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("id", id);
if (onLoad) script.onload = onLoad;
if (onError) script.onerror = onError;
script.src = url;
script.async = true;
document.body.appendChild(script);
} catch (e) {
console.error(e);
}
}
export function isRetina() {
if (window.devicePixelRatio > 1) return true;
var mediaQuery =
"(-webkit-min-device-pixel-ratio: 1.5),\
(min--moz-device-pixel-ratio: 1.5),\
(-o-min-device-pixel-ratio: 3/2),\
(min-resolution: 1.5dppx),\
(min-device-pixel-ratio: 1.5)";
if (window.matchMedia && window.matchMedia(mediaQuery).matches) return true;
return false;
}
export function convertLanguage(key) {
switch (key) {
case "en-US":
return "en";
case "ru-RU":
return "ru";
case "de-DE":
return "de";
case "it-IT":
return "it";
case "fr-FR":
return "fr";
}
return key;
}
import FilesFilter from "../api/files/filter";
export function getFolderOptions(folderId, filter) {
if (folderId && typeof folderId === "string") {
folderId = encodeURIComponent(folderId.replace(/\\\\/g, "\\"));
}
const params =
filter && filter instanceof FilesFilter
? `${folderId}?${filter.toApiUrlParams()}`
: folderId;
const options = {
method: "get",
url: `/files/${params}`,
};
return options;
}
export function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function isElementInViewport(el) {
if (!el) return;
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
export function assign(obj, keyPath, value) {
const lastKeyIndex = keyPath.length - 1;
for (let i = 0; i < lastKeyIndex; ++i) {
const key = keyPath[i];
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}