utils.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import { Toast } from '@douyinfe/semi-ui';
  2. import { toastConstants } from '../constants';
  3. import React from 'react';
  4. import { toast } from 'react-toastify';
  5. const HTMLToastContent = ({ htmlContent }) => {
  6. return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  7. };
  8. export default HTMLToastContent;
  9. export function isAdmin() {
  10. let user = localStorage.getItem('user');
  11. if (!user) return false;
  12. user = JSON.parse(user);
  13. return user.role >= 10;
  14. }
  15. export function isRoot() {
  16. let user = localStorage.getItem('user');
  17. if (!user) return false;
  18. user = JSON.parse(user);
  19. return user.role >= 100;
  20. }
  21. export function getSystemName() {
  22. let system_name = localStorage.getItem('system_name');
  23. if (!system_name) return 'New API';
  24. return system_name;
  25. }
  26. export function getLogo() {
  27. let logo = localStorage.getItem('logo');
  28. if (!logo) return '/logo.png';
  29. return logo;
  30. }
  31. export function getUserIdFromLocalStorage() {
  32. let user = localStorage.getItem('user');
  33. if (!user) return -1;
  34. user = JSON.parse(user);
  35. return user.id;
  36. }
  37. export function getFooterHTML() {
  38. return localStorage.getItem('footer_html');
  39. }
  40. export async function copy(text) {
  41. let okay = true;
  42. try {
  43. await navigator.clipboard.writeText(text);
  44. } catch (e) {
  45. try {
  46. // 构建input 执行 复制命令
  47. var _input = window.document.createElement('input');
  48. _input.value = text;
  49. window.document.body.appendChild(_input);
  50. _input.select();
  51. window.document.execCommand('Copy');
  52. window.document.body.removeChild(_input);
  53. } catch (e) {
  54. okay = false;
  55. console.error(e);
  56. }
  57. }
  58. return okay;
  59. }
  60. export function isMobile() {
  61. return window.innerWidth <= 600;
  62. }
  63. let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
  64. let showWarningOptions = { autoClose: toastConstants.WARNING_TIMEOUT };
  65. let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
  66. let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
  67. let showNoticeOptions = { autoClose: false };
  68. if (isMobile()) {
  69. showErrorOptions.position = 'top-center';
  70. // showErrorOptions.transition = 'flip';
  71. showSuccessOptions.position = 'top-center';
  72. // showSuccessOptions.transition = 'flip';
  73. showInfoOptions.position = 'top-center';
  74. // showInfoOptions.transition = 'flip';
  75. showNoticeOptions.position = 'top-center';
  76. // showNoticeOptions.transition = 'flip';
  77. }
  78. export function showError(error) {
  79. console.error(error);
  80. if (error.message) {
  81. if (error.name === 'AxiosError') {
  82. switch (error.response.status) {
  83. case 401:
  84. // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
  85. window.location.href = '/login?expired=true';
  86. break;
  87. case 429:
  88. Toast.error('错误:请求次数过多,请稍后再试!');
  89. break;
  90. case 500:
  91. Toast.error('错误:服务器内部错误,请联系管理员!');
  92. break;
  93. case 405:
  94. Toast.info('本站仅作演示之用,无服务端!');
  95. break;
  96. default:
  97. Toast.error('错误:' + error.message);
  98. }
  99. return;
  100. }
  101. Toast.error('错误:' + error.message);
  102. } else {
  103. Toast.error('错误:' + error);
  104. }
  105. }
  106. export function showWarning(message) {
  107. Toast.warning(message);
  108. }
  109. export function showSuccess(message) {
  110. Toast.success(message);
  111. }
  112. export function showInfo(message) {
  113. Toast.info(message);
  114. }
  115. export function showNotice(message, isHTML = false) {
  116. if (isHTML) {
  117. toast(<HTMLToastContent htmlContent={message} />, showNoticeOptions);
  118. } else {
  119. Toast.info(message);
  120. }
  121. }
  122. export function openPage(url) {
  123. window.open(url);
  124. }
  125. export function removeTrailingSlash(url) {
  126. if (!url) return '';
  127. if (url.endsWith('/')) {
  128. return url.slice(0, -1);
  129. } else {
  130. return url;
  131. }
  132. }
  133. export function getTodayStartTimestamp() {
  134. var now = new Date();
  135. now.setHours(0, 0, 0, 0);
  136. return Math.floor(now.getTime() / 1000);
  137. }
  138. export function timestamp2string(timestamp) {
  139. let date = new Date(timestamp * 1000);
  140. let year = date.getFullYear().toString();
  141. let month = (date.getMonth() + 1).toString();
  142. let day = date.getDate().toString();
  143. let hour = date.getHours().toString();
  144. let minute = date.getMinutes().toString();
  145. let second = date.getSeconds().toString();
  146. if (month.length === 1) {
  147. month = '0' + month;
  148. }
  149. if (day.length === 1) {
  150. day = '0' + day;
  151. }
  152. if (hour.length === 1) {
  153. hour = '0' + hour;
  154. }
  155. if (minute.length === 1) {
  156. minute = '0' + minute;
  157. }
  158. if (second.length === 1) {
  159. second = '0' + second;
  160. }
  161. return (
  162. year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  163. );
  164. }
  165. export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') {
  166. let date = new Date(timestamp * 1000);
  167. // let year = date.getFullYear().toString();
  168. let month = (date.getMonth() + 1).toString();
  169. let day = date.getDate().toString();
  170. let hour = date.getHours().toString();
  171. if (day === '24') {
  172. console.log('timestamp', timestamp);
  173. }
  174. if (month.length === 1) {
  175. month = '0' + month;
  176. }
  177. if (day.length === 1) {
  178. day = '0' + day;
  179. }
  180. if (hour.length === 1) {
  181. hour = '0' + hour;
  182. }
  183. let str = month + '-' + day;
  184. if (dataExportDefaultTime === 'hour') {
  185. str += ' ' + hour + ':00';
  186. } else if (dataExportDefaultTime === 'week') {
  187. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  188. let nextMonth = (nextWeek.getMonth() + 1).toString();
  189. let nextDay = nextWeek.getDate().toString();
  190. if (nextMonth.length === 1) {
  191. nextMonth = '0' + nextMonth;
  192. }
  193. if (nextDay.length === 1) {
  194. nextDay = '0' + nextDay;
  195. }
  196. str += ' - ' + nextMonth + '-' + nextDay;
  197. }
  198. return str;
  199. }
  200. export function downloadTextAsFile(text, filename) {
  201. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  202. let url = URL.createObjectURL(blob);
  203. let a = document.createElement('a');
  204. a.href = url;
  205. a.download = filename;
  206. a.click();
  207. }
  208. export const verifyJSON = (str) => {
  209. try {
  210. JSON.parse(str);
  211. } catch (e) {
  212. return false;
  213. }
  214. return true;
  215. };
  216. export function verifyJSONPromise(value) {
  217. try {
  218. JSON.parse(value);
  219. return Promise.resolve();
  220. } catch (e) {
  221. return Promise.reject('不是合法的 JSON 字符串');
  222. }
  223. }
  224. export function shouldShowPrompt(id) {
  225. let prompt = localStorage.getItem(`prompt-${id}`);
  226. return !prompt;
  227. }
  228. export function setPromptShown(id) {
  229. localStorage.setItem(`prompt-${id}`, 'true');
  230. }
  231. /**
  232. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  233. * @param {Object} oldObject - 旧对象
  234. * @param {Object} newObject - 新对象
  235. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  236. */
  237. export function compareObjects(oldObject, newObject) {
  238. const changedProperties = [];
  239. // 比较两个对象的属性
  240. for (const key in oldObject) {
  241. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  242. if (oldObject[key] !== newObject[key]) {
  243. changedProperties.push({
  244. key: key,
  245. oldValue: oldObject[key],
  246. newValue: newObject[key],
  247. });
  248. }
  249. }
  250. }
  251. return changedProperties;
  252. }