Helper.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import { CASH_BASE } from '@scripts/constants/App';
  2. import { CURRENCY_TYPE } from '@scripts/define/Define';
  3. import { native, sys } from 'cc';
  4. import { ANDROID, IOS } from 'cc/env';
  5. const STORAGE_ENCRYPTION_HEAD = 'a6072637';
  6. const STORAGE_ENCRYPTION_PASSWORD = 'xbd4jl';
  7. const STORAGE_ENCRYPTION_ENABLED = true;
  8. /** 在按钮点击回调中调用;Web 使用 Clipboard API,原生使用引擎剪贴板接口。 */
  9. export async function copyTextToClipboard(text: string): Promise<boolean> {
  10. if (!text) return false;
  11. if (sys.isNative) {
  12. try {
  13. if (typeof native.copyTextToClipboard !== 'function') return false;
  14. native.copyTextToClipboard(text);
  15. return true;
  16. } catch (error) {
  17. console.warn('[Clipboard] Native copy failed', error);
  18. return false;
  19. }
  20. }
  21. if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
  22. try {
  23. await navigator.clipboard.writeText(text);
  24. return true;
  25. } catch {
  26. // 权限受限或旧浏览器时尝试兼容方式。
  27. }
  28. }
  29. if (typeof document === 'undefined' || !document.body) return false;
  30. const previousFocus = document.activeElement as HTMLElement | null;
  31. const textarea = document.createElement('textarea');
  32. textarea.value = text;
  33. textarea.readOnly = true;
  34. textarea.style.cssText = 'position:fixed;top:0;left:0;opacity:0;font-size:16px;pointer-events:none;';
  35. document.body.appendChild(textarea);
  36. try {
  37. textarea.focus({ preventScroll: true });
  38. textarea.select();
  39. textarea.setSelectionRange(0, text.length);
  40. return document.execCommand('copy');
  41. } catch {
  42. return false;
  43. } finally {
  44. textarea.remove();
  45. previousFocus?.focus({ preventScroll: true });
  46. }
  47. }
  48. /**
  49. * 将数字格式化为财务展示格式:使用千位分隔符并保留两位小数。
  50. * 例如:1234567.8 -> 1,234,567.80。
  51. */
  52. export function formatCurrency(value: number | string, decimal = 0): string {
  53. if (typeof value === 'string') value = Number(value);
  54. if (!Number.isFinite(value)) value = 0;
  55. return value.toLocaleString('en-US', {
  56. minimumFractionDigits: decimal,
  57. maximumFractionDigits: decimal,
  58. useGrouping: true,
  59. });
  60. }
  61. export function formatSCNum(value: number | string, unit = false) {
  62. if (unit) {
  63. return formatCurrency(value, 2) + CURRENCY_TYPE.SC
  64. }
  65. return formatCurrency(value, 2);
  66. }
  67. export function formatGCNum(value: number | string) {
  68. return formatCurrency(value, 0);
  69. }
  70. export function formatCash(value: number) {
  71. value = Math.floor(value / CASH_BASE);
  72. return formatCurrency(value, 2);
  73. }
  74. const SHORT_MONTH_NAMES = [
  75. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  76. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
  77. ];
  78. /** Converts `YYYY-MM-DD HH:mm:ss.SSS` into `Mon D, HH:mm`. */
  79. export function formatShortDateTime(value: string): string {
  80. const match = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2})/);
  81. if (!match) return '';
  82. const month = Number(match[2]);
  83. const day = Number(match[3]);
  84. const hour = Number(match[4]);
  85. const minute = Number(match[5]);
  86. if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return '';
  87. return `${SHORT_MONTH_NAMES[month - 1]} ${day}, ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  88. }
  89. export function formatTimestamp(timestamp: number): string {
  90. // 1. 将秒转换为毫秒
  91. const date = new Date(timestamp);
  92. // 2. 获取各项时间分量并补零
  93. const hours = String(date.getHours()).padStart(2, '0');
  94. const minutes = String(date.getMinutes()).padStart(2, '0');
  95. const seconds = String(date.getSeconds()).padStart(2, '0');
  96. const day = String(date.getDate()).padStart(2, '0');
  97. // getMonth() 返回的月份是从 0 开始的 (0-11),所以需要 +1
  98. const month = String(date.getMonth() + 1).padStart(2, '0');
  99. const year = date.getFullYear();
  100. // 3. 按 hh:mm:ss dd-mm-yyyy 格式拼接
  101. return `${hours}:${minutes}:${seconds} ${day}-${month}-${year}`;
  102. }
  103. /**
  104. * 商品货币显示
  105. * 小于 10,000 时展示完整数值;小于 1,000,000 时向下取整为 K;
  106. * 其余数值向下截取到 0.01M,并固定展示两位小数。
  107. * @param value 商品数量
  108. */
  109. export function formatGoodsNum(value: number): string {
  110. if (!Number.isFinite(value)) value = 0;
  111. if (value < 10_000) {
  112. let decimal = value % 1 > 0 ? 2 : 0;
  113. return value.toLocaleString('en-US', {
  114. minimumFractionDigits: decimal,
  115. maximumFractionDigits: 20,
  116. useGrouping: true,
  117. });
  118. }
  119. if (value < 1_000_000) {
  120. return `${Math.floor(value / 1_000)}K`;
  121. }
  122. return `${(Math.floor(value / 10_000) / 100).toFixed(2)}M`;
  123. }
  124. /**
  125. * 读取本地数据,并兼容 game_web_us2 写入的加密格式。
  126. */
  127. export function localStorageGet<T = string>(key: string, defaultValue: T = '' as T): string | T {
  128. let value = sys.localStorage.getItem(key);
  129. if (value === null) return defaultValue;
  130. if (value.startsWith(STORAGE_ENCRYPTION_HEAD)) {
  131. try {
  132. value = decrypt(value.substring(STORAGE_ENCRYPTION_HEAD.length));
  133. } catch {
  134. // 与原项目保持一致:解密失败时返回空字符串。
  135. value = '';
  136. }
  137. }
  138. return value;
  139. }
  140. /**
  141. * 加密并保存本地数据。空字符串不加密,行为与 game_web_us2 保持一致。
  142. */
  143. export function localStorageSet(key: string, value: unknown): void {
  144. let storageValue = value;
  145. if (STORAGE_ENCRYPTION_ENABLED && storageValue !== null && storageValue !== '') {
  146. const plainValue = typeof storageValue === 'string' ? storageValue : String(storageValue);
  147. storageValue = plainValue;
  148. try {
  149. storageValue = STORAGE_ENCRYPTION_HEAD + encrypt(plainValue);
  150. } catch {
  151. // 加密失败时沿用原值保存,兼容原项目行为。
  152. }
  153. }
  154. sys.localStorage.setItem(key, String(storageValue));
  155. }
  156. export function localStorageRemove(key: string): void {
  157. sys.localStorage.removeItem(key);
  158. }
  159. function encrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  160. if (value === '') return '';
  161. const source = encodeURIComponent(value);
  162. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  163. if (encodedPassword.length === 0) return '';
  164. let randomSeed = '';
  165. for (let index = 0; index < encodedPassword.length; index += 1) {
  166. randomSeed += encodedPassword.charCodeAt(index).toString();
  167. }
  168. const seedPosition = Math.floor(randomSeed.length / 5);
  169. const multiplier = Number.parseInt(
  170. randomSeed.charAt(seedPosition)
  171. + randomSeed.charAt(seedPosition * 2)
  172. + randomSeed.charAt(seedPosition * 3)
  173. + randomSeed.charAt(seedPosition * 4)
  174. + randomSeed.charAt(seedPosition * 5),
  175. 10,
  176. );
  177. const increment = Math.ceil(encodedPassword.length / 2);
  178. const modulus = Math.pow(2, 31) - 1;
  179. if (multiplier < 2) return '';
  180. let salt = Math.round(Math.random() * 1_000_000_000) % 100_000_000;
  181. randomSeed += salt;
  182. randomSeed = reduceSeed(randomSeed);
  183. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  184. let encrypted = '';
  185. for (let index = 0; index < source.length; index += 1) {
  186. const encryptedChar = source.charCodeAt(index) ^ Math.floor((pseudoRandom / modulus) * 255);
  187. encrypted += encryptedChar < 16
  188. ? `0${encryptedChar.toString(16)}`
  189. : encryptedChar.toString(16);
  190. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  191. }
  192. let saltHex = salt.toString(16);
  193. while (saltHex.length < 8) saltHex = `0${saltHex}`;
  194. return encrypted + saltHex;
  195. }
  196. function decrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  197. if (value === '') return '';
  198. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  199. if (value.length < 8 || encodedPassword.length === 0) return '';
  200. let randomSeed = '';
  201. for (let index = 0; index < encodedPassword.length; index += 1) {
  202. randomSeed += encodedPassword.charCodeAt(index).toString();
  203. }
  204. const seedPosition = Math.floor(randomSeed.length / 5);
  205. const multiplier = Number.parseInt(
  206. randomSeed.charAt(seedPosition)
  207. + randomSeed.charAt(seedPosition * 2)
  208. + randomSeed.charAt(seedPosition * 3)
  209. + randomSeed.charAt(seedPosition * 4)
  210. + randomSeed.charAt(seedPosition * 5),
  211. 10,
  212. );
  213. const increment = Math.round(encodedPassword.length / 2);
  214. const modulus = Math.pow(2, 31) - 1;
  215. const salt = Number.parseInt(value.substring(value.length - 8), 16);
  216. const encrypted = value.substring(0, value.length - 8);
  217. randomSeed += salt;
  218. randomSeed = reduceSeed(randomSeed);
  219. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  220. let decrypted = '';
  221. for (let index = 0; index < encrypted.length; index += 2) {
  222. const decryptedChar = Number.parseInt(encrypted.substring(index, index + 2), 16)
  223. ^ Math.floor((pseudoRandom / modulus) * 255);
  224. decrypted += String.fromCharCode(decryptedChar);
  225. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  226. }
  227. return decodeURIComponent(decrypted);
  228. }
  229. function reduceSeed(seed: string): string {
  230. let result = seed;
  231. while (result.length > 10) {
  232. let remaining = result;
  233. let total = 0;
  234. while (remaining.length > 0) {
  235. total += Number.parseInt(remaining.substring(0, 10), 10);
  236. remaining = remaining.substring(10);
  237. }
  238. result = total.toString();
  239. }
  240. return result;
  241. }
  242. /**
  243. * 进入平台判定:0=普通浏览器 1=iOS壳包 2=Android壳包 3=PWA(桌面图标/TWA 进入)
  244. * 用于按来源差异化展示(如提现页官网引流提示:桌面图标进入的玩家不显示)。
  245. * 壳包判定优先于 PWA;TWA 判定内联实现,避免 helpers→UAUtils 循环依赖。
  246. */
  247. export function getEnterPlatform(): 0 | 1 | 2 | 3 {
  248. if (ANDROID) return 2;
  249. if (IOS) return 1;
  250. return 0;
  251. }
  252. export function createUUID() {
  253. const chars: string[] = [];
  254. const hexDigits = '0123456789abcdef';
  255. for (let index = 0; index < 36; index += 1) {
  256. chars[index] = hexDigits.charAt(
  257. Math.floor(Math.random() * 16),
  258. );
  259. }
  260. // UUID version 4:0100
  261. chars[14] = '4';
  262. // RFC variant:10xx
  263. const variant = (Number.parseInt(chars[19], 16) & 0x3) | 0x8;
  264. chars[19] = hexDigits.charAt(variant);
  265. chars[8] = '-';
  266. chars[13] = '-';
  267. chars[18] = '-';
  268. chars[23] = '-';
  269. return chars.join('');
  270. }
  271. export function getUrlParams(url: string) {
  272. const queryIndex = url.indexOf('?');
  273. const params = {};
  274. if (queryIndex >= 0) {
  275. url.slice(queryIndex + 1).split('&').forEach((entry) => {
  276. if (!entry) return;
  277. const separatorIndex = entry.indexOf('=');
  278. const rawKey = separatorIndex >= 0 ? entry.slice(0, separatorIndex) : entry;
  279. const rawValue = separatorIndex >= 0 ? entry.slice(separatorIndex + 1) : '';
  280. try {
  281. const key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
  282. params[key] = decodeURIComponent(rawValue.replace(/\+/g, ' '));
  283. } catch {
  284. // Preserve malformed values instead of crashing the native callback.
  285. params[rawKey] = rawValue;
  286. }
  287. });
  288. }
  289. return params;
  290. }
  291. export function toUrlParams(obj: any) {
  292. const params = new URLSearchParams();
  293. for (const key in obj) {
  294. console.log(key, obj[key]);
  295. if (!obj[key]) continue;
  296. const value = encodeURIComponent(String(obj[key]));
  297. params.append(encodeURIComponent(key), value)
  298. }
  299. return params.toString();
  300. }
  301. export function waitForSeconds(duration: number) {
  302. return new Promise((resolve, reject) => {
  303. setTimeout(resolve, duration * 1000)
  304. })
  305. }
  306. export function formatMaskContent(content: string, prefix: number, suffix: number) {
  307. const startIdx = Math.min(prefix, content.length);
  308. const endIdx = content.length - suffix;
  309. const first = content.substring(0, startIdx);
  310. const last = content.substring(endIdx, content.length)
  311. return `${first}***${last}`
  312. }
  313. export function formatMaskNickName(nickName: string) {
  314. return formatMaskContent(nickName, 2, 1);
  315. }
  316. export function formatMaskEmail(email: string) {
  317. if (!email || email.length === 0) return '';
  318. let index = email.indexOf('@');
  319. if (index === -1) return formatMaskContent(email, 2, 3);
  320. return formatMaskContent(email, 2, email.length - index);
  321. }
  322. export function checkIsEmail(str: string): boolean {
  323. const s = str.trim();
  324. if (!s) return false;
  325. const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  326. return reg.test(s);
  327. }
  328. export function safeFloor(num: number, decimal = 2) {
  329. let unit = Math.pow(10, decimal);
  330. return Math.floor(num * unit) / unit
  331. }
  332. export function formatMailTimeToMMDDYYYY(timeStr: string): string {
  333. const date = new Date(timeStr);
  334. if (isNaN(date.getTime())) {
  335. return ""; // 无效时间返回空
  336. }
  337. const month = String(date.getMonth() + 1).padStart(2, "0");
  338. const day = String(date.getDate()).padStart(2, "0");
  339. const year = date.getFullYear();
  340. return `${month}-${day}-${year}`;
  341. }
  342. export function parseMailRewardStr(str: string) {
  343. const result = [];
  344. const itemStrList = str.split(";").filter(Boolean);
  345. for (const itemStr of itemStrList) {
  346. const parts = itemStr.split(",");
  347. if (parts.length !== 2) continue;
  348. const type = parts[0]; // 直接字符串,不转数字!
  349. const rawRewardStr = parts[1];
  350. const rawReward = Number(rawRewardStr);
  351. if (isNaN(rawReward)) continue;
  352. if (rawReward == 0) continue;
  353. result.push({
  354. type,
  355. reward: rawReward / 100,
  356. rawReward: rawRewardStr
  357. });
  358. }
  359. return result;
  360. }