GamesPs.js 34 KB

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