GamesPs.js 38 KB

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