Helper.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { sys } from 'cc';
  2. import { ANDROID, IOS } from 'cc/env';
  3. const STORAGE_ENCRYPTION_HEAD = 'a6072637';
  4. const STORAGE_ENCRYPTION_PASSWORD = 'xbd4jl';
  5. const STORAGE_ENCRYPTION_ENABLED = true;
  6. /**
  7. * 将数字格式化为财务展示格式:使用千位分隔符并保留两位小数。
  8. * 例如:1234567.8 -> 1,234,567.80。
  9. */
  10. export function formatCurrency(value: number | string, decimal = 0): string {
  11. if (typeof value === 'string') value = Number(value);
  12. if (!Number.isFinite(value)) value = 0;
  13. return value.toLocaleString('en-US', {
  14. minimumFractionDigits: decimal,
  15. maximumFractionDigits: decimal,
  16. useGrouping: true,
  17. });
  18. }
  19. export function formatSCNum(value: number | string) {
  20. return formatCurrency(value, 2);
  21. }
  22. export function formatGCNum(value: number | string) {
  23. return formatCurrency(value, 0);
  24. }
  25. /**
  26. * 商品货币显示
  27. * 小于 10,000 时展示完整数值;小于 1,000,000 时向下取整为 K;
  28. * 其余数值向下截取到 0.01M,并固定展示两位小数。
  29. * @param value 商品数量
  30. */
  31. export function formatGoodsNum(value: number): string {
  32. if (!Number.isFinite(value)) value = 0;
  33. if (value < 10_000) {
  34. return value.toLocaleString('en-US', {
  35. maximumFractionDigits: 20,
  36. useGrouping: true,
  37. });
  38. }
  39. if (value < 1_000_000) {
  40. return `${Math.floor(value / 1_000)}K`;
  41. }
  42. return `${(Math.floor(value / 10_000) / 100).toFixed(2)}M`;
  43. }
  44. /**
  45. * 读取本地数据,并兼容 game_web_us2 写入的加密格式。
  46. */
  47. export function localStorageGet<T = string>(key: string, defaultValue: T = '' as T): string | T {
  48. let value = sys.localStorage.getItem(key);
  49. if (value === null) return defaultValue;
  50. if (value.startsWith(STORAGE_ENCRYPTION_HEAD)) {
  51. try {
  52. value = decrypt(value.substring(STORAGE_ENCRYPTION_HEAD.length));
  53. } catch {
  54. // 与原项目保持一致:解密失败时返回空字符串。
  55. value = '';
  56. }
  57. }
  58. return value;
  59. }
  60. /**
  61. * 加密并保存本地数据。空字符串不加密,行为与 game_web_us2 保持一致。
  62. */
  63. export function localStorageSet(key: string, value: unknown): void {
  64. let storageValue = value;
  65. if (STORAGE_ENCRYPTION_ENABLED && storageValue !== null && storageValue !== '') {
  66. const plainValue = typeof storageValue === 'string' ? storageValue : String(storageValue);
  67. storageValue = plainValue;
  68. try {
  69. storageValue = STORAGE_ENCRYPTION_HEAD + encrypt(plainValue);
  70. } catch {
  71. // 加密失败时沿用原值保存,兼容原项目行为。
  72. }
  73. }
  74. sys.localStorage.setItem(key, String(storageValue));
  75. }
  76. export function localStorageRemove(key: string): void {
  77. sys.localStorage.removeItem(key);
  78. }
  79. function encrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  80. if (value === '') return '';
  81. const source = encodeURIComponent(value);
  82. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  83. if (encodedPassword.length === 0) return '';
  84. let randomSeed = '';
  85. for (let index = 0; index < encodedPassword.length; index += 1) {
  86. randomSeed += encodedPassword.charCodeAt(index).toString();
  87. }
  88. const seedPosition = Math.floor(randomSeed.length / 5);
  89. const multiplier = Number.parseInt(
  90. randomSeed.charAt(seedPosition)
  91. + randomSeed.charAt(seedPosition * 2)
  92. + randomSeed.charAt(seedPosition * 3)
  93. + randomSeed.charAt(seedPosition * 4)
  94. + randomSeed.charAt(seedPosition * 5),
  95. 10,
  96. );
  97. const increment = Math.ceil(encodedPassword.length / 2);
  98. const modulus = Math.pow(2, 31) - 1;
  99. if (multiplier < 2) return '';
  100. let salt = Math.round(Math.random() * 1_000_000_000) % 100_000_000;
  101. randomSeed += salt;
  102. randomSeed = reduceSeed(randomSeed);
  103. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  104. let encrypted = '';
  105. for (let index = 0; index < source.length; index += 1) {
  106. const encryptedChar = source.charCodeAt(index) ^ Math.floor((pseudoRandom / modulus) * 255);
  107. encrypted += encryptedChar < 16
  108. ? `0${encryptedChar.toString(16)}`
  109. : encryptedChar.toString(16);
  110. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  111. }
  112. let saltHex = salt.toString(16);
  113. while (saltHex.length < 8) saltHex = `0${saltHex}`;
  114. return encrypted + saltHex;
  115. }
  116. function decrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  117. if (value === '') return '';
  118. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  119. if (value.length < 8 || encodedPassword.length === 0) return '';
  120. let randomSeed = '';
  121. for (let index = 0; index < encodedPassword.length; index += 1) {
  122. randomSeed += encodedPassword.charCodeAt(index).toString();
  123. }
  124. const seedPosition = Math.floor(randomSeed.length / 5);
  125. const multiplier = Number.parseInt(
  126. randomSeed.charAt(seedPosition)
  127. + randomSeed.charAt(seedPosition * 2)
  128. + randomSeed.charAt(seedPosition * 3)
  129. + randomSeed.charAt(seedPosition * 4)
  130. + randomSeed.charAt(seedPosition * 5),
  131. 10,
  132. );
  133. const increment = Math.round(encodedPassword.length / 2);
  134. const modulus = Math.pow(2, 31) - 1;
  135. const salt = Number.parseInt(value.substring(value.length - 8), 16);
  136. const encrypted = value.substring(0, value.length - 8);
  137. randomSeed += salt;
  138. randomSeed = reduceSeed(randomSeed);
  139. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  140. let decrypted = '';
  141. for (let index = 0; index < encrypted.length; index += 2) {
  142. const decryptedChar = Number.parseInt(encrypted.substring(index, index + 2), 16)
  143. ^ Math.floor((pseudoRandom / modulus) * 255);
  144. decrypted += String.fromCharCode(decryptedChar);
  145. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  146. }
  147. return decodeURIComponent(decrypted);
  148. }
  149. function reduceSeed(seed: string): string {
  150. let result = seed;
  151. while (result.length > 10) {
  152. let remaining = result;
  153. let total = 0;
  154. while (remaining.length > 0) {
  155. total += Number.parseInt(remaining.substring(0, 10), 10);
  156. remaining = remaining.substring(10);
  157. }
  158. result = total.toString();
  159. }
  160. return result;
  161. }
  162. /**
  163. * 进入平台判定:0=普通浏览器 1=iOS壳包 2=Android壳包 3=PWA(桌面图标/TWA 进入)
  164. * 用于按来源差异化展示(如提现页官网引流提示:桌面图标进入的玩家不显示)。
  165. * 壳包判定优先于 PWA;TWA 判定内联实现,避免 helpers→UAUtils 循环依赖。
  166. */
  167. export function getEnterPlatform(): 0 | 1 | 2 | 3 {
  168. if (ANDROID) return 2;
  169. if (IOS) return 1;
  170. return 0;
  171. }
  172. export function createUUID() {
  173. const chars: string[] = [];
  174. const hexDigits = '0123456789abcdef';
  175. for (let index = 0; index < 36; index += 1) {
  176. chars[index] = hexDigits.charAt(
  177. Math.floor(Math.random() * 16),
  178. );
  179. }
  180. // UUID version 4:0100
  181. chars[14] = '4';
  182. // RFC variant:10xx
  183. const variant = (Number.parseInt(chars[19], 16) & 0x3) | 0x8;
  184. chars[19] = hexDigits.charAt(variant);
  185. chars[8] = '-';
  186. chars[13] = '-';
  187. chars[18] = '-';
  188. chars[23] = '-';
  189. return chars.join('');
  190. }
  191. export function getUrlParams(url: string) {
  192. const queryIndex = url.indexOf('?');
  193. const params = {};
  194. if (queryIndex >= 0) {
  195. url.slice(queryIndex + 1).split('&').forEach((entry) => {
  196. if (!entry) return;
  197. const separatorIndex = entry.indexOf('=');
  198. const rawKey = separatorIndex >= 0 ? entry.slice(0, separatorIndex) : entry;
  199. const rawValue = separatorIndex >= 0 ? entry.slice(separatorIndex + 1) : '';
  200. try {
  201. const key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
  202. params[key] = decodeURIComponent(rawValue.replace(/\+/g, ' '));
  203. } catch {
  204. // Preserve malformed values instead of crashing the native callback.
  205. params[rawKey] = rawValue;
  206. }
  207. });
  208. }
  209. return params;
  210. }
  211. export function waitForSeconds(duration: number) {
  212. return new Promise((resolve, reject) => {
  213. setTimeout(resolve, duration * 1000)
  214. })
  215. }
  216. export function formatMaskNickName(nickName: string, prefix = 2, suffix = 1) {
  217. const startIdx = Math.min(prefix, nickName.length);
  218. const endIdx = nickName.length - suffix;
  219. const first = nickName.substring(0, startIdx);
  220. const last = nickName.substring(endIdx, nickName.length)
  221. return `${first}***${last}`
  222. }