GamesPs.js 33 KB

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