GamesPs.js 41 KB

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