GamesPs.js 35 KB

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