GamesPs.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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=9228'],
  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. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  23. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  24. // ['0-1', 'ior_ot_0', 'ior_os_0-1', 'ior_ot_1'],
  25. // ['2-3', 'ior_ot_2', 'ior_os_2-3', 'ior_ot_3'],
  26. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
  27. ];
  28. // 测试环境
  29. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  30. const IS_DEV = process.env.NODE_ENV == 'development';
  31. const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
  32. const GAMES = {
  33. Leagues: {},
  34. Baselist: {},
  35. Relations: {},
  36. Solutions: {},
  37. UpdateTimestamp: {},
  38. };
  39. const Request = {
  40. callbacks: {},
  41. count: 0,
  42. }
  43. /**
  44. * 精确浮点数字
  45. * @param {number} number
  46. * @param {number} x
  47. * @returns {number}
  48. */
  49. const fixFloat = (number, x=2) => {
  50. return parseFloat(number.toFixed(x));
  51. }
  52. /**
  53. * 获取市场类型
  54. */
  55. const getMarketType = (mk) => {
  56. if (mk == 0) {
  57. return 'early';
  58. }
  59. else if (mk == 2) {
  60. return 'rollball';
  61. }
  62. return 'today';
  63. }
  64. /**
  65. * 同步联赛列表
  66. */
  67. const syncLeaguesList = ({ mk, leagues }) => {
  68. if (IS_DEV) {
  69. return Logs.out('syncLeaguesList', { mk, leagues });
  70. }
  71. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  72. .then(res => {
  73. // Logs.out('syncLeaguesList', res.data);
  74. })
  75. .catch(err => {
  76. Logs.out('syncLeaguesList', err.message);
  77. });
  78. }
  79. /**
  80. * 更新联赛列表
  81. */
  82. const updateLeaguesList = ({ mk, leagues }) => {
  83. const leaguesMap = GAMES.Leagues;
  84. const nowTime = Date.now();
  85. const expireTime = nowTime - 1000 * 60 * 5;
  86. if (!leaguesMap[mk]) {
  87. leaguesMap[mk] = {
  88. timestamp: 0,
  89. leagues: [],
  90. };
  91. }
  92. if (leaguesMap[mk].timestamp < expireTime ||
  93. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  94. leaguesMap[mk].leagues = leagues;
  95. leaguesMap[mk].timestamp = nowTime;
  96. syncLeaguesList({ mk, leagues });
  97. return leagues.length;
  98. }
  99. return 0;
  100. }
  101. /**
  102. * 获取筛选过的联赛
  103. */
  104. const getFilteredLeagues = async (mk) => {
  105. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  106. .then(res => {
  107. if (res.data.code == 0) {
  108. return res.data.data;
  109. }
  110. return Promise.reject(new Error(res.data.message));
  111. });
  112. }
  113. /**
  114. * 同步比赛列表到服务器
  115. */
  116. const syncGamesList = ({ platform, mk, games }) => {
  117. if (IS_DEV) {
  118. return Logs.out('syncGamesList', { platform, mk, games });
  119. }
  120. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  121. .then(res => {
  122. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  123. })
  124. .catch(err => {
  125. Logs.out('syncGamesList', { platform, mk }, err.message);
  126. });
  127. }
  128. /**
  129. * 同步基准比赛列表
  130. */
  131. const syncBaseList = ({ marketType, games }) => {
  132. const baseList = GAMES.Baselist;
  133. // 直接创建新列表
  134. if (!baseList[marketType]) {
  135. baseList[marketType] = games;
  136. return;
  137. }
  138. const newMap = new Map(games.map(item => [item.eventId, item]));
  139. // 删除不存在的项
  140. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  141. if (!newMap.has(baseList[marketType][i].eventId)) {
  142. baseList[marketType].splice(i, 1);
  143. }
  144. }
  145. // 添加或更新
  146. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  147. games.forEach(game => {
  148. if (!oldIds.has(game.eventId)) {
  149. // 添加新项
  150. baseList[marketType].push(game);
  151. }
  152. });
  153. }
  154. /**
  155. * 更新比赛列表
  156. */
  157. const updateGamesList = (({ platform, mk, games } = {}) => {
  158. return new Promise((resolve, reject) => {
  159. if (!platform || !games) {
  160. return reject(new Error('PLATFORM_GAMES_INVALID'));
  161. }
  162. syncGamesList({ platform, mk, games });
  163. resolve();
  164. });
  165. });
  166. /**
  167. * 提交盘口数据
  168. */
  169. const submitOdds = ({ platform, mk, games }) => {
  170. if (IS_DEV) {
  171. return Logs.out('syncOdds', { platform, mk, games });
  172. }
  173. axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  174. .then(res => {
  175. // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  176. })
  177. .catch(err => {
  178. Logs.out('syncOdds', { platform, mk }, err.message);
  179. });
  180. }
  181. /**
  182. * 同步基准盘口
  183. */
  184. const syncBaseEvents = ({ mk, games, outrights }) => {
  185. const { expireTimeEvents, expireTimeSpecial } = getSetting();
  186. const marketType = getMarketType(mk);
  187. const baseList = GAMES.Baselist;
  188. if (!baseList[marketType]) {
  189. return;
  190. }
  191. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  192. games?.forEach(game => {
  193. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  194. const baseGame = baseMap.get(eventId);
  195. if (baseGame) {
  196. baseGame.originId = originId;
  197. baseGame.stage = stage;
  198. baseGame.retime = retime;
  199. baseGame.score = score;
  200. baseGame.wm = wm;
  201. baseGame.evtime = evtime;
  202. baseGame.events = events;
  203. }
  204. });
  205. outrights?.forEach(outright => {
  206. const { parentId, sptime, special } = outright;
  207. const baseGame = baseMap.get(parentId);
  208. if (baseGame) {
  209. baseGame.sptime = sptime;
  210. baseGame.special = special;
  211. }
  212. else {
  213. const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  214. const originBaseGame = originBaseMap.get(parentId);
  215. if (originBaseGame) {
  216. originBaseGame.sptime = sptime;
  217. originBaseGame.special = special;
  218. }
  219. }
  220. });
  221. if (games?.length) {
  222. const gamesList = baseList[marketType]?.map(game => {
  223. const { evtime, events, sptime, special, ...gameInfo } = game;
  224. const expireTimeEv = Date.now() - expireTimeEvents;
  225. const expireTimeSP = Date.now() - expireTimeSpecial;
  226. let odds = {};
  227. if (evtime > expireTimeEv) {
  228. odds = { ...odds, ...events };
  229. }
  230. if (sptime > expireTimeSP) {
  231. odds = { ...odds, ...special };
  232. }
  233. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  234. let match = keys.map(key => {
  235. return {
  236. key,
  237. value: odds[key]?.v ?? 0,
  238. origin: odds[key]?.r
  239. }
  240. // if (key.includes('os') && !odds[key]) {
  241. // return { key, value: 1 };
  242. // }
  243. // else {
  244. // return {
  245. // key,
  246. // value: odds[key]?.v ?? 0,
  247. // origin: odds[key]?.r
  248. // }
  249. // }
  250. });
  251. if (label == 'jqs') {
  252. match = match.filter(item => item.value !== 0);
  253. }
  254. return {
  255. label,
  256. match
  257. };
  258. }).filter(item => {
  259. if (item.label == 'jqs') {
  260. return item.match.length;
  261. }
  262. else {
  263. return item.match.every(entry => entry.value !== 0);
  264. }
  265. });
  266. let uptime = evtime ?? 0;
  267. // if (evtime && sptime) {
  268. // uptime = Math.min(evtime, sptime);
  269. // }
  270. // else if (!sptime) {
  271. // uptime = evtime ?? 0;
  272. // }
  273. return { ...gameInfo, matches, uptime };
  274. });
  275. if (gamesList.filter(item => item.uptime > 0).length) {
  276. // if (mk == 2) {
  277. // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  278. // }
  279. submitOdds({ platform: 'ps', mk, games: gamesList });
  280. }
  281. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  282. if (!relatedGames.length) {
  283. return 0;
  284. }
  285. let update = 0;
  286. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  287. gamesList?.forEach(game => {
  288. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  289. const relatedGame = relatedMap.get(eventId);
  290. if (relatedGame) {
  291. const events = {};
  292. matches.forEach(({ label, match }) => {
  293. match.forEach(({ key, value, origin }) => {
  294. events[key] = {
  295. v: value,
  296. r: origin
  297. };
  298. });
  299. });
  300. relatedGame.evtime = uptime;
  301. relatedGame.events = events;
  302. relatedGame.stage = stage;
  303. relatedGame.retime = retime;
  304. relatedGame.score = score;
  305. relatedGame.wm = wm;
  306. update ++;
  307. }
  308. });
  309. return update;
  310. }
  311. }
  312. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  313. return new Promise((resolve, reject) => {
  314. if (!platform || (!games && !outrights)) {
  315. return reject(new Error('PLATFORM_GAMES_INVALID'));
  316. }
  317. const { UpdateTimestamp } = GAMES;
  318. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  319. // Logs.out('updateGamesEvents', { tp, timestamp });
  320. UpdateTimestamp[tp] = timestamp;
  321. }
  322. else {
  323. return resolve({ update: 0 });
  324. }
  325. if (platform == 'ps') {
  326. const update = syncBaseEvents({ mk, games, outrights });
  327. return resolve({ update });
  328. }
  329. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  330. if (!relatedGames.length) {
  331. return resolve({ update: 0 });
  332. }
  333. const updateCount = {
  334. update: 0
  335. };
  336. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  337. games?.forEach(game => {
  338. const { eventId, evtime, events, stage, retime, score, wm } = game;
  339. const relatedGame = relatedMap.get(eventId);
  340. if (relatedGame) {
  341. relatedGame.evtime = evtime;
  342. relatedGame.events = events;
  343. relatedGame.stage = stage;
  344. relatedGame.retime = retime;
  345. relatedGame.score = score;
  346. relatedGame.wm = wm;
  347. updateCount.update ++;
  348. }
  349. });
  350. outrights?.forEach(outright => {
  351. const { parentId, sptime, special } = outright;
  352. const relatedGame = relatedMap.get(parentId);
  353. if (relatedGame) {
  354. relatedGame.sptime = sptime;
  355. relatedGame.special = special;
  356. updateCount.update ++;
  357. }
  358. });
  359. resolve(updateCount);
  360. });
  361. }
  362. /**
  363. * 获取比赛盘口
  364. */
  365. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  366. if (!relIds.length) {
  367. return null;
  368. }
  369. const idSet = new Set(relIds);
  370. const relations = { ...GAMES.Relations };
  371. Object.keys(relations).forEach(id => {
  372. if (idSet.size && !idSet.has(+id)) {
  373. delete relations[id];
  374. }
  375. });
  376. if (platform) {
  377. return Object.values(relations).map(rel => rel[platform] ?? {});
  378. }
  379. const gamesEvents = {};
  380. Object.values(relations).forEach(({ rel }) => {
  381. Object.keys(rel).forEach(platform => {
  382. const game = rel[platform] ?? {};
  383. const { eventId, events, special } = game;
  384. if (!gamesEvents[platform]) {
  385. gamesEvents[platform] = {};
  386. }
  387. gamesEvents[platform][eventId] = { ...events, ...special };
  388. });
  389. });
  390. return gamesEvents;
  391. }
  392. /**
  393. * 获取关联比赛
  394. */
  395. const getDevGameTast = () => {
  396. return new Promise((resolve) => {
  397. const data = Cache.getData(DevGameTastFile, true);
  398. resolve({data});
  399. });
  400. }
  401. const fetchGamesRelation = async (mk='') => {
  402. const getGameTast = Promise.all([
  403. getDevGameTast(),
  404. axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
  405. ]);
  406. return getGameTast.then(([res1, res2]) => {
  407. const resData = res1.data ?? res2.data;
  408. if (resData.code == 0) {
  409. const nowTime = Date.now();
  410. const gamesRelation = resData.data?.filter(item => {
  411. const timestamp = new Date(item.timestamp).getTime();
  412. if (nowTime > timestamp) {
  413. item.mk = 2;
  414. }
  415. item.timestamp = timestamp;
  416. const expireTime = timestamp + 1000*60*60*3;
  417. return expireTime > nowTime;
  418. }).map(item => {
  419. const {
  420. id, mk, league_name,
  421. event_id: ps_event_id,
  422. league_id: ps_league_id,
  423. team_home_name: ps_team_home_name,
  424. team_away_name: ps_team_away_name,
  425. ob_event_id, ob_league_id,
  426. ob_team_home_name,
  427. ob_team_away_name,
  428. hg_event_id, hg_league_id,
  429. hg_team_home_name,
  430. hg_team_away_name,
  431. timestamp,
  432. } = item;
  433. const rel = {
  434. ps: {
  435. eventId: +ps_event_id,
  436. leagueId: +ps_league_id,
  437. leagueName: league_name,
  438. teamHomeName: ps_team_home_name,
  439. teamAwayName: ps_team_away_name,
  440. timestamp
  441. },
  442. ob: ob_event_id ? {
  443. eventId: +ob_event_id,
  444. leagueId: +ob_league_id,
  445. leagueName: league_name,
  446. teamHomeName: ob_team_home_name,
  447. teamAwayName: ob_team_away_name,
  448. timestamp
  449. } : null,
  450. hg: hg_event_id ? {
  451. eventId: +hg_event_id,
  452. leagueId: +hg_league_id,
  453. leagueName: league_name,
  454. teamHomeName: hg_team_home_name,
  455. teamAwayName: hg_team_away_name,
  456. timestamp
  457. } : null
  458. };
  459. return { id: ps_event_id, mk, rel, timestamp };
  460. }) ?? [];
  461. return gamesRelation;
  462. }
  463. return Promise.reject(new Error(resData.message));
  464. });
  465. }
  466. const getGamesRelation = ({ mk, ids, listEvents } = {}) => {
  467. let idsSet = null;
  468. if (ids?.length) {
  469. idsSet = new Set(ids);
  470. }
  471. const relations = Object.values(GAMES.Relations).filter(item => {
  472. if (idsSet && !idsSet.has(item.id)) {
  473. return false;
  474. }
  475. if (typeof(mk) === 'undefined' || mk === '') {
  476. return true;
  477. }
  478. return item.mk == mk;
  479. }).sort((a, b) => a.timestamp - b.timestamp);
  480. if (listEvents) {
  481. return relations;
  482. }
  483. const gamesRelation = relations.map(item => {
  484. const { rel, ...relationInfo } = item;
  485. const tempRel = { ...rel };
  486. Object.keys(tempRel).forEach(platform => {
  487. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  488. tempRel[platform] = gameInfo;
  489. });
  490. return { ...relationInfo, rel: tempRel };
  491. });
  492. return gamesRelation;
  493. }
  494. /**
  495. * 定时更新关联比赛列表
  496. */
  497. const updateGamesRelation = () => {
  498. fetchGamesRelation()
  499. .then(gamesRelation => {
  500. const baseList = {};
  501. gamesRelation.map(item => {
  502. const baseGame = item.rel?.['ps'] ?? {};
  503. return { ...baseGame, mk: item.mk };
  504. }).forEach(item => {
  505. const marketType = getMarketType(item.mk);
  506. if (!baseList[marketType]) {
  507. baseList[marketType] = [];
  508. }
  509. baseList[marketType].push(item);
  510. });
  511. Object.keys(baseList).forEach(marketType => {
  512. syncBaseList({ marketType, games: baseList[marketType] });
  513. });
  514. const updateCount = {
  515. add: 0,
  516. update: 0,
  517. delete: 0
  518. };
  519. gamesRelation.forEach(item => {
  520. const { id, mk } = item;
  521. const oldItem = GAMES.Relations[id];
  522. if (!oldItem) {
  523. GAMES.Relations[id] = item;
  524. updateCount.add ++;
  525. }
  526. else if (oldItem.mk != mk) {
  527. GAMES.Relations[id] = item;
  528. updateCount.update ++;
  529. }
  530. });
  531. const relations = new Set(gamesRelation.map(item => +item.id));
  532. Object.keys(GAMES.Relations).forEach(id => {
  533. if (!relations.has(+id)) {
  534. delete GAMES.Relations[id];
  535. updateCount.delete ++;
  536. }
  537. });
  538. if (updateCount.add || updateCount.update || updateCount.delete) {
  539. Logs.out('updateGamesRelation', updateCount);
  540. }
  541. else {
  542. Logs.outDev('updateGamesRelation', updateCount);
  543. }
  544. })
  545. .catch(err => {
  546. Logs.out('updateGamesRelation', err.message);
  547. })
  548. .finally(() => {
  549. setTimeout(updateGamesRelation, 60000);
  550. });
  551. }
  552. updateGamesRelation();
  553. const gamesRelationCleanup = () => {
  554. const relations = Object.values(GAMES.Relations);
  555. const expireTime = Date.now() - 1000*60;
  556. relations.forEach(item => {
  557. const { rel } = item;
  558. Object.keys(rel).forEach(platform => {
  559. const { evtime, sptime } = rel[platform];
  560. if (evtime && evtime < expireTime) {
  561. delete rel[platform].events;
  562. delete rel[platform].evtime;
  563. }
  564. if (sptime && sptime < expireTime) {
  565. delete rel[platform].special;
  566. delete rel[platform].sptime;
  567. }
  568. });
  569. });
  570. }
  571. /**
  572. * 同步比赛结果
  573. */
  574. const syncGamesResult = async (result) => {
  575. if (IS_DEV) {
  576. return Logs.out('updateGamesResult', result);
  577. }
  578. axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  579. .then(res => {
  580. // Logs.out('syncMatchResult', res.data);
  581. })
  582. .catch(err => {
  583. Logs.out('syncMatchResult', err.message);
  584. });
  585. }
  586. /**
  587. * 更新比赛结果
  588. */
  589. const updateGamesResult = (result) => {
  590. syncGamesResult(result);
  591. return Promise.resolve();
  592. }
  593. /**
  594. * 同步中单方案
  595. */
  596. const syncSolutions = (solutions) => {
  597. if (IS_DEV) {
  598. return Logs.out('syncSolutions', solutions);
  599. }
  600. axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  601. .then(res => {
  602. // Logs.out('syncSolutions', res.data);
  603. })
  604. .catch(err => {
  605. Logs.out('syncSolutions', err.message);
  606. });
  607. }
  608. /**
  609. * 更新中单方案
  610. */
  611. const getCprKey = (cpr) => {
  612. const { k, p, v } = cpr;
  613. return `${k}_${p}_${v}`;
  614. }
  615. const compareCpr = (cpr1, cpr2) => {
  616. const key1 = getCprKey(cpr1);
  617. const key2 = getCprKey(cpr2);
  618. return key1 === key2;
  619. }
  620. const updateSolutions = (solutions, eventsLogsMap) => {
  621. if (solutions?.length) {
  622. const solutionsHistory = GAMES.Solutions;
  623. const updateIds = { add: [], update: [], retain: [], remove: [] }
  624. solutions.forEach(item => {
  625. const { sid, cpr, sol: { win_average } } = item;
  626. if (!solutionsHistory[sid]) {
  627. solutionsHistory[sid] = item;
  628. updateIds.add.push(sid);
  629. return;
  630. }
  631. const historySolution = solutionsHistory[sid];
  632. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  633. solutionsHistory[sid] = item;
  634. updateIds.update.push(sid);
  635. return;
  636. }
  637. const { timestamp } = item;
  638. historySolution.timestamp = timestamp;
  639. updateIds.retain.push(sid);
  640. });
  641. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  642. Object.keys(solutionsHistory).forEach(sid => {
  643. if (!solutionsMap.has(sid)) {
  644. delete solutionsHistory[sid];
  645. updateIds.remove.push(sid);
  646. }
  647. });
  648. const solutionUpdate = {};
  649. Object.keys(updateIds).forEach(key => {
  650. if (key == 'retain' || key == 'remove') {
  651. solutionUpdate[key] = updateIds[key];
  652. }
  653. else {
  654. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  655. }
  656. });
  657. syncSolutions(solutionUpdate);
  658. if (updateIds.add.length / solutions.length > 0.25 ||
  659. updateIds.remove.length / solutions.length > 0.25
  660. ) {
  661. const { expireEvents, removeEvents } = eventsLogsMap;
  662. const expireEvemtsMap = {};
  663. expireEvents.forEach(item => {
  664. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  665. if (!expireEvemtsMap[mk]) {
  666. expireEvemtsMap[mk] = {};
  667. }
  668. if (!expireEvemtsMap[mk][platform]) {
  669. expireEvemtsMap[mk][platform] = {};
  670. }
  671. if (!expireEvemtsMap[mk][platform].list) {
  672. expireEvemtsMap[mk][platform].list = [];
  673. }
  674. if (!expireEvemtsMap[mk][platform].evtime) {
  675. expireEvemtsMap[mk][platform].evtime = evtime;
  676. }
  677. if (!expireEvemtsMap[mk][platform].sptime) {
  678. expireEvemtsMap[mk][platform].sptime = sptime;
  679. }
  680. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  681. });
  682. Object.keys(expireEvemtsMap).forEach(mk => {
  683. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  684. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  685. mk, platform,
  686. expireEvemtsMap[mk][platform].list.length,
  687. expireEvemtsMap[mk][platform].evtime,
  688. expireEvemtsMap[mk][platform].sptime,
  689. )
  690. });
  691. });
  692. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  693. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  694. }
  695. else {
  696. Logs.outDev('solutions update complete');
  697. }
  698. }
  699. }
  700. /**
  701. * 获取中单方案
  702. */
  703. const getSolutions = async ({ win_min, no_events }) => {
  704. // Logs.out('getSolutions', win_min);
  705. const { minShowAmount } = getSetting();
  706. const solutionsList = Object.values(GAMES.Solutions);
  707. const gamesRelation = getGamesRelation();
  708. const relationsMap = new Map(gamesRelation.map(item => [item.id, item.rel]));
  709. const solutions = solutionsList.sort((a, b) => b.sol.win_average - a.sol.win_average)
  710. .filter(item => {
  711. const { sol: { win_average } } = item;
  712. return win_average >= (win_min ?? minShowAmount);
  713. })
  714. .map(item => {
  715. const { info: { id } } = item;
  716. const relation = relationsMap.get(id);
  717. return {
  718. ...item,
  719. info: { id, ...relation }
  720. }
  721. });
  722. const relIds = solutions.map(item => item.info.id);
  723. let gamesEvents = null;
  724. if (!no_events) {
  725. gamesEvents = getGamesEvents({ relIds });
  726. }
  727. return { solutions, gamesEvents };
  728. }
  729. /**
  730. * 获取单个中单方案
  731. */
  732. const getSolution = async (sid) => {
  733. if (!sid) {
  734. return Promise.reject(new Error('sid is required'));
  735. }
  736. const solution = GAMES.Solutions[sid];
  737. if (!solution) {
  738. return Promise.reject(new Error('solution not found'));
  739. }
  740. return solution;
  741. }
  742. /**
  743. * 清理中单方案
  744. */
  745. const solutionsCleanup = () => {
  746. const solutionsHistory = GAMES.Solutions;
  747. const updateIds = { remove: [] }
  748. Object.keys(solutionsHistory).forEach(sid => {
  749. const { timestamp } = solutionsHistory[sid];
  750. const nowTime = Date.now();
  751. if (nowTime - timestamp > 1000*60) {
  752. delete solutionsHistory[sid];
  753. updateIds.remove.push(sid);
  754. return;
  755. }
  756. const solution = solutionsHistory[sid];
  757. const eventTime = solution.info.timestamp;
  758. if (nowTime > eventTime) {
  759. delete solutionsHistory[sid];
  760. updateIds.remove.push(sid);
  761. }
  762. });
  763. if (updateIds.remove.length) {
  764. syncSolutions(updateIds);
  765. }
  766. }
  767. /**
  768. * 定时清理中单方案
  769. * 定时清理盘口信息
  770. */
  771. setInterval(() => {
  772. solutionsCleanup();
  773. gamesRelationCleanup();
  774. }, 1000*30);
  775. /**
  776. * 获取综合利润
  777. */
  778. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  779. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  780. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  781. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  782. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  783. return profit;
  784. }
  785. /**
  786. * 通过 sid 获取综合利润
  787. */
  788. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  789. const preSolution = GAMES.Solutions[sid1];
  790. const subSolution = GAMES.Solutions[sid2];
  791. const sol1 = preSolution?.sol;
  792. const sol2 = subSolution?.sol;
  793. if (!sol1) {
  794. return Promise.reject(new Error('sid1 已失效'));
  795. }
  796. if (!sol2) {
  797. return Promise.reject(new Error('sid2 已失效'));
  798. }
  799. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  800. return { profit, solutions: [preSolution, subSolution] };
  801. }
  802. /**
  803. * 通过盘口信息获取综合利润
  804. */
  805. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  806. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  807. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  808. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  809. if (fixed) {
  810. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  811. }
  812. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  813. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  814. }
  815. /**
  816. * 获取后台设置
  817. */
  818. // const getSetting = async () => {
  819. // return ;
  820. // }
  821. /**
  822. * 异常通知
  823. */
  824. const notifyException = (message) => {
  825. if (IS_DEV) {
  826. return Logs.out('notifyException', { message });
  827. }
  828. const chat_id = -1003032820471;
  829. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  830. .then(() => {
  831. Logs.out('notifyException', '通知成功');
  832. })
  833. .catch(err => {
  834. Logs.out('notifyException', err.message);
  835. });
  836. }
  837. /**
  838. * 从子进程获取数据
  839. */
  840. const getDataFromChild = (type, callback) => {
  841. const id = ++Request.count;
  842. Request.callbacks[id] = callback;
  843. events_child.send({ method: 'get', id, type });
  844. }
  845. /**
  846. * 向子进程发送数据
  847. */
  848. const postDataToChild = (type, data) => {
  849. events_child.send({ method: 'post', type, data });
  850. }
  851. /**
  852. * 处理子进程消息
  853. */
  854. events_child.on('message', async (message) => {
  855. const { callbacks } = Request;
  856. const { method, id, type, data } = message;
  857. if (method == 'get' && id) {
  858. let responseData = null;
  859. if (type == 'getGamesRelation') {
  860. responseData = getGamesRelation({ listEvents: true });
  861. }
  862. else if (type == 'getSetting') {
  863. responseData = getSetting();
  864. }
  865. // else if (type == 'getSolutionHistory') {
  866. // responseData = getSolutionHistory();
  867. // }
  868. events_child.send({ type: 'response', id, data: responseData });
  869. }
  870. else if (method == 'post') {
  871. if (type == 'updateSolutions') {
  872. updateSolutions(data.solutions, data.eventsLogsMap);
  873. }
  874. }
  875. else if (method == 'response' && id && callbacks[id]) {
  876. callbacks[id](data);
  877. delete callbacks[id];
  878. }
  879. });
  880. events_child.stderr?.on('data', data => {
  881. Logs.out('events_child stderr', data.toString());
  882. });
  883. const settingUpdate = (fields) => {
  884. updateSetting(fields);
  885. postDataToChild('updateSetting', fields);
  886. }
  887. const syncSetting = async () => {
  888. const setting = await Setting.get();
  889. settingUpdate(setting.toObject());
  890. }
  891. syncSetting();
  892. Setting.onUpdate(settingUpdate);
  893. /**
  894. * 保存GAMES数据到缓存文件
  895. */
  896. const saveGamesToCache = () => {
  897. Cache.setData(GamesCacheFile, GAMES, err => {
  898. if (err) {
  899. Logs.out('Failed to save games cache:', err.message);
  900. }
  901. else {
  902. Logs.out('Games cache saved successfully');
  903. }
  904. });
  905. }
  906. /**
  907. * 从缓存文件加载GAMES数据
  908. */
  909. const loadGamesFromCache = () => {
  910. const gamesCacheData = Cache.getData(GamesCacheFile, true);
  911. Object.assign(GAMES, gamesCacheData);
  912. Logs.out('Games cache loaded successfully');
  913. }
  914. // 在模块加载时尝试从缓存恢复数据
  915. loadGamesFromCache();
  916. // 监听进程退出事件,保存GAMES数据
  917. process.on('exit', saveGamesToCache);
  918. process.on('SIGINT', () => {
  919. process.exit(0);
  920. });
  921. process.on('SIGTERM', () => {
  922. process.exit(0);
  923. });
  924. process.on('SIGUSR2', () => {
  925. process.exit(0);
  926. });
  927. module.exports = {
  928. updateLeaguesList, getFilteredLeagues,
  929. updateGamesList, updateGamesEvents,
  930. getGamesRelation,
  931. updateGamesResult,
  932. getSolutions, getSolution,
  933. getTotalProfitWithSid,
  934. getTotalProfitWithBetInfo,
  935. notifyException,
  936. }