utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import { Toast } from '@douyinfe/semi-ui';
  2. import { toastConstants } from '../constants';
  3. import React from 'react';
  4. import { toast } from 'react-toastify';
  5. import { THINK_TAG_REGEX, MESSAGE_ROLES } from '../constants/playground.constants';
  6. const HTMLToastContent = ({ htmlContent }) => {
  7. return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  8. };
  9. export default HTMLToastContent;
  10. export function isAdmin() {
  11. let user = localStorage.getItem('user');
  12. if (!user) return false;
  13. user = JSON.parse(user);
  14. return user.role >= 10;
  15. }
  16. export function isRoot() {
  17. let user = localStorage.getItem('user');
  18. if (!user) return false;
  19. user = JSON.parse(user);
  20. return user.role >= 100;
  21. }
  22. export function getSystemName() {
  23. let system_name = localStorage.getItem('system_name');
  24. if (!system_name) return 'New API';
  25. return system_name;
  26. }
  27. export function getLogo() {
  28. let logo = localStorage.getItem('logo');
  29. if (!logo) return '/logo.png';
  30. return logo;
  31. }
  32. export function getUserIdFromLocalStorage() {
  33. let user = localStorage.getItem('user');
  34. if (!user) return -1;
  35. user = JSON.parse(user);
  36. return user.id;
  37. }
  38. export function getFooterHTML() {
  39. return localStorage.getItem('footer_html');
  40. }
  41. export async function copy(text) {
  42. let okay = true;
  43. try {
  44. await navigator.clipboard.writeText(text);
  45. } catch (e) {
  46. try {
  47. // 构建input 执行 复制命令
  48. var _input = window.document.createElement('input');
  49. _input.value = text;
  50. window.document.body.appendChild(_input);
  51. _input.select();
  52. window.document.execCommand('Copy');
  53. window.document.body.removeChild(_input);
  54. } catch (e) {
  55. okay = false;
  56. console.error(e);
  57. }
  58. }
  59. return okay;
  60. }
  61. export function isMobile() {
  62. return window.innerWidth <= 600;
  63. }
  64. let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
  65. let showWarningOptions = { autoClose: toastConstants.WARNING_TIMEOUT };
  66. let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
  67. let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
  68. let showNoticeOptions = { autoClose: false };
  69. if (isMobile()) {
  70. showErrorOptions.position = 'top-center';
  71. // showErrorOptions.transition = 'flip';
  72. showSuccessOptions.position = 'top-center';
  73. // showSuccessOptions.transition = 'flip';
  74. showInfoOptions.position = 'top-center';
  75. // showInfoOptions.transition = 'flip';
  76. showNoticeOptions.position = 'top-center';
  77. // showNoticeOptions.transition = 'flip';
  78. }
  79. export function showError(error) {
  80. console.error(error);
  81. if (error.message) {
  82. if (error.name === 'AxiosError') {
  83. switch (error.response.status) {
  84. case 401:
  85. // 清除用户状态
  86. localStorage.removeItem('user');
  87. // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
  88. window.location.href = '/login?expired=true';
  89. break;
  90. case 429:
  91. Toast.error('错误:请求次数过多,请稍后再试!');
  92. break;
  93. case 500:
  94. Toast.error('错误:服务器内部错误,请联系管理员!');
  95. break;
  96. case 405:
  97. Toast.info('本站仅作演示之用,无服务端!');
  98. break;
  99. default:
  100. Toast.error('错误:' + error.message);
  101. }
  102. return;
  103. }
  104. Toast.error('错误:' + error.message);
  105. } else {
  106. Toast.error('错误:' + error);
  107. }
  108. }
  109. export function showWarning(message) {
  110. Toast.warning(message);
  111. }
  112. export function showSuccess(message) {
  113. Toast.success(message);
  114. }
  115. export function showInfo(message) {
  116. Toast.info(message);
  117. }
  118. export function showNotice(message, isHTML = false) {
  119. if (isHTML) {
  120. toast(<HTMLToastContent htmlContent={message} />, showNoticeOptions);
  121. } else {
  122. Toast.info(message);
  123. }
  124. }
  125. export function openPage(url) {
  126. window.open(url);
  127. }
  128. export function removeTrailingSlash(url) {
  129. if (!url) return '';
  130. if (url.endsWith('/')) {
  131. return url.slice(0, -1);
  132. } else {
  133. return url;
  134. }
  135. }
  136. export function getTodayStartTimestamp() {
  137. var now = new Date();
  138. now.setHours(0, 0, 0, 0);
  139. return Math.floor(now.getTime() / 1000);
  140. }
  141. export function timestamp2string(timestamp) {
  142. let date = new Date(timestamp * 1000);
  143. let year = date.getFullYear().toString();
  144. let month = (date.getMonth() + 1).toString();
  145. let day = date.getDate().toString();
  146. let hour = date.getHours().toString();
  147. let minute = date.getMinutes().toString();
  148. let second = date.getSeconds().toString();
  149. if (month.length === 1) {
  150. month = '0' + month;
  151. }
  152. if (day.length === 1) {
  153. day = '0' + day;
  154. }
  155. if (hour.length === 1) {
  156. hour = '0' + hour;
  157. }
  158. if (minute.length === 1) {
  159. minute = '0' + minute;
  160. }
  161. if (second.length === 1) {
  162. second = '0' + second;
  163. }
  164. return (
  165. year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  166. );
  167. }
  168. export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') {
  169. let date = new Date(timestamp * 1000);
  170. // let year = date.getFullYear().toString();
  171. let month = (date.getMonth() + 1).toString();
  172. let day = date.getDate().toString();
  173. let hour = date.getHours().toString();
  174. if (day === '24') {
  175. console.log('timestamp', timestamp);
  176. }
  177. if (month.length === 1) {
  178. month = '0' + month;
  179. }
  180. if (day.length === 1) {
  181. day = '0' + day;
  182. }
  183. if (hour.length === 1) {
  184. hour = '0' + hour;
  185. }
  186. let str = month + '-' + day;
  187. if (dataExportDefaultTime === 'hour') {
  188. str += ' ' + hour + ':00';
  189. } else if (dataExportDefaultTime === 'week') {
  190. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  191. let nextMonth = (nextWeek.getMonth() + 1).toString();
  192. let nextDay = nextWeek.getDate().toString();
  193. if (nextMonth.length === 1) {
  194. nextMonth = '0' + nextMonth;
  195. }
  196. if (nextDay.length === 1) {
  197. nextDay = '0' + nextDay;
  198. }
  199. str += ' - ' + nextMonth + '-' + nextDay;
  200. }
  201. return str;
  202. }
  203. export function downloadTextAsFile(text, filename) {
  204. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  205. let url = URL.createObjectURL(blob);
  206. let a = document.createElement('a');
  207. a.href = url;
  208. a.download = filename;
  209. a.click();
  210. }
  211. export const verifyJSON = (str) => {
  212. try {
  213. JSON.parse(str);
  214. } catch (e) {
  215. return false;
  216. }
  217. return true;
  218. };
  219. export function verifyJSONPromise(value) {
  220. try {
  221. JSON.parse(value);
  222. return Promise.resolve();
  223. } catch (e) {
  224. return Promise.reject('不是合法的 JSON 字符串');
  225. }
  226. }
  227. export function shouldShowPrompt(id) {
  228. let prompt = localStorage.getItem(`prompt-${id}`);
  229. return !prompt;
  230. }
  231. export function setPromptShown(id) {
  232. localStorage.setItem(`prompt-${id}`, 'true');
  233. }
  234. /**
  235. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  236. * @param {Object} oldObject - 旧对象
  237. * @param {Object} newObject - 新对象
  238. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  239. */
  240. export function compareObjects(oldObject, newObject) {
  241. const changedProperties = [];
  242. // 比较两个对象的属性
  243. for (const key in oldObject) {
  244. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  245. if (oldObject[key] !== newObject[key]) {
  246. changedProperties.push({
  247. key: key,
  248. oldValue: oldObject[key],
  249. newValue: newObject[key],
  250. });
  251. }
  252. }
  253. }
  254. return changedProperties;
  255. }
  256. // playground message
  257. // 生成唯一ID
  258. let messageId = 4;
  259. export const generateMessageId = () => `${messageId++}`;
  260. // 提取消息中的文本内容
  261. export const getTextContent = (message) => {
  262. if (!message || !message.content) return '';
  263. if (Array.isArray(message.content)) {
  264. const textContent = message.content.find(item => item.type === 'text');
  265. return textContent?.text || '';
  266. }
  267. return typeof message.content === 'string' ? message.content : '';
  268. };
  269. // 处理 think 标签
  270. export const processThinkTags = (content, reasoningContent = '') => {
  271. if (!content || !content.includes('<think>')) {
  272. return { content, reasoningContent };
  273. }
  274. const thoughts = [];
  275. const replyParts = [];
  276. let lastIndex = 0;
  277. let match;
  278. THINK_TAG_REGEX.lastIndex = 0;
  279. while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
  280. replyParts.push(content.substring(lastIndex, match.index));
  281. thoughts.push(match[1]);
  282. lastIndex = match.index + match[0].length;
  283. }
  284. replyParts.push(content.substring(lastIndex));
  285. const processedContent = replyParts.join('').replace(/<\/?think>/g, '').trim();
  286. const thoughtsStr = thoughts.join('\n\n---\n\n');
  287. const processedReasoningContent = reasoningContent && thoughtsStr
  288. ? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
  289. : reasoningContent || thoughtsStr;
  290. return {
  291. content: processedContent,
  292. reasoningContent: processedReasoningContent
  293. };
  294. };
  295. // 处理未完成的 think 标签
  296. export const processIncompleteThinkTags = (content, reasoningContent = '') => {
  297. if (!content) return { content: '', reasoningContent };
  298. const lastOpenThinkIndex = content.lastIndexOf('<think>');
  299. if (lastOpenThinkIndex === -1) {
  300. return processThinkTags(content, reasoningContent);
  301. }
  302. const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
  303. if (!fragmentAfterLastOpen.includes('</think>')) {
  304. const unclosedThought = fragmentAfterLastOpen.substring('<think>'.length).trim();
  305. const cleanContent = content.substring(0, lastOpenThinkIndex);
  306. const processedReasoningContent = unclosedThought
  307. ? reasoningContent ? `${reasoningContent}\n\n---\n\n${unclosedThought}` : unclosedThought
  308. : reasoningContent;
  309. return processThinkTags(cleanContent, processedReasoningContent);
  310. }
  311. return processThinkTags(content, reasoningContent);
  312. };
  313. // 构建消息内容(包含图片)
  314. export const buildMessageContent = (textContent, imageUrls = [], imageEnabled = false) => {
  315. if (!textContent && (!imageUrls || imageUrls.length === 0)) {
  316. return '';
  317. }
  318. const validImageUrls = imageUrls.filter(url => url && url.trim() !== '');
  319. if (imageEnabled && validImageUrls.length > 0) {
  320. return [
  321. { type: 'text', text: textContent || '' },
  322. ...validImageUrls.map(url => ({
  323. type: 'image_url',
  324. image_url: { url: url.trim() }
  325. }))
  326. ];
  327. }
  328. return textContent || '';
  329. };
  330. // 创建新消息
  331. export const createMessage = (role, content, options = {}) => ({
  332. role,
  333. content,
  334. createAt: Date.now(),
  335. id: generateMessageId(),
  336. ...options
  337. });
  338. // 创建加载中的助手消息
  339. export const createLoadingAssistantMessage = () => createMessage(
  340. MESSAGE_ROLES.ASSISTANT,
  341. '',
  342. {
  343. reasoningContent: '',
  344. isReasoningExpanded: true,
  345. isThinkingComplete: false,
  346. hasAutoCollapsed: false,
  347. status: 'loading'
  348. }
  349. );
  350. // 检查消息是否包含图片
  351. export const hasImageContent = (message) => {
  352. return message &&
  353. Array.isArray(message.content) &&
  354. message.content.some(item => item.type === 'image_url');
  355. };
  356. // 格式化消息用于API请求
  357. export const formatMessageForAPI = (message) => {
  358. if (!message) return null;
  359. return {
  360. role: message.role,
  361. content: message.content
  362. };
  363. };
  364. // 验证消息是否有效
  365. export const isValidMessage = (message) => {
  366. return message &&
  367. message.role &&
  368. (message.content || message.content === '');
  369. };
  370. // 获取最后一条用户消息
  371. export const getLastUserMessage = (messages) => {
  372. if (!Array.isArray(messages)) return null;
  373. for (let i = messages.length - 1; i >= 0; i--) {
  374. if (messages[i].role === MESSAGE_ROLES.USER) {
  375. return messages[i];
  376. }
  377. }
  378. return null;
  379. };
  380. // 获取最后一条助手消息
  381. export const getLastAssistantMessage = (messages) => {
  382. if (!Array.isArray(messages)) return null;
  383. for (let i = messages.length - 1; i >= 0; i--) {
  384. if (messages[i].role === MESSAGE_ROLES.ASSISTANT) {
  385. return messages[i];
  386. }
  387. }
  388. return null;
  389. };
  390. // 计算相对时间(几天前、几小时前等)
  391. export const getRelativeTime = (publishDate) => {
  392. if (!publishDate) return '';
  393. const now = new Date();
  394. const pubDate = new Date(publishDate);
  395. // 如果日期无效,返回原始字符串
  396. if (isNaN(pubDate.getTime())) return publishDate;
  397. const diffMs = now.getTime() - pubDate.getTime();
  398. const diffSeconds = Math.floor(diffMs / 1000);
  399. const diffMinutes = Math.floor(diffSeconds / 60);
  400. const diffHours = Math.floor(diffMinutes / 60);
  401. const diffDays = Math.floor(diffHours / 24);
  402. const diffWeeks = Math.floor(diffDays / 7);
  403. const diffMonths = Math.floor(diffDays / 30);
  404. const diffYears = Math.floor(diffDays / 365);
  405. // 如果是未来时间,显示具体日期
  406. if (diffMs < 0) {
  407. return formatDateString(pubDate);
  408. }
  409. // 根据时间差返回相应的描述
  410. if (diffSeconds < 60) {
  411. return '刚刚';
  412. } else if (diffMinutes < 60) {
  413. return `${diffMinutes} 分钟前`;
  414. } else if (diffHours < 24) {
  415. return `${diffHours} 小时前`;
  416. } else if (diffDays < 7) {
  417. return `${diffDays} 天前`;
  418. } else if (diffWeeks < 4) {
  419. return `${diffWeeks} 周前`;
  420. } else if (diffMonths < 12) {
  421. return `${diffMonths} 个月前`;
  422. } else if (diffYears < 2) {
  423. return '1 年前';
  424. } else {
  425. // 超过2年显示具体日期
  426. return formatDateString(pubDate);
  427. }
  428. };
  429. // 格式化日期字符串
  430. export const formatDateString = (date) => {
  431. const year = date.getFullYear();
  432. const month = String(date.getMonth() + 1).padStart(2, '0');
  433. const day = String(date.getDate()).padStart(2, '0');
  434. return `${year}-${month}-${day}`;
  435. };
  436. // 格式化日期时间字符串(包含时间)
  437. export const formatDateTimeString = (date) => {
  438. const year = date.getFullYear();
  439. const month = String(date.getMonth() + 1).padStart(2, '0');
  440. const day = String(date.getDate()).padStart(2, '0');
  441. const hours = String(date.getHours()).padStart(2, '0');
  442. const minutes = String(date.getMinutes()).padStart(2, '0');
  443. return `${year}-${month}-${day} ${hours}:${minutes}`;
  444. };