You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Setting.js 15 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import {Tag, Tooltip, message} from "antd";
  15. import {SyncOutlined} from "@ant-design/icons";
  16. import {isMobile as isMobileDevice} from "react-device-detect";
  17. import i18next from "i18next";
  18. import Sdk from "casdoor-js-sdk";
  19. import FileSaver from "file-saver";
  20. import XLSX from "xlsx";
  21. import moment from "moment/moment";
  22. import * as StoreBackend from "./backend/StoreBackend";
  23. export let ServerUrl = "";
  24. export let CasdoorSdk;
  25. export function initServerUrl() {
  26. const hostname = window.location.hostname;
  27. if (hostname === "localhost") {
  28. ServerUrl = `http://${hostname}:14000`;
  29. }
  30. }
  31. export function initCasdoorSdk(config) {
  32. CasdoorSdk = new Sdk(config);
  33. }
  34. function getUrlWithLanguage(url) {
  35. if (url.includes("?")) {
  36. return `${url}&language=${getLanguage()}`;
  37. } else {
  38. return `${url}?language=${getLanguage()}`;
  39. }
  40. }
  41. export function getSignupUrl() {
  42. return getUrlWithLanguage(CasdoorSdk.getSignupUrl());
  43. }
  44. export function getSigninUrl() {
  45. return getUrlWithLanguage(CasdoorSdk.getSigninUrl());
  46. }
  47. export function getUserProfileUrl(userName, account) {
  48. return getUrlWithLanguage(CasdoorSdk.getUserProfileUrl(userName, account));
  49. }
  50. export function getMyProfileUrl(account) {
  51. return getUrlWithLanguage(CasdoorSdk.getMyProfileUrl(account));
  52. }
  53. export function signin() {
  54. return CasdoorSdk.signin(ServerUrl);
  55. }
  56. export function parseJson(s) {
  57. if (s === "") {
  58. return null;
  59. } else {
  60. return JSON.parse(s);
  61. }
  62. }
  63. export function myParseInt(i) {
  64. const res = parseInt(i);
  65. return isNaN(res) ? 0 : res;
  66. }
  67. export function openLink(link) {
  68. // this.props.history.push(link);
  69. const w = window.open("about:blank");
  70. w.location.href = link;
  71. }
  72. export function goToLink(link) {
  73. window.location.href = link;
  74. }
  75. export function goToLinkSoft(ths, link) {
  76. ths.props.history.push(link);
  77. }
  78. export function showMessage(type, text) {
  79. if (type === "") {
  80. return;
  81. } else if (type === "success") {
  82. message.success(text);
  83. } else if (type === "error") {
  84. message.error(text);
  85. }
  86. }
  87. export function isAdminUser(account) {
  88. if (account === undefined || account === null) {
  89. return false;
  90. }
  91. return account.owner === "built-in" || account.isGlobalAdmin === true;
  92. }
  93. export function isLocalAdminUser(account) {
  94. if (account === undefined || account === null) {
  95. return false;
  96. }
  97. return account.isAdmin === true || isAdminUser(account);
  98. }
  99. export function deepCopy(obj) {
  100. if (obj === null) {
  101. showMessage("error", "deepCopy obj is null.");
  102. }
  103. return Object.assign({}, obj);
  104. }
  105. export function insertRow(array, row, i) {
  106. return [...array.slice(0, i), row, ...array.slice(i)];
  107. }
  108. export function addRow(array, row) {
  109. return [...array, row];
  110. }
  111. export function prependRow(array, row) {
  112. return [row, ...array];
  113. }
  114. export function deleteRow(array, i) {
  115. // return array = array.slice(0, i).concat(array.slice(i + 1));
  116. return [...array.slice(0, i), ...array.slice(i + 1)];
  117. }
  118. export function swapRow(array, i, j) {
  119. return [...array.slice(0, i), array[j], ...array.slice(i + 1, j), array[i], ...array.slice(j + 1)];
  120. }
  121. export function trim(str, ch) {
  122. if (str === undefined) {
  123. return undefined;
  124. }
  125. let start = 0;
  126. let end = str.length;
  127. while (start < end && str[start] === ch) {++start;}
  128. while (end > start && str[end - 1] === ch) {--end;}
  129. return (start > 0 || end < str.length) ? str.substring(start, end) : str;
  130. }
  131. export function isMobile() {
  132. // return getIsMobileView();
  133. return isMobileDevice;
  134. }
  135. export function getFormattedDate(date) {
  136. if (date === undefined || date === null) {
  137. return null;
  138. }
  139. date = date.replace("T", " ");
  140. date = date.replace("+08:00", " ");
  141. return date;
  142. }
  143. export function getFormattedDateShort(date) {
  144. return date.slice(0, 10);
  145. }
  146. export function getShortName(s) {
  147. return s.split("/").slice(-1)[0];
  148. }
  149. export function getShortText(s, maxLength = 35) {
  150. if (s.length > maxLength) {
  151. return `${s.slice(0, maxLength)}...`;
  152. } else {
  153. return s;
  154. }
  155. }
  156. function getRandomInt(s) {
  157. let hash = 0;
  158. if (s.length !== 0) {
  159. for (let i = 0; i < s.length; i++) {
  160. const char = s.charCodeAt(i);
  161. hash = ((hash << 5) - hash) + char;
  162. hash = hash & hash;
  163. }
  164. }
  165. return hash;
  166. }
  167. export function getAvatarColor(s) {
  168. const colorList = ["#f56a00", "#7265e6", "#ffbf00", "#00a2ae"];
  169. let random = getRandomInt(s);
  170. if (random < 0) {
  171. random = -random;
  172. }
  173. return colorList[random % 4];
  174. }
  175. export function getLanguage() {
  176. return i18next.language;
  177. }
  178. export function setLanguage(language) {
  179. localStorage.setItem("language", language);
  180. changeMomentLanguage(language);
  181. i18next.changeLanguage(language);
  182. }
  183. export function changeLanguage(language) {
  184. localStorage.setItem("language", language);
  185. changeMomentLanguage(language);
  186. i18next.changeLanguage(language);
  187. window.location.reload(true);
  188. }
  189. export function changeMomentLanguage(lng) {
  190. return;
  191. // if (lng === "zh") {
  192. // moment.locale("zh", {
  193. // relativeTime: {
  194. // future: "%s内",
  195. // past: "%s前",
  196. // s: "几秒",
  197. // ss: "%d秒",
  198. // m: "1分钟",
  199. // mm: "%d分钟",
  200. // h: "1小时",
  201. // hh: "%d小时",
  202. // d: "1天",
  203. // dd: "%d天",
  204. // M: "1个月",
  205. // MM: "%d个月",
  206. // y: "1年",
  207. // yy: "%d年",
  208. // },
  209. // });
  210. // }
  211. }
  212. export function getTag(text, type, state) {
  213. let icon = null;
  214. let style = {};
  215. if (state === "Pending") {
  216. icon = <SyncOutlined spin />;
  217. style = {borderStyle: "dashed", backgroundColor: "white"};
  218. }
  219. if (type === "Read") {
  220. return (
  221. <Tooltip placement="top" title={"Read"}>
  222. <Tag icon={icon} style={style} color={"success"}>
  223. {text}
  224. </Tag>
  225. </Tooltip>
  226. );
  227. } else if (type === "Write") {
  228. return (
  229. <Tooltip placement="top" title={"Write"}>
  230. <Tag icon={icon} style={style} color={"processing"}>
  231. {text}
  232. </Tag>
  233. </Tooltip>
  234. );
  235. } else if (type === "Admin") {
  236. return (
  237. <Tooltip placement="top" title={"Admin"}>
  238. <Tag icon={icon} style={style} color={"error"}>
  239. {text}
  240. </Tag>
  241. </Tooltip>
  242. );
  243. } else {
  244. return null;
  245. }
  246. }
  247. export function getTags(vectors) {
  248. if (!vectors) {
  249. return [];
  250. }
  251. const res = [];
  252. vectors.forEach((vector, i) => {
  253. if (vector.data.length !== 0) {
  254. res.push(
  255. <Tooltip placement="top" title={getShortText(JSON.stringify(vector.data), 500)}>
  256. <Tag color={"success"}>
  257. {vector.name}
  258. </Tag>
  259. </Tooltip>
  260. );
  261. } else {
  262. res.push(
  263. <Tag color={"warning"}>
  264. {vector.name}
  265. </Tag>
  266. );
  267. }
  268. });
  269. return res;
  270. }
  271. export function getLabelTags(labels) {
  272. if (!labels) {
  273. return [];
  274. }
  275. const res = [];
  276. labels.forEach((label, i) => {
  277. res.push(
  278. <Tooltip placement="top" title={getShortText(JSON.stringify(label.text), 500)}>
  279. <Tag color={"processing"}>
  280. {`${label.startTime}: ${label.text !== "" ? label.text : "(Empty)"}`}
  281. </Tag>
  282. </Tooltip>
  283. );
  284. });
  285. return res;
  286. }
  287. export function getPercentage(f) {
  288. if (f === undefined) {
  289. return 0.0;
  290. }
  291. return (100 * f).toFixed(1);
  292. }
  293. function s2ab(s) {
  294. const buf = new ArrayBuffer(s.length);
  295. const view = new Uint8Array(buf);
  296. for (let i = 0; i !== s.length; i++) {
  297. view[i] = s.charCodeAt(i) & 0xFF;
  298. }
  299. return buf;
  300. }
  301. export function sheet2blob(sheet, sheetName) {
  302. const workbook = {
  303. SheetNames: [sheetName],
  304. Sheets: {},
  305. };
  306. workbook.Sheets[sheetName] = sheet;
  307. return workbook2blob(workbook);
  308. }
  309. export function workbook2blob(workbook) {
  310. const wopts = {
  311. bookType: "xlsx",
  312. bookSST: false,
  313. type: "binary",
  314. };
  315. const wbout = XLSX.write(workbook, wopts);
  316. return new Blob([s2ab(wbout)], {type: "application/octet-stream"});
  317. }
  318. export function downloadXlsx(wordset) {
  319. const data = [];
  320. wordset.vectors.forEach((vector, i) => {
  321. const row = {};
  322. row[0] = vector.name;
  323. vector.data.forEach((dataItem, i) => {
  324. row[i + 1] = dataItem;
  325. });
  326. data.push(row);
  327. });
  328. const sheet = XLSX.utils.json_to_sheet(data, {skipHeader: true});
  329. // sheet["!cols"] = [
  330. // { wch: 18 },
  331. // { wch: 7 },
  332. // ];
  333. try {
  334. const blob = sheet2blob(sheet, "vectors");
  335. const fileName = `vectors-${wordset.name}.xlsx`;
  336. FileSaver.saveAs(blob, fileName);
  337. } catch (error) {
  338. showMessage("error", `failed to download: ${error.message}`);
  339. }
  340. }
  341. export function downloadLabels(table) {
  342. const data = [];
  343. table.forEach((label, i) => {
  344. const row = {};
  345. row[0] = label.startTime;
  346. row[1] = label.endTime;
  347. row[2] = label.text;
  348. data.push(row);
  349. });
  350. const sheet = XLSX.utils.json_to_sheet(data, {skipHeader: true});
  351. try {
  352. const blob = sheet2blob(sheet, "labels");
  353. const fileName = `labels-${this.props.video.name}-${table.length}.xlsx`;
  354. FileSaver.saveAs(blob, fileName);
  355. } catch (error) {
  356. showMessage("error", `failed to download: ${error.message}`);
  357. }
  358. }
  359. export const redirectCatchJsonError = async(url) => {
  360. try {
  361. const response = await fetch(url);
  362. const msg = await response.json();
  363. if (response.ok) {
  364. this.props.history.push(url);
  365. } else {
  366. showMessage("error", `error in redirect: ${msg}`);
  367. }
  368. } catch (error) {
  369. showMessage("error", `failed to redirect: ${error.message}`);
  370. }
  371. };
  372. export function toFixed(f, n) {
  373. return parseFloat(f.toFixed(n));
  374. }
  375. export function getRandomName() {
  376. return Math.random().toString(36).slice(-6);
  377. }
  378. export function getFriendlyFileSize(size) {
  379. if (size < 1024) {
  380. return size + " B";
  381. }
  382. const i = Math.floor(Math.log(size) / Math.log(1024));
  383. let num = (size / Math.pow(1024, i));
  384. const round = Math.round(num);
  385. num = round < 10 ? num.toFixed(2) : round < 100 ? num.toFixed(1) : round;
  386. return `${num} ${"KMGTPEZY"[i - 1]}B`;
  387. }
  388. export function getTreeWithParents(tree) {
  389. const res = deepCopy(tree);
  390. res.children = tree.children.map((file, index) => {
  391. file.parent = tree;
  392. return getTreeWithParents(file);
  393. });
  394. return res;
  395. }
  396. export function getTreeWithSearch(tree, s) {
  397. const res = deepCopy(tree);
  398. res.children = tree.children.map((file, index) => {
  399. if (file.children.length === 0) {
  400. if (file.title.includes(s)) {
  401. return file;
  402. } else {
  403. return null;
  404. }
  405. } else {
  406. const tmpTree = getTreeWithSearch(file, s);
  407. if (tmpTree.children.length !== 0) {
  408. return tmpTree;
  409. } else {
  410. if (file.title.includes(s)) {
  411. return file;
  412. } else {
  413. return null;
  414. }
  415. }
  416. }
  417. }).filter((file, index) => {
  418. return file !== null;
  419. });
  420. return res;
  421. }
  422. export function getExtFromPath(path) {
  423. const filename = path.split("/").pop();
  424. if (filename.includes(".")) {
  425. return filename.split(".").pop().toLowerCase();
  426. } else {
  427. return "";
  428. }
  429. }
  430. export function getExtFromFile(file) {
  431. const res = file.title.split(".")[1];
  432. if (res === undefined) {
  433. return "";
  434. } else {
  435. return res;
  436. }
  437. }
  438. export function getFileCategory(file) {
  439. if (file.isLeaf) {
  440. return i18next.t("store:File");
  441. } else {
  442. return i18next.t("store:Folder");
  443. }
  444. }
  445. export function getDistinctArray(arr) {
  446. return [...new Set(arr)];
  447. }
  448. export function getCollectedTime(filename) {
  449. // 20220827_210300_CH~Logo.png
  450. const tokens = filename.split("~");
  451. if (tokens.length < 2) {
  452. return null;
  453. }
  454. const time = tokens[0].slice(0, -3);
  455. const m = new moment(time, "YYYYMMDD_HH:mm:ss");
  456. return m.format();
  457. }
  458. export function getSubject(filename) {
  459. // 20220827_210300_CH~Logo.png
  460. const tokens = filename.split("~");
  461. if (tokens.length < 2) {
  462. return null;
  463. }
  464. const subject = tokens[0].slice(tokens[0].length - 2);
  465. if (subject === "MA") {
  466. return i18next.t("store:Math");
  467. } else if (subject === "CH") {
  468. return i18next.t("store:Chinese");
  469. } else if (subject === "NU") {
  470. return null;
  471. } else {
  472. return subject;
  473. }
  474. }
  475. export function submitStoreEdit(storeObj) {
  476. const store = deepCopy(storeObj);
  477. store.fileTree = undefined;
  478. StoreBackend.updateStore(storeObj.owner, storeObj.name, store)
  479. .then((res) => {
  480. if (res.status === "ok") {
  481. if (res.data) {
  482. showMessage("success", "Successfully saved");
  483. } else {
  484. showMessage("error", "failed to save: server side failure");
  485. }
  486. } else {
  487. showMessage("error", `failed to save: ${res.msg}`);
  488. }
  489. })
  490. .catch(error => {
  491. showMessage("error", `failed to save: ${error}`);
  492. });
  493. }
  494. export const StaticBaseUrl = "https://cdn.casbin.org";
  495. export const Countries = [{label: "English", key: "en", country: "US", alt: "English"},
  496. {label: "中文", key: "zh", country: "CN", alt: "中文"},
  497. {label: "Español", key: "es", country: "ES", alt: "Español"},
  498. {label: "Français", key: "fr", country: "FR", alt: "Français"},
  499. {label: "Deutsch", key: "de", country: "DE", alt: "Deutsch"},
  500. {label: "Indonesia", key: "id", country: "ID", alt: "Indonesia"},
  501. {label: "日本語", key: "ja", country: "JP", alt: "日本語"},
  502. {label: "한국어", key: "ko", country: "KR", alt: "한국어"},
  503. {label: "Русский", key: "ru", country: "RU", alt: "Русский"},
  504. {label: "TiếngViệt", key: "vi", country: "VN", alt: "TiếngViệt"},
  505. {label: "Português", key: "pt", country: "BR", alt: "Português"},
  506. ];
  507. export function getItem(label, key, icon, children, type) {
  508. return {
  509. key,
  510. icon,
  511. children,
  512. label,
  513. type,
  514. };
  515. }

基于Casbin的开源AI领域知识库平台