GamesPs.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Cache = require('../libs/cache');
  4. const Setting = require('./Setting');
  5. const { eventSolutions } = require('../triangle/eventSolutions');
  6. const { calcTotalProfit, calcTotalProfitWithFixedFirst } = require('../triangle/totalProfitCalc');
  7. const { getSetting, updateSetting } = require('../triangle/settings');
  8. const fs = require('fs');
  9. const path = require('path');
  10. const GamesCacheFile = path.join(__dirname, '../data/games.cache');
  11. const DevGameTastFile = path.join(__dirname, '../data/gameTast.json');
  12. const childOptions = process.env.NODE_ENV == 'development' ? {
  13. execArgv: ['--inspect=9230'],
  14. stdio: ['pipe', 'pipe', 'pipe', 'ipc']
  15. } : {};
  16. const { fork } = require('child_process');
  17. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  18. const PS_IOR_KEYS = [
  19. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  20. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  21. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  22. ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
  23. ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
  24. ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
  25. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  26. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  27. ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
  28. ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
  29. ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
  30. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
  31. ];
  32. const IOR_KEYS_TYPE = {
  33. A: 1, L: 1,
  34. D: 2, K: 2,
  35. }
  36. // 测试环境
  37. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  38. const IS_DEV = process.env.NODE_ENV == 'development';
  39. const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
  40. const GAMES = {
  41. Leagues: {},
  42. Baselist: {},
  43. Relations: {},
  44. Solutions: {},
  45. ObOriginalData: {},
  46. UpdateTimestamp: {},
  47. };
  48. const Request = {
  49. callbacks: {},
  50. count: 0,
  51. }
  52. /**
  53. * 精确浮点数字
  54. * @param {number} number
  55. * @param {number} x
  56. * @returns {number}
  57. */
  58. const fixFloat = (number, x=2) => {
  59. return parseFloat(number.toFixed(x));
  60. }
  61. /**
  62. * 获取市场类型
  63. */
  64. const getMarketType = (mk) => {
  65. if (mk == 0) {
  66. return 'early';
  67. }
  68. else if (mk == 2) {
  69. return 'rollball';
  70. }
  71. return 'today';
  72. }
  73. /**
  74. * 获取策略类型
  75. */
  76. const getRuleType = (rule) => {
  77. const rulePrefix = rule.split(':')[0];
  78. return IOR_KEYS_TYPE[rulePrefix];
  79. }
  80. /**
  81. * 关键词匹配比赛
  82. */
  83. const matchGame = (relation, sk) => {
  84. const keys = [];
  85. Object.keys(relation).forEach(platform => {
  86. const { leagueName, teamHomeName, teamAwayName } = relation[platform];
  87. if (platform == 'ps') {
  88. keys.push(leagueName);
  89. }
  90. keys.push(teamHomeName, teamAwayName);
  91. });
  92. return keys.some(key => key.includes(sk));
  93. }
  94. /**
  95. * 同步联赛列表
  96. */
  97. const syncLeaguesList = ({ mk, leagues }) => {
  98. if (IS_DEV) {
  99. return Logs.out('syncLeaguesList', { mk, leagues });
  100. }
  101. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  102. .then(res => {
  103. // Logs.out('syncLeaguesList', res.data);
  104. })
  105. .catch(err => {
  106. Logs.out('syncLeaguesList', err.message);
  107. });
  108. }
  109. /**
  110. * 更新联赛列表
  111. */
  112. const updateLeaguesList = ({ mk, leagues, platform='ps' }) => {
  113. const { Leagues } = GAMES;
  114. if (!Leagues[platform]) {
  115. Leagues[platform] = {};
  116. }
  117. const leaguesMap = Leagues[platform];
  118. const nowTime = Date.now();
  119. const expireTime = nowTime - 1000 * 60 * 5;
  120. if (!leaguesMap[mk]) {
  121. leaguesMap[mk] = {
  122. timestamp: 0,
  123. leagues: [],
  124. };
  125. }
  126. if (leaguesMap[mk].timestamp < expireTime ||
  127. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  128. leaguesMap[mk].leagues = leagues;
  129. leaguesMap[mk].timestamp = nowTime;
  130. if (platform == 'ps') {
  131. syncLeaguesList({ mk, leagues });
  132. }
  133. return leagues.length;
  134. }
  135. return 0;
  136. }
  137. /**
  138. * 获取筛选过的联赛
  139. */
  140. const getFilteredLeagues = async (mk) => {
  141. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  142. .then(res => {
  143. if (res.data.code == 0) {
  144. return res.data.data;
  145. }
  146. return Promise.reject(new Error(res.data.message));
  147. });
  148. }
  149. /**
  150. * 更新OB原始数据
  151. */
  152. const updateOriginalData = ({ leagues, matches }) => {
  153. const { ObOriginalData } = GAMES;
  154. ObOriginalData.leagues = leagues;
  155. ObOriginalData.matches = matches;
  156. ObOriginalData.timestamp = Date.now();
  157. }
  158. /**
  159. * 获取OB原始数据
  160. */
  161. const getOriginalData = () => {
  162. const { ObOriginalData } = GAMES;
  163. return ObOriginalData;
  164. }
  165. /**
  166. * 同步比赛列表到服务器
  167. */
  168. const syncGamesList = ({ platform, mk, games }) => {
  169. if (IS_DEV) {
  170. return Logs.out('syncGamesList', { platform, mk, games });
  171. }
  172. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  173. .then(res => {
  174. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  175. })
  176. .catch(err => {
  177. Logs.out('syncGamesList', { platform, mk }, err.message);
  178. });
  179. }
  180. /**
  181. * 同步基准比赛列表
  182. */
  183. const syncBaseList = ({ marketType, games }) => {
  184. const baseList = GAMES.Baselist;
  185. // 直接创建新列表
  186. if (!baseList[marketType]) {
  187. baseList[marketType] = games;
  188. return;
  189. }
  190. const newMap = new Map(games.map(item => [item.eventId, item]));
  191. // 删除不存在的项
  192. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  193. if (!newMap.has(baseList[marketType][i].eventId)) {
  194. baseList[marketType].splice(i, 1);
  195. }
  196. }
  197. // 添加或更新
  198. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  199. games.forEach(game => {
  200. if (!oldIds.has(game.eventId)) {
  201. // 添加新项
  202. baseList[marketType].push(game);
  203. }
  204. });
  205. }
  206. /**
  207. * 清理基准比赛列表
  208. */
  209. // const cleanupBaseList = () => {
  210. // const baseList = GAMES.Baselist;
  211. // const nowTime = Date.now();
  212. // const expireTime = nowTime - 1000*60*60*3;
  213. // Object.keys(baseList).forEach(marketType => {
  214. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  215. // });
  216. // }
  217. /**
  218. * 更新比赛列表
  219. */
  220. const updateGamesList = (({ platform, mk, games } = {}) => {
  221. return new Promise((resolve, reject) => {
  222. if (!platform || !games) {
  223. return reject(new Error('PLATFORM_GAMES_INVALID'));
  224. }
  225. syncGamesList({ platform, mk, games });
  226. resolve();
  227. });
  228. });
  229. /**
  230. * 提交盘口数据
  231. */
  232. // const submitOdds = ({ platform, mk, games }) => {
  233. // if (IS_DEV) {
  234. // return Logs.out('syncOdds', { platform, mk, games });
  235. // }
  236. // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  237. // .then(res => {
  238. // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  239. // })
  240. // .catch(err => {
  241. // Logs.out('syncOdds', { platform, mk }, err.message);
  242. // });
  243. // }
  244. /**
  245. * 同步基准盘口
  246. */
  247. const syncBaseEvents = ({ mk, games, outrights }) => {
  248. const {
  249. expireTimeEvents, expireTimeSpecial,
  250. subsidyTime, subsidyAmount,
  251. subsidyRbWmAmount, subsidyRbOtAmount
  252. } = getSetting();
  253. const nowTime = Date.now();
  254. const marketType = getMarketType(mk);
  255. const baseList = GAMES.Baselist;
  256. if (!baseList[marketType]) {
  257. return 0;
  258. }
  259. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  260. games?.forEach(game => {
  261. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  262. const baseGame = baseMap.get(eventId);
  263. if (baseGame) {
  264. const { mk, timestamp } = baseGame;
  265. const isRb = (mk == 2);
  266. const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  267. Object.keys(events).forEach(ior => {
  268. // 滚球胜平负补水
  269. if (isRb && (ior.startsWith('ior_r') || ior.startsWith('ior_m') || ior.startsWith('ior_wm')) && subsidyRbWmAmount) {
  270. const sourceOdds = events[ior].v;
  271. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  272. events[ior].s = sourceOdds
  273. }
  274. // 滚球进球数补水
  275. // API采集特殊盘口用
  276. else if (isRb && ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  277. const sourceOdds = events[ior].v;
  278. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  279. events[ior].s = sourceOdds
  280. }
  281. // 赛前进球数补水
  282. // API采集特殊盘口用
  283. else if (!isRb && isSubsidy && ior.startsWith('ior_ot') && subsidyAmount) {
  284. const sourceOdds = events[ior].v;
  285. events[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  286. events[ior].s = sourceOdds
  287. }
  288. });
  289. baseGame.originId = originId;
  290. baseGame.stage = stage;
  291. baseGame.retime = retime;
  292. baseGame.score = score;
  293. baseGame.wm = wm;
  294. baseGame.evtime = evtime;
  295. baseGame.events = events;
  296. }
  297. });
  298. // 浏览器采集特殊盘口用的
  299. // outrights?.forEach(outright => {
  300. // const { parentId, sptime, special } = outright;
  301. // const baseGame = baseMap.get(parentId);
  302. // if (baseGame) { // 赛前特殊盘口
  303. // const { timestamp } = baseGame;
  304. // const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  305. // if (isSubsidy) {
  306. // Object.keys(special).forEach(ior => {
  307. // if (ior.startsWith('ior_ot') && subsidyAmount) {
  308. // const sourceOdds = special[ior].v;
  309. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  310. // special[ior].s = sourceOdds
  311. // }
  312. // });
  313. // }
  314. // baseGame.sptime = sptime;
  315. // baseGame.special = special;
  316. // }
  317. // else {
  318. // const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  319. // const originBaseGame = originBaseMap.get(parentId);
  320. // if (originBaseGame) { // 滚球特殊盘口
  321. // Object.keys(special).forEach(ior => {
  322. // if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
  323. // const sourceOdds = special[ior].v;
  324. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  325. // special[ior].s = sourceOdds
  326. // }
  327. // else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  328. // const sourceOdds = special[ior].v;
  329. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  330. // special[ior].s = sourceOdds
  331. // }
  332. // });
  333. // originBaseGame.sptime = sptime;
  334. // originBaseGame.special = special;
  335. // }
  336. // }
  337. // });
  338. if (games?.length) {
  339. const gamesList = baseList[marketType]?.map(game => {
  340. const { evtime, events, sptime, special, ...gameInfo } = game;
  341. const expireTimeEv = nowTime - expireTimeEvents;
  342. const expireTimeSP = nowTime - expireTimeSpecial;
  343. let odds = {};
  344. if (evtime > expireTimeEv) {
  345. odds = { ...odds, ...events };
  346. }
  347. if (sptime > expireTimeSP) {
  348. odds = { ...odds, ...special };
  349. }
  350. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  351. let match = keys.map(key => {
  352. return {
  353. key,
  354. value: odds[key]?.v ?? 0,
  355. origin: odds[key]?.r,
  356. source: odds[key]?.s,
  357. }
  358. });
  359. if (label == 'jqs') {
  360. match = match.filter(item => item.value !== 0);
  361. }
  362. return {
  363. label,
  364. match
  365. };
  366. }).filter(item => {
  367. if (item.label == 'jqs') {
  368. return item.match.length;
  369. }
  370. else {
  371. return item.match.every(entry => entry.value !== 0);
  372. }
  373. });
  374. game.matches = matches; // matches 也记录下来
  375. let uptime = evtime ?? 0;
  376. return { ...gameInfo, matches, uptime };
  377. });
  378. // if (gamesList.filter(item => item.uptime > 0).length) {
  379. // // if (mk == 2) {
  380. // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  381. // // }
  382. // submitOdds({ platform: 'ps', mk, games: gamesList });
  383. // }
  384. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  385. if (!relatedGames.length) {
  386. return 0;
  387. }
  388. let update = 0;
  389. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  390. gamesList?.forEach(game => {
  391. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  392. const relatedGame = relatedMap.get(eventId);
  393. if (relatedGame) {
  394. const events = {};
  395. matches.forEach(({ label, match }) => {
  396. match.forEach(({ key, value, origin, source }) => {
  397. events[key] = {
  398. v: value,
  399. r: origin,
  400. s: source
  401. };
  402. });
  403. });
  404. relatedGame.evtime = uptime;
  405. relatedGame.events = events;
  406. relatedGame.stage = stage;
  407. relatedGame.retime = retime;
  408. relatedGame.score = score;
  409. relatedGame.wm = wm;
  410. update ++;
  411. }
  412. });
  413. return update;
  414. }
  415. }
  416. const updateBaseEvents = ({ games, timestamp }) => {
  417. return new Promise((resolve, reject) => {
  418. if (!games) {
  419. return reject(new Error('GAMES_INVALID'));
  420. }
  421. if (!timestamp) {
  422. return reject(new Error('TIMESTAMP_INVALID'));
  423. }
  424. let update = 0;
  425. const { UpdateTimestamp } = GAMES;
  426. const tp = 'ps_9_9';
  427. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  428. UpdateTimestamp[tp] = timestamp;
  429. }
  430. else {
  431. return resolve({ update });
  432. }
  433. Object.keys(games).forEach(mk => {
  434. update += syncBaseEvents({ mk, games: games[mk] ?? [] });
  435. });
  436. resolve({ update });
  437. });
  438. }
  439. /**
  440. * 比较外盘与内盘的赔率
  441. */
  442. const compareOdds = (events, baseEvents, platform) => {
  443. const setting = getSetting();
  444. const maxDiff = setting[`${platform}MaxDiff`] ?? 0;
  445. Object.keys(events).forEach(ior => {
  446. const value = events[ior].v;
  447. const baseValue = baseEvents[ior]?.s ?? baseEvents[ior]?.v ?? 1;
  448. if (value - baseValue >= maxDiff) {
  449. events[ior].q = 1;
  450. }
  451. else {
  452. events[ior].q = 0;
  453. }
  454. });
  455. }
  456. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  457. return new Promise((resolve, reject) => {
  458. if (!platform || (!games && !outrights)) {
  459. return reject(new Error('PLATFORM_GAMES_INVALID'));
  460. }
  461. const { UpdateTimestamp } = GAMES;
  462. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  463. // Logs.out('updateGamesEvents', { tp, timestamp });
  464. UpdateTimestamp[tp] = timestamp;
  465. }
  466. else {
  467. return resolve({ update: 0 });
  468. }
  469. if (platform == 'ps') {
  470. const update = syncBaseEvents({ mk, games, outrights });
  471. return resolve({ update });
  472. }
  473. const relatedGames = Object.values(GAMES.Relations).map(item => {
  474. // item.rel?.[platform] ?? {}
  475. const { rel } = item ?? {};
  476. if (!rel) {
  477. return {};
  478. }
  479. const game = rel[platform] ?? {};
  480. game.baseId = rel['ps']?.eventId;
  481. return game;
  482. });
  483. if (!relatedGames.length) {
  484. return resolve({ update: 0 });
  485. }
  486. const updateCount = {
  487. update: 0
  488. };
  489. const marketType = getMarketType(mk);
  490. const baseList = GAMES.Baselist[marketType] ?? [];
  491. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  492. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  493. games?.forEach(game => {
  494. const { eventId, evtime, events, stage, retime, score, wm } = game;
  495. const relatedGame = relatedMap.get(eventId);
  496. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  497. compareOdds(events, baseEvents, platform);
  498. if (relatedGame) {
  499. relatedGame.evtime = evtime;
  500. relatedGame.events = events;
  501. relatedGame.stage = stage;
  502. relatedGame.retime = retime;
  503. relatedGame.score = score;
  504. relatedGame.wm = wm;
  505. updateCount.update ++;
  506. }
  507. });
  508. outrights?.forEach(outright => {
  509. const { parentId, sptime, special } = outright;
  510. const relatedGame = relatedMap.get(parentId);
  511. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  512. compareOdds(special, baseEvents, platform);
  513. if (relatedGame) {
  514. relatedGame.sptime = sptime;
  515. relatedGame.special = special;
  516. updateCount.update ++;
  517. }
  518. });
  519. resolve(updateCount);
  520. });
  521. }
  522. /**
  523. * 获取比赛盘口
  524. */
  525. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  526. if (!relIds.length) {
  527. return null;
  528. }
  529. const idSet = new Set(relIds);
  530. const relations = { ...GAMES.Relations };
  531. Object.keys(relations).forEach(id => {
  532. if (idSet.size && !idSet.has(+id)) {
  533. delete relations[id];
  534. }
  535. });
  536. if (platform) {
  537. return Object.values(relations).map(rel => rel[platform] ?? {});
  538. }
  539. const gamesEvents = {};
  540. Object.values(relations).forEach(({ rel }) => {
  541. Object.keys(rel).forEach(platform => {
  542. const game = rel[platform] ?? {};
  543. const { eventId, events, special } = game;
  544. if (!gamesEvents[platform]) {
  545. gamesEvents[platform] = {};
  546. }
  547. gamesEvents[platform][eventId] = { ...events, ...special };
  548. });
  549. });
  550. return gamesEvents;
  551. }
  552. /**
  553. * 获取关联比赛
  554. */
  555. const getDevGameTast = () => {
  556. return new Promise((resolve) => {
  557. const data = Cache.getData(DevGameTastFile, true);
  558. resolve({data});
  559. });
  560. }
  561. const fetchGamesRelation = async (mk='') => {
  562. const getGameTast = Promise.all([
  563. getDevGameTast(),
  564. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  565. ]);
  566. return getGameTast.then(([res1, res2]) => {
  567. const resData = res1.data ?? res2.data;
  568. if (resData.code == 0) {
  569. const nowTime = Date.now();
  570. const gamesRelation = resData.data?.filter(item => {
  571. const timestamp = new Date(item.timestamp).getTime();
  572. if (nowTime > timestamp) {
  573. item.mk = 2;
  574. }
  575. item.timestamp = timestamp;
  576. const expireTime = timestamp + 1000*60*60*3;
  577. return expireTime > nowTime;
  578. }).map(item => {
  579. const {
  580. id, mk, league_name,
  581. event_id: ps_event_id,
  582. league_id: ps_league_id,
  583. team_home_name: ps_team_home_name,
  584. team_away_name: ps_team_away_name,
  585. ob_event_id, ob_league_id,
  586. ob_team_home_name,
  587. ob_team_away_name,
  588. hg_event_id, hg_league_id,
  589. hg_team_home_name,
  590. hg_team_away_name,
  591. timestamp,
  592. } = item;
  593. const rel = {
  594. ps: {
  595. eventId: +ps_event_id,
  596. leagueId: +ps_league_id,
  597. leagueName: league_name,
  598. teamHomeName: ps_team_home_name,
  599. teamAwayName: ps_team_away_name,
  600. timestamp
  601. },
  602. ob: ob_event_id ? {
  603. eventId: +ob_event_id,
  604. leagueId: +ob_league_id,
  605. leagueName: league_name,
  606. teamHomeName: ob_team_home_name,
  607. teamAwayName: ob_team_away_name,
  608. timestamp
  609. } : null,
  610. hg: hg_event_id ? {
  611. eventId: +hg_event_id,
  612. leagueId: +hg_league_id,
  613. leagueName: league_name,
  614. teamHomeName: hg_team_home_name,
  615. teamAwayName: hg_team_away_name,
  616. timestamp
  617. } : null
  618. };
  619. return { id: ps_event_id, mk, rel, timestamp };
  620. }) ?? [];
  621. return gamesRelation;
  622. }
  623. return Promise.reject(new Error(resData.message));
  624. });
  625. }
  626. const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
  627. let idsSet = null;
  628. if (ids?.length) {
  629. idsSet = new Set(ids);
  630. }
  631. const relations = Object.values(GAMES.Relations).filter(item => {
  632. if (idsSet && !idsSet.has(item.id)) {
  633. return false;
  634. }
  635. return mk == -1 || item.mk == mk;
  636. }).sort((a, b) => a.timestamp - b.timestamp);
  637. if (listEvents) {
  638. return relations;
  639. }
  640. const gamesRelation = relations.map(item => {
  641. const { rel, ...relationInfo } = item;
  642. const tempRel = { ...rel };
  643. Object.keys(tempRel).forEach(platform => {
  644. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  645. tempRel[platform] = gameInfo;
  646. });
  647. return { ...relationInfo, rel: tempRel };
  648. });
  649. return gamesRelation;
  650. }
  651. /**
  652. * 定时更新关联比赛列表
  653. */
  654. const updateGamesRelation = () => {
  655. fetchGamesRelation()
  656. .then(gamesRelation => {
  657. const baseList = {};
  658. gamesRelation.map(item => {
  659. const baseGame = item.rel?.['ps'] ?? {};
  660. return { ...baseGame, mk: item.mk };
  661. }).forEach(item => {
  662. const marketType = getMarketType(item.mk);
  663. if (!baseList[marketType]) {
  664. baseList[marketType] = [];
  665. }
  666. baseList[marketType].push(item);
  667. });
  668. Object.keys(baseList).forEach(marketType => {
  669. syncBaseList({ marketType, games: baseList[marketType] });
  670. });
  671. const updateCount = {
  672. add: 0,
  673. update: 0,
  674. delete: 0
  675. };
  676. gamesRelation.forEach(item => {
  677. const { id, mk } = item;
  678. const oldItem = GAMES.Relations[id];
  679. if (!oldItem) {
  680. GAMES.Relations[id] = item;
  681. updateCount.add ++;
  682. }
  683. else if (oldItem.mk != mk) {
  684. GAMES.Relations[id] = item;
  685. updateCount.update ++;
  686. }
  687. });
  688. const relations = new Set(gamesRelation.map(item => +item.id));
  689. Object.keys(GAMES.Relations).forEach(id => {
  690. if (!relations.has(+id)) {
  691. delete GAMES.Relations[id];
  692. updateCount.delete ++;
  693. }
  694. });
  695. if (updateCount.add || updateCount.update || updateCount.delete) {
  696. Logs.out('updateGamesRelation', updateCount);
  697. }
  698. else {
  699. Logs.outDev('updateGamesRelation', updateCount);
  700. }
  701. })
  702. .catch(err => {
  703. Logs.out('updateGamesRelation', err.message);
  704. })
  705. .finally(() => {
  706. setTimeout(updateGamesRelation, 60000);
  707. });
  708. }
  709. updateGamesRelation();
  710. const gamesRelationCleanup = () => {
  711. const relations = Object.values(GAMES.Relations);
  712. const expireTime = Date.now() - 1000*60;
  713. relations.forEach(item => {
  714. const { rel } = item;
  715. Object.keys(rel).forEach(platform => {
  716. const { evtime, sptime } = rel[platform];
  717. if (evtime && evtime < expireTime) {
  718. delete rel[platform].events;
  719. delete rel[platform].evtime;
  720. }
  721. if (sptime && sptime < expireTime) {
  722. delete rel[platform].special;
  723. delete rel[platform].sptime;
  724. }
  725. });
  726. });
  727. }
  728. /**
  729. * 同步比赛结果
  730. */
  731. const syncGamesResult = async (result) => {
  732. if (IS_DEV) {
  733. return Logs.out('updateGamesResult', result);
  734. }
  735. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  736. // .then(res => {
  737. // // Logs.out('syncMatchResult', res.data);
  738. // })
  739. // .catch(err => {
  740. // Logs.out('syncMatchResult', err.message);
  741. // });
  742. }
  743. /**
  744. * 更新比赛结果
  745. */
  746. const updateGamesResult = (result) => {
  747. syncGamesResult(result);
  748. return Promise.resolve();
  749. }
  750. /**
  751. * 同步中单方案
  752. */
  753. // const syncSolutions = (solutions) => {
  754. // if (IS_DEV) {
  755. // return Logs.out('syncSolutions', solutions);
  756. // }
  757. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  758. // .then(res => {
  759. // // Logs.out('syncSolutions', res.data);
  760. // })
  761. // .catch(err => {
  762. // Logs.out('syncSolutions', err.message);
  763. // });
  764. // }
  765. /**
  766. * 更新中单方案
  767. */
  768. const getCprKey = (cpr) => {
  769. const { k, p, v } = cpr;
  770. return `${k}_${p}_${v}`;
  771. }
  772. const compareCpr = (cpr1, cpr2) => {
  773. const key1 = getCprKey(cpr1);
  774. const key2 = getCprKey(cpr2);
  775. return key1 === key2;
  776. }
  777. const updateSolutions = (solutions, eventsLogsMap) => {
  778. if (solutions?.length) {
  779. const solutionsHistory = GAMES.Solutions;
  780. const updateIds = { add: [], update: [], retain: [], remove: [] }
  781. solutions.forEach(item => {
  782. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  783. if (!solutionsHistory[sid]) {
  784. solutionsHistory[sid] = item;
  785. updateIds.add.push(sid);
  786. return;
  787. }
  788. const historySolution = solutionsHistory[sid];
  789. if (historySolution.sol.win_average !== win_average ||
  790. historySolution.sol.win_profit_rate !== win_profit_rate ||
  791. !compareCpr(historySolution.cpr, cpr)) {
  792. solutionsHistory[sid] = item;
  793. updateIds.update.push(sid);
  794. return;
  795. }
  796. const { timestamp } = item;
  797. historySolution.timestamp = timestamp;
  798. updateIds.retain.push(sid);
  799. });
  800. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  801. Object.keys(solutionsHistory).forEach(sid => {
  802. if (!solutionsMap.has(sid)) {
  803. delete solutionsHistory[sid];
  804. updateIds.remove.push(sid);
  805. }
  806. });
  807. const solutionUpdate = {};
  808. Object.keys(updateIds).forEach(key => {
  809. if (key == 'retain' || key == 'remove') {
  810. solutionUpdate[key] = updateIds[key];
  811. }
  812. else {
  813. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  814. }
  815. });
  816. // syncSolutions(solutionUpdate);
  817. if (updateIds.add.length / solutions.length > 0.2 ||
  818. updateIds.remove.length / solutions.length > 0.2
  819. ) {
  820. const { expireEvents, removeEvents } = eventsLogsMap;
  821. const expireEvemtsMap = {};
  822. expireEvents.forEach(item => {
  823. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  824. if (!expireEvemtsMap[mk]) {
  825. expireEvemtsMap[mk] = {};
  826. }
  827. if (!expireEvemtsMap[mk][platform]) {
  828. expireEvemtsMap[mk][platform] = {};
  829. }
  830. if (!expireEvemtsMap[mk][platform].list) {
  831. expireEvemtsMap[mk][platform].list = [];
  832. }
  833. if (!expireEvemtsMap[mk][platform].evtime) {
  834. expireEvemtsMap[mk][platform].evtime = evtime;
  835. }
  836. if (!expireEvemtsMap[mk][platform].sptime) {
  837. expireEvemtsMap[mk][platform].sptime = sptime;
  838. }
  839. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  840. });
  841. Object.keys(expireEvemtsMap).forEach(mk => {
  842. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  843. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  844. mk, platform,
  845. expireEvemtsMap[mk][platform].list.length,
  846. expireEvemtsMap[mk][platform].evtime,
  847. expireEvemtsMap[mk][platform].sptime,
  848. )
  849. });
  850. });
  851. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  852. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  853. }
  854. else {
  855. Logs.outDev('solutions update complete', updateIds);
  856. }
  857. }
  858. }
  859. /**
  860. * 获取中单方案
  861. */
  862. const getSolutions = async ({ win_min, with_events, mk=-1 }) => {
  863. // Logs.out('getSolutions', win_min);
  864. const filterMarketType = +mk;
  865. const { minShowAmount } = getSetting();
  866. const solutionsList = Object.values(GAMES.Solutions);
  867. const gamesRelation = getGamesRelation();
  868. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  869. const mkCount = {
  870. all: 0,
  871. rollball: 0,
  872. today: 0,
  873. early: 0,
  874. }
  875. let solutions = solutionsList.filter(item => {
  876. const { sol: { win_average } } = item;
  877. return win_average >= (win_min ?? minShowAmount);
  878. })
  879. .map(item => {
  880. const { info: { id } } = item;
  881. const { mk, rel } = relationsMap.get(id);
  882. const marketType = getMarketType(mk);
  883. mkCount.all ++;
  884. mkCount[marketType] ++;
  885. return {
  886. ...item,
  887. info: { id, mk, ...rel }
  888. }
  889. });
  890. if (mk >= 0) {
  891. solutions = solutions.filter(item => {
  892. const { info: { mk } } = item;
  893. return mk == filterMarketType;
  894. });
  895. }
  896. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  897. const relIds = solutions.map(item => item.info.id);
  898. let gamesEvents;
  899. if (with_events) {
  900. gamesEvents = getGamesEvents({ relIds });
  901. }
  902. return { solutions, gamesEvents, mkCount };
  903. }
  904. /**
  905. * 获取中单方案并按照比赛分组
  906. */
  907. const getGamesSolutions = async ({ win_min, with_events, mk=-1, tp=0, sk }) => {
  908. const filterMarketType = +mk;
  909. const filterDataType = +tp;
  910. const { minShowAmount } = getSetting();
  911. const solutionsList = Object.values(GAMES.Solutions);
  912. const gamesRelation = getGamesRelation({ listEvents: with_events });
  913. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  914. const mkCount = {
  915. all: 0,
  916. rollball: 0,
  917. today: 0,
  918. early: 0,
  919. }
  920. const solutionsMap = {};
  921. solutionsList.forEach(item => {
  922. const { info: { id }, ...solution } = item;
  923. const { rule, sol: { win_average } } = solution;
  924. const ruleType = getRuleType(rule);
  925. if ((filterDataType == 0 || filterDataType == ruleType) && (!!sk || win_average >= (win_min ?? minShowAmount))) {
  926. const gameRelation = relationsMap.get(id);
  927. if (!solutionsMap[id]) {
  928. solutionsMap[id] = { ...gameRelation, solutions: [] };
  929. }
  930. solutionsMap[id].solutions.push(solution);
  931. }
  932. })
  933. const gamesSolutions = Object.values(solutionsMap)
  934. .filter(item => {
  935. const { mk, rel, solutions } = item;
  936. const marketType = getMarketType(mk);
  937. if (!sk || matchGame(rel, sk)) {
  938. mkCount.all ++;
  939. mkCount[marketType] ++;
  940. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  941. return filterMarketType == -1 || filterMarketType == mk;
  942. }
  943. return false;
  944. })
  945. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  946. return { gamesSolutions, mkCount };
  947. }
  948. /**
  949. * 获取单个中单方案
  950. */
  951. const getSolution = async (sid) => {
  952. if (!sid) {
  953. return Promise.reject(new Error('sid is required'));
  954. }
  955. const solution = GAMES.Solutions[sid];
  956. if (!solution) {
  957. return Promise.reject(new Error('solution not found'));
  958. }
  959. return solution;
  960. }
  961. /**
  962. * 通过比赛 ID 获取中单方案
  963. */
  964. const getSolutionsByIds = async (ids) => {
  965. const baseList = Object.values(GAMES.Baselist).flat();
  966. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  967. const result = {};
  968. ids.forEach(id => {
  969. const baseGame = baseMap.get(id);
  970. result[id] = {};
  971. result[id].matches = baseGame?.matches ?? [];
  972. result[id].sols = [];
  973. });
  974. Object.values(GAMES.Solutions).forEach(item => {
  975. const { info: { id } } = item;
  976. if (result[id]) {
  977. result[id].sols.push(item);
  978. }
  979. });
  980. return result;
  981. }
  982. /**
  983. * 清理中单方案
  984. */
  985. const solutionsCleanup = () => {
  986. const solutionsHistory = GAMES.Solutions;
  987. const updateIds = { remove: [] }
  988. Object.keys(solutionsHistory).forEach(sid => {
  989. const { timestamp } = solutionsHistory[sid];
  990. const nowTime = Date.now();
  991. if (nowTime - timestamp > 1000*60) {
  992. delete solutionsHistory[sid];
  993. updateIds.remove.push(sid);
  994. return;
  995. }
  996. const solution = solutionsHistory[sid];
  997. const eventTime = solution.info.timestamp;
  998. if (nowTime > eventTime) {
  999. delete solutionsHistory[sid];
  1000. updateIds.remove.push(sid);
  1001. }
  1002. });
  1003. // if (updateIds.remove.length) {
  1004. // syncSolutions(updateIds);
  1005. // }
  1006. }
  1007. /**
  1008. * 清理更新时间戳
  1009. */
  1010. const cleanupUpdateTimestamp = () => {
  1011. const updateTimestamp = GAMES.UpdateTimestamp;
  1012. const nowTime = Date.now();
  1013. const expireTime = nowTime - 1000*60;
  1014. Object.keys(updateTimestamp).forEach(key => {
  1015. if (updateTimestamp[key] < expireTime) {
  1016. delete updateTimestamp[key];
  1017. }
  1018. });
  1019. }
  1020. /**
  1021. * 定时清理中单方案
  1022. * 定时清理盘口信息
  1023. */
  1024. setInterval(() => {
  1025. // cleanupBaseList();
  1026. solutionsCleanup();
  1027. gamesRelationCleanup();
  1028. cleanupUpdateTimestamp();
  1029. }, 1000*30);
  1030. /**
  1031. * 获取综合利润
  1032. */
  1033. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  1034. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1035. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1036. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1037. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1038. return profit;
  1039. }
  1040. /**
  1041. * 通过 sid 获取综合利润
  1042. */
  1043. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  1044. const preSolution = GAMES.Solutions[sid1];
  1045. const subSolution = GAMES.Solutions[sid2];
  1046. const sol1 = preSolution?.sol;
  1047. const sol2 = subSolution?.sol;
  1048. if (!sol1) {
  1049. return Promise.reject(new Error('sid1 已失效'));
  1050. }
  1051. if (!sol2) {
  1052. return Promise.reject(new Error('sid2 已失效'));
  1053. }
  1054. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1055. return { profit, solutions: [preSolution, subSolution] };
  1056. }
  1057. /**
  1058. * 通过盘口信息获取综合利润
  1059. */
  1060. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  1061. if (!betInfo1?.cross_type) {
  1062. return Promise.reject(new Error('第一个下注信息无效'));
  1063. }
  1064. if (!betInfo2?.cross_type) {
  1065. return Promise.reject(new Error('第二个下注信息无效'));
  1066. }
  1067. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1068. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1069. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1070. if (fixed) {
  1071. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  1072. }
  1073. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  1074. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1075. }
  1076. /**
  1077. * 同步Qboss平台配置
  1078. */
  1079. const syncQbossConfig = () => {
  1080. const setting = getSetting();
  1081. if (!setting.syncSettingEnabled) {
  1082. // Logs.outDev('syncQbossConfig disabled');
  1083. return setTimeout(syncQbossConfig, 1000*5);
  1084. }
  1085. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  1086. .then(res => {
  1087. const { data } = res;
  1088. if (!data?.data) {
  1089. throw new Error('syncQbossConfig data is empty');
  1090. }
  1091. const {
  1092. qboss_return_ratio,
  1093. ob_return_ratio, ob_return_type, ob_odds_more_than,
  1094. hg_return_ratio, hg_return_type, hg_odds_more_than,
  1095. pc_return_ratio, pc_return_type,
  1096. qboss_jq_add_odds, qboss_jq_add_hours,
  1097. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1098. } = data.data;
  1099. const qbossSetting = {
  1100. innerRebateRatio: +qboss_return_ratio,
  1101. obRebateRatio: +ob_return_ratio,
  1102. obRebateType: +ob_return_type,
  1103. obMaxDiff: +ob_odds_more_than,
  1104. hgRebateRatio: +hg_return_ratio,
  1105. hgRebateType: +hg_return_type,
  1106. hgMaxDiff: +hg_odds_more_than,
  1107. pcRebateRatio: +pc_return_ratio,
  1108. pcRebateType: +pc_return_type,
  1109. subsidyTime: +qboss_jq_add_hours,
  1110. subsidyAmount: +qboss_jq_add_odds,
  1111. subsidyRbWmAmount: +qboss_gq_add_dy_odds,
  1112. subsidyRbOtAmount: +qboss_gq_add_jq_odds,
  1113. };
  1114. const settingFields = {};
  1115. let needUpdate = false;
  1116. Object.keys(qbossSetting).forEach(key => {
  1117. if (qbossSetting[key] !== setting[key]) {
  1118. settingFields[key] = qbossSetting[key];
  1119. needUpdate = true;
  1120. }
  1121. });
  1122. if (needUpdate) {
  1123. Setting.update(settingFields);
  1124. // Logs.outDev('syncQbossConfig', settingFields);
  1125. }
  1126. // else {
  1127. // Logs.outDev('syncQbossConfig no change');
  1128. // }
  1129. })
  1130. .catch(err => {
  1131. Logs.out('syncQbossConfig error', err.message);
  1132. })
  1133. .finally(() => {
  1134. setTimeout(syncQbossConfig, 1000*15);
  1135. });
  1136. }
  1137. syncQbossConfig();
  1138. /**
  1139. * 异常通知
  1140. */
  1141. const notifyException = (message) => {
  1142. if (IS_DEV) {
  1143. return Logs.out('notifyException', { message });
  1144. }
  1145. const chat_id = -1003032820471;
  1146. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  1147. .then(() => {
  1148. Logs.out('notifyException', '通知成功');
  1149. })
  1150. .catch(err => {
  1151. Logs.out('notifyException', err.message);
  1152. });
  1153. }
  1154. /**
  1155. * 从子进程获取数据
  1156. */
  1157. const getDataFromChild = (type, callback) => {
  1158. const id = ++Request.count;
  1159. Request.callbacks[id] = callback;
  1160. events_child.send({ method: 'get', id, type });
  1161. }
  1162. /**
  1163. * 向子进程发送数据
  1164. */
  1165. const postDataToChild = (type, data) => {
  1166. events_child.send({ method: 'post', type, data });
  1167. }
  1168. /**
  1169. * 处理子进程消息
  1170. */
  1171. events_child.on('message', async (message) => {
  1172. const { callbacks } = Request;
  1173. const { method, id, type, data } = message;
  1174. if (method == 'get' && id) {
  1175. let responseData = null;
  1176. if (type == 'getGamesRelation') {
  1177. responseData = getGamesRelation({ listEvents: true });
  1178. }
  1179. else if (type == 'getSetting') {
  1180. responseData = getSetting();
  1181. }
  1182. // else if (type == 'getSolutionHistory') {
  1183. // responseData = getSolutionHistory();
  1184. // }
  1185. events_child.send({ type: 'response', id, data: responseData });
  1186. }
  1187. else if (method == 'post') {
  1188. if (type == 'updateSolutions') {
  1189. updateSolutions(data.solutions, data.eventsLogsMap);
  1190. }
  1191. }
  1192. else if (method == 'response' && id && callbacks[id]) {
  1193. callbacks[id](data);
  1194. delete callbacks[id];
  1195. }
  1196. });
  1197. events_child.stderr?.on('data', data => {
  1198. Logs.out('events_child stderr', data.toString());
  1199. });
  1200. const settingUpdate = (fields) => {
  1201. updateSetting(fields);
  1202. postDataToChild('updateSetting', fields);
  1203. }
  1204. const syncSetting = async () => {
  1205. const setting = await Setting.get();
  1206. settingUpdate(setting.toObject());
  1207. }
  1208. syncSetting();
  1209. Setting.onUpdate(settingUpdate);
  1210. /**
  1211. * 保存GAMES数据到缓存文件
  1212. */
  1213. const saveGamesToCache = () => {
  1214. Cache.setData(GamesCacheFile, GAMES, err => {
  1215. if (err) {
  1216. Logs.out('Failed to save games cache:', err.message);
  1217. }
  1218. else {
  1219. Logs.out('Games cache saved successfully');
  1220. }
  1221. });
  1222. }
  1223. /**
  1224. * 从缓存文件加载GAMES数据
  1225. */
  1226. const loadGamesFromCache = () => {
  1227. const gamesCacheData = Cache.getData(GamesCacheFile, true) ?? {};
  1228. Object.keys(GAMES).forEach(key => {
  1229. if (key in gamesCacheData) {
  1230. GAMES[key] = gamesCacheData[key];
  1231. }
  1232. });
  1233. Logs.out('Games cache loaded successfully');
  1234. }
  1235. // 在模块加载时尝试从缓存恢复数据
  1236. loadGamesFromCache();
  1237. // 监听进程退出事件,保存GAMES数据
  1238. process.on('exit', saveGamesToCache);
  1239. process.on('SIGINT', () => {
  1240. process.exit(0);
  1241. });
  1242. process.on('SIGTERM', () => {
  1243. process.exit(0);
  1244. });
  1245. process.on('SIGUSR2', () => {
  1246. process.exit(0);
  1247. });
  1248. module.exports = {
  1249. updateLeaguesList, getFilteredLeagues,
  1250. updateGamesList, updateGamesEvents, updateBaseEvents,
  1251. getGamesRelation,
  1252. updateGamesResult,
  1253. updateOriginalData, getOriginalData,
  1254. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1255. getTotalProfitWithSid,
  1256. getTotalProfitWithBetInfo,
  1257. notifyException,
  1258. }