Helper.ts 8.2 KB

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