GamesPs.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  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 } = 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 idsSet = null;
  659. if (ids?.length) {
  660. idsSet = new Set(ids);
  661. }
  662. let relations;
  663. if (ids?.length) {
  664. relations = ids.map(id => GAMES.Relations[id]);
  665. }
  666. else {
  667. relations = Object.values(GAMES.Relations);
  668. }
  669. relations = relations.filter(item => {
  670. if (idsSet && !idsSet.has(item.id)) {
  671. return false;
  672. }
  673. return mk == -1 || item.mk == mk;
  674. }).sort((a, b) => a.timestamp - b.timestamp);
  675. if (listEvents && !listPC) {
  676. return relations;
  677. }
  678. return relations.map(item => {
  679. const { rel, ...relationInfo } = item;
  680. const tempRel = { ...rel };
  681. const { id } = relationInfo;
  682. if (listPC) {
  683. tempRel.pc = getPCData(id);
  684. }
  685. if (!listEvents) {
  686. Object.keys(tempRel).forEach(platform => {
  687. const { events, evtime, special, sptime, ...gameInfo } = tempRel[platform];
  688. tempRel[platform] = gameInfo;
  689. });
  690. }
  691. return { ...relationInfo, rel: tempRel };
  692. });
  693. }
  694. /**
  695. * 定时更新关联比赛列表
  696. */
  697. const updateGamesRelation = () => {
  698. fetchGamesRelation()
  699. .then(gamesRelation => {
  700. const baseList = {};
  701. gamesRelation.map(item => {
  702. const baseGame = item.rel?.['ps'] ?? {};
  703. return { ...baseGame, mk: item.mk };
  704. }).forEach(item => {
  705. const marketType = getMarketType(item.mk);
  706. if (!baseList[marketType]) {
  707. baseList[marketType] = [];
  708. }
  709. baseList[marketType].push(item);
  710. });
  711. Object.keys(baseList).forEach(marketType => {
  712. syncBaseList({ marketType, games: baseList[marketType] });
  713. });
  714. const updateCount = {
  715. add: 0,
  716. update: 0,
  717. delete: 0
  718. };
  719. gamesRelation.forEach(item => {
  720. const { id, mk } = item;
  721. const oldItem = GAMES.Relations[id];
  722. if (!oldItem) {
  723. GAMES.Relations[id] = item;
  724. updateCount.add ++;
  725. }
  726. else if (oldItem.mk != mk) {
  727. GAMES.Relations[id] = item;
  728. updateCount.update ++;
  729. }
  730. });
  731. const relations = new Set(gamesRelation.map(item => +item.id));
  732. Object.keys(GAMES.Relations).forEach(id => {
  733. if (!relations.has(+id)) {
  734. delete GAMES.Relations[id];
  735. updateCount.delete ++;
  736. }
  737. });
  738. if (updateCount.add || updateCount.update || updateCount.delete) {
  739. Logs.out('updateGamesRelation', updateCount);
  740. }
  741. else {
  742. Logs.outDev('updateGamesRelation', updateCount);
  743. }
  744. })
  745. .catch(err => {
  746. Logs.out('updateGamesRelation', err.message);
  747. })
  748. .finally(() => {
  749. setTimeout(updateGamesRelation, 60000);
  750. });
  751. }
  752. updateGamesRelation();
  753. const gamesRelationCleanup = () => {
  754. const relations = Object.values(GAMES.Relations);
  755. const expireTime = Date.now() - 1000*60;
  756. relations.forEach(item => {
  757. const { rel } = item;
  758. Object.keys(rel).forEach(platform => {
  759. const { evtime, sptime } = rel[platform];
  760. if (evtime && evtime < expireTime) {
  761. delete rel[platform].events;
  762. delete rel[platform].evtime;
  763. }
  764. if (sptime && sptime < expireTime) {
  765. delete rel[platform].special;
  766. delete rel[platform].sptime;
  767. }
  768. });
  769. });
  770. }
  771. /**
  772. * 同步比赛结果
  773. */
  774. const syncGamesResult = async (result) => {
  775. if (IS_DEV) {
  776. return Logs.out('updateGamesResult', result);
  777. }
  778. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  779. // .then(res => {
  780. // // Logs.out('syncMatchResult', res.data);
  781. // })
  782. // .catch(err => {
  783. // Logs.out('syncMatchResult', err.message);
  784. // });
  785. }
  786. /**
  787. * 更新比赛结果
  788. */
  789. const updateGamesResult = (result) => {
  790. syncGamesResult(result);
  791. return Promise.resolve();
  792. }
  793. /**
  794. * 同步中单方案
  795. */
  796. // const syncSolutions = (solutions) => {
  797. // if (IS_DEV) {
  798. // return Logs.out('syncSolutions', solutions);
  799. // }
  800. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  801. // .then(res => {
  802. // // Logs.out('syncSolutions', res.data);
  803. // })
  804. // .catch(err => {
  805. // Logs.out('syncSolutions', err.message);
  806. // });
  807. // }
  808. /**
  809. * 更新中单方案
  810. */
  811. const getCprKey = (cpr) => {
  812. const { k, p, v, q } = cpr;
  813. return `${k}_${p}_${v}_${q}`;
  814. }
  815. const compareCpr = (cpr1, cpr2) => {
  816. const key1 = getCprKey(cpr1);
  817. const key2 = getCprKey(cpr2);
  818. return key1 === key2;
  819. }
  820. const updateSolutions = (solutions, eventsLogsMap) => {
  821. if (solutions?.length) {
  822. const solutionsHistory = GAMES.Solutions;
  823. const updateIds = { add: [], update: [], retain: [], remove: [] }
  824. solutions.forEach(item => {
  825. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  826. if (!solutionsHistory[sid]) {
  827. solutionsHistory[sid] = item;
  828. updateIds.add.push(sid);
  829. return;
  830. }
  831. const historySolution = solutionsHistory[sid];
  832. if (historySolution.sol.win_average !== win_average ||
  833. historySolution.sol.win_profit_rate !== win_profit_rate ||
  834. !compareCpr(historySolution.cpr, cpr)) {
  835. solutionsHistory[sid] = item;
  836. updateIds.update.push(sid);
  837. return;
  838. }
  839. const { timestamp } = item;
  840. historySolution.timestamp = timestamp;
  841. updateIds.retain.push(sid);
  842. });
  843. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  844. Object.keys(solutionsHistory).forEach(sid => {
  845. if (!solutionsMap.has(sid)) {
  846. delete solutionsHistory[sid];
  847. updateIds.remove.push(sid);
  848. }
  849. });
  850. // const solutionUpdate = {};
  851. // Object.keys(updateIds).forEach(key => {
  852. // if (key == 'retain' || key == 'remove') {
  853. // solutionUpdate[key] = updateIds[key];
  854. // }
  855. // else {
  856. // solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  857. // }
  858. // });
  859. // syncSolutions(solutionUpdate);
  860. if (updateIds.add.length / solutions.length > 0.2 ||
  861. updateIds.remove.length / solutions.length > 0.2
  862. ) {
  863. const { expireEvents, removeEvents } = eventsLogsMap;
  864. const expireEvemtsMap = {};
  865. expireEvents.forEach(item => {
  866. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  867. if (!expireEvemtsMap[mk]) {
  868. expireEvemtsMap[mk] = {};
  869. }
  870. if (!expireEvemtsMap[mk][platform]) {
  871. expireEvemtsMap[mk][platform] = {};
  872. }
  873. if (!expireEvemtsMap[mk][platform].list) {
  874. expireEvemtsMap[mk][platform].list = [];
  875. }
  876. if (!expireEvemtsMap[mk][platform].evtime) {
  877. expireEvemtsMap[mk][platform].evtime = evtime;
  878. }
  879. if (!expireEvemtsMap[mk][platform].sptime) {
  880. expireEvemtsMap[mk][platform].sptime = sptime;
  881. }
  882. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  883. });
  884. Object.keys(expireEvemtsMap).forEach(mk => {
  885. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  886. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  887. mk, platform,
  888. expireEvemtsMap[mk][platform].list.length,
  889. expireEvemtsMap[mk][platform].evtime,
  890. expireEvemtsMap[mk][platform].sptime,
  891. )
  892. });
  893. });
  894. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  895. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  896. }
  897. else {
  898. Logs.outDev('solutions update complete', updateIds);
  899. }
  900. }
  901. }
  902. /**
  903. * 获取中单方案
  904. */
  905. const getSolutions = async ({ win_min, with_events, show_lower=false, mk=-1 }) => {
  906. // Logs.out('getSolutions', win_min);
  907. const filterMarketType = +mk;
  908. const { minShowAmount } = getSetting();
  909. const solutionsList = Object.values(GAMES.Solutions);
  910. const gamesRelation = getGamesRelation();
  911. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  912. const mkCount = {
  913. all: 0,
  914. rollball: 0,
  915. today: 0,
  916. early: 0,
  917. }
  918. let solutions = solutionsList.filter(item => {
  919. const { sol: { win_average }, lower } = item;
  920. if (!show_lower && lower) {
  921. return false;
  922. }
  923. return win_average >= (win_min ?? minShowAmount);
  924. })
  925. .map(item => {
  926. const { info: { id } } = item;
  927. const { mk, rel } = relationsMap.get(id);
  928. const marketType = getMarketType(mk);
  929. mkCount.all ++;
  930. mkCount[marketType] ++;
  931. return {
  932. ...item,
  933. info: { id, mk, ...rel }
  934. }
  935. });
  936. if (mk >= 0) {
  937. solutions = solutions.filter(item => {
  938. const { info: { mk } } = item;
  939. return mk == filterMarketType;
  940. });
  941. }
  942. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  943. const relIds = solutions.map(item => item.info.id);
  944. let gamesEvents;
  945. if (with_events) {
  946. gamesEvents = getGamesEvents({ relIds });
  947. }
  948. return { solutions, gamesEvents, mkCount };
  949. }
  950. /**
  951. * 获取中单方案并按照比赛分组
  952. */
  953. const getGamesSolutions = async ({ win_min, with_events, show_lower=false, mk=-1, tp=0, sk }) => {
  954. const filterMarketType = +mk;
  955. const filterDataType = +tp;
  956. const { minShowAmount } = getSetting();
  957. const solutionsList = Object.values(GAMES.Solutions);
  958. const gamesRelation = getGamesRelation({ listEvents: with_events });
  959. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  960. const mkCount = {
  961. all: 0,
  962. rollball: 0,
  963. today: 0,
  964. early: 0,
  965. }
  966. const solutionsMap = {};
  967. solutionsList.forEach(item => {
  968. const { info: { id }, ...solution } = item;
  969. const { rule, sol: { win_average }, lower } = solution;
  970. const ruleType = getRuleType(rule);
  971. if (!show_lower && lower) {
  972. return false;
  973. }
  974. if ((filterDataType == 0 || filterDataType == ruleType) && (!!sk || win_average >= (win_min ?? minShowAmount))) {
  975. const gameRelation = relationsMap.get(id);
  976. if (!solutionsMap[id]) {
  977. solutionsMap[id] = { ...gameRelation, solutions: [] };
  978. }
  979. solutionsMap[id].solutions.push(solution);
  980. }
  981. })
  982. const gamesSolutions = Object.values(solutionsMap)
  983. .filter(item => {
  984. const { mk, rel, solutions } = item;
  985. const marketType = getMarketType(mk);
  986. if (!sk || matchGame(rel, sk)) {
  987. mkCount.all ++;
  988. mkCount[marketType] ++;
  989. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  990. return filterMarketType == -1 || filterMarketType == mk;
  991. }
  992. return false;
  993. })
  994. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  995. return { gamesSolutions, mkCount };
  996. }
  997. /**
  998. * 获取单个中单方案
  999. */
  1000. const getSolution = async (sid) => {
  1001. if (!sid) {
  1002. return Promise.reject(new Error('sid is required'));
  1003. }
  1004. const solution = GAMES.Solutions[sid];
  1005. if (!solution) {
  1006. return Promise.reject(new Error('solution not found'));
  1007. }
  1008. return solution;
  1009. }
  1010. /**
  1011. * 通过比赛 ID 获取中单方案
  1012. */
  1013. const getSolutionsByIds = async (ids) => {
  1014. const baseList = Object.values(GAMES.Baselist).flat();
  1015. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  1016. const result = {};
  1017. ids.forEach(id => {
  1018. const baseGame = baseMap.get(id);
  1019. result[id] = {};
  1020. result[id].matches = baseGame?.matches ?? [];
  1021. result[id].sols = [];
  1022. });
  1023. Object.values(GAMES.Solutions).forEach(item => {
  1024. const { info: { id }, lower } = item;
  1025. if (result[id] && !lower) {
  1026. result[id].sols.push(item);
  1027. }
  1028. });
  1029. return result;
  1030. }
  1031. /**
  1032. * 清理中单方案
  1033. */
  1034. const solutionsCleanup = () => {
  1035. const solutionsHistory = GAMES.Solutions;
  1036. const updateIds = { remove: [] }
  1037. Object.keys(solutionsHistory).forEach(sid => {
  1038. const { timestamp } = solutionsHistory[sid];
  1039. const nowTime = Date.now();
  1040. if (nowTime - timestamp > 1000*60) {
  1041. delete solutionsHistory[sid];
  1042. updateIds.remove.push(sid);
  1043. return;
  1044. }
  1045. const solution = solutionsHistory[sid];
  1046. const eventTime = solution.info.timestamp;
  1047. if (nowTime > eventTime) {
  1048. delete solutionsHistory[sid];
  1049. updateIds.remove.push(sid);
  1050. }
  1051. });
  1052. // if (updateIds.remove.length) {
  1053. // syncSolutions(updateIds);
  1054. // }
  1055. }
  1056. /**
  1057. * 清理更新时间戳
  1058. */
  1059. const cleanupUpdateTimestamp = () => {
  1060. const updateTimestamp = GAMES.UpdateTimestamp;
  1061. const nowTime = Date.now();
  1062. const expireTime = nowTime - 1000*60;
  1063. Object.keys(updateTimestamp).forEach(key => {
  1064. if (updateTimestamp[key] < expireTime) {
  1065. delete updateTimestamp[key];
  1066. }
  1067. });
  1068. }
  1069. /**
  1070. * 定时清理中单方案
  1071. * 定时清理盘口信息
  1072. */
  1073. setInterval(() => {
  1074. // cleanupBaseList();
  1075. solutionsCleanup();
  1076. gamesRelationCleanup();
  1077. cleanupUpdateTimestamp();
  1078. }, 1000*30);
  1079. /**
  1080. * 获取综合利润
  1081. */
  1082. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  1083. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1084. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1085. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1086. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1087. return profit;
  1088. }
  1089. /**
  1090. * 通过 sid 获取综合利润
  1091. */
  1092. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  1093. const preSolution = GAMES.Solutions[sid1];
  1094. const subSolution = GAMES.Solutions[sid2];
  1095. const sol1 = preSolution?.sol;
  1096. const sol2 = subSolution?.sol;
  1097. if (!sol1) {
  1098. return Promise.reject(new Error('sid1 已失效'));
  1099. }
  1100. if (!sol2) {
  1101. return Promise.reject(new Error('sid2 已失效'));
  1102. }
  1103. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1104. return { profit, solutions: [preSolution, subSolution] };
  1105. }
  1106. /**
  1107. * 通过盘口信息获取综合利润
  1108. */
  1109. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  1110. if (!betInfo1?.cross_type) {
  1111. return Promise.reject(new Error('第一个下注信息无效'));
  1112. }
  1113. if (!betInfo2?.cross_type) {
  1114. return Promise.reject(new Error('第二个下注信息无效'));
  1115. }
  1116. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1117. inner_base = typeof(inner_base) != 'undefined' ? +inner_base : innerDefaultAmount;
  1118. inner_rebate = typeof(inner_rebate) != 'undefined' ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1119. if (fixed) {
  1120. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  1121. }
  1122. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  1123. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1124. }
  1125. /**
  1126. * 计算补单综合利润
  1127. */
  1128. const getTotalReplacement = async (event_id, inner_base, inner_rebate, inner_ior, inner_odds, outer_golds) => {
  1129. // return Promise.resolve();
  1130. if (!event_id) {
  1131. return Promise.reject(new Error('event_id 无效'));
  1132. }
  1133. if (!inner_ior) {
  1134. return Promise.reject(new Error('inner_ior 无效'));
  1135. }
  1136. if (inner_odds?.length != 2) {
  1137. return Promise.reject(new Error('inner_odds 无效'));
  1138. }
  1139. if (!outer_golds?.length) {
  1140. return Promise.reject(new Error('outer_golds 无效'));
  1141. }
  1142. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1143. inner_base = typeof(inner_base) != 'undefined' ? +inner_base : innerDefaultAmount;
  1144. inner_rebate = typeof(inner_rebate) != 'undefined' ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1145. const inner_odds_value = fixFloat(inner_odds[0] * inner_odds[1], 3);
  1146. const outer_golds_rebate = outer_golds.map(item => (item.gold ?? 0) * (item.rebate ?? 0)).reduce((sum, rebate) => sum + rebate, 0);
  1147. const outer_golds_loss = outer_golds.map(item => item.gold ?? 0).reduce((sum, gold) => sum + gold, 0) - outer_golds_rebate;
  1148. const relation = getGamesRelation({ ids: [event_id], listEvents: true, listPC: true }).map(item => {
  1149. const { rel, ...relationInfo } = item;
  1150. const tempRel = { ...rel };
  1151. const events = {};
  1152. events[inner_ior] = { v: inner_odds_value };
  1153. tempRel.ps = { ...rel.ps, events }
  1154. return { ...relationInfo, rel: tempRel };
  1155. });
  1156. const passableEvents = getPassableEvents(relation, null);
  1157. const solutions = eventsCombination(passableEvents, inner_base, inner_rebate);
  1158. if (!solutions?.length) {
  1159. return Promise.reject(new Error('没有可用的解决方案'));
  1160. }
  1161. return solutions.filter(solution => !solution.lower).map(solution => {
  1162. const { sid, info, sol, ...solutionInfo } = solution;
  1163. const { win_profit_rate, win_average_rate, ...solInfo } = sol;
  1164. const { cross_type } = solInfo;
  1165. solInfo.win_side_a = typeof(solInfo.win_side_a) !== 'number' ? undefined : fixFloat(solInfo.win_side_a - outer_golds_loss);
  1166. solInfo.win_side_b = typeof(solInfo.win_side_b) !== 'number' ? undefined : fixFloat(solInfo.win_side_b - outer_golds_loss);
  1167. solInfo.win_side_c = cross_type == 'la_wa_rv' ? 0 : (typeof(solInfo.win_side_c) !== 'number' ? undefined : fixFloat(solInfo.win_side_c - outer_golds_loss));
  1168. solInfo.win_average = fixFloat(solInfo.win_average - outer_golds_loss);
  1169. return { ...solutionInfo, sol: solInfo };
  1170. });
  1171. }
  1172. /**
  1173. * 同步Qboss平台配置
  1174. */
  1175. const syncQbossConfig = () => {
  1176. const setting = getSetting();
  1177. if (!setting.syncSettingEnabled) {
  1178. // Logs.outDev('syncQbossConfig disabled');
  1179. return setTimeout(syncQbossConfig, 1000*5);
  1180. }
  1181. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  1182. .then(res => {
  1183. const { data } = res;
  1184. if (!data?.data) {
  1185. throw new Error('syncQbossConfig data is empty');
  1186. }
  1187. const {
  1188. qboss_return_ratio,
  1189. ob_return_ratio, ob_return_type, ob_odds_more_than,
  1190. hg_return_ratio, hg_return_type, hg_odds_more_than,
  1191. pc_return_ratio, pc_return_type,
  1192. qboss_jq_add_odds, qboss_jq_add_hours,
  1193. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1194. } = data.data;
  1195. const qbossSetting = {
  1196. innerRebateRatio: +qboss_return_ratio,
  1197. obRebateRatio: +ob_return_ratio,
  1198. obRebateType: +ob_return_type,
  1199. obMaxDiff: +ob_odds_more_than,
  1200. hgRebateRatio: +hg_return_ratio,
  1201. hgRebateType: +hg_return_type,
  1202. hgMaxDiff: +hg_odds_more_than,
  1203. pcRebateRatio: +pc_return_ratio,
  1204. pcRebateType: +pc_return_type,
  1205. subsidyTime: +qboss_jq_add_hours,
  1206. subsidyAmount: +qboss_jq_add_odds,
  1207. subsidyRbWmAmount: +qboss_gq_add_dy_odds,
  1208. subsidyRbOtAmount: +qboss_gq_add_jq_odds,
  1209. };
  1210. const settingFields = {};
  1211. let needUpdate = false;
  1212. Object.keys(qbossSetting).forEach(key => {
  1213. if (qbossSetting[key] !== setting[key]) {
  1214. settingFields[key] = qbossSetting[key];
  1215. needUpdate = true;
  1216. }
  1217. });
  1218. if (needUpdate) {
  1219. Setting.update(settingFields);
  1220. // Logs.outDev('syncQbossConfig', settingFields);
  1221. }
  1222. // else {
  1223. // Logs.outDev('syncQbossConfig no change');
  1224. // }
  1225. })
  1226. .catch(err => {
  1227. Logs.out('syncQbossConfig error', err.message);
  1228. })
  1229. .finally(() => {
  1230. setTimeout(syncQbossConfig, 1000*15);
  1231. });
  1232. }
  1233. syncQbossConfig();
  1234. /**
  1235. * 异常通知
  1236. */
  1237. const notifyException = (message) => {
  1238. if (IS_DEV) {
  1239. return Logs.out('notifyException', { message });
  1240. }
  1241. const chat_id = -1003032820471;
  1242. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  1243. .then(() => {
  1244. Logs.out('notifyException', '通知成功');
  1245. })
  1246. .catch(err => {
  1247. Logs.out('notifyException', err.message);
  1248. });
  1249. }
  1250. /**
  1251. * 从子进程获取数据
  1252. */
  1253. const getDataFromChild = (type, callback) => {
  1254. const id = ++Request.count;
  1255. Request.callbacks[id] = callback;
  1256. events_child.send({ method: 'get', id, type });
  1257. }
  1258. /**
  1259. * 向子进程发送数据
  1260. */
  1261. const postDataToChild = (type, data) => {
  1262. events_child.send({ method: 'post', type, data });
  1263. }
  1264. /**
  1265. * 处理子进程消息
  1266. */
  1267. events_child.on('message', async (message) => {
  1268. const { callbacks } = Request;
  1269. const { method, id, type, data } = message;
  1270. if (method == 'get' && id) {
  1271. let responseData = null;
  1272. if (type == 'getGamesRelation') {
  1273. responseData = getGamesRelation({ listEvents: true });
  1274. }
  1275. else if (type == 'getSetting') {
  1276. responseData = getSetting();
  1277. }
  1278. // else if (type == 'getSolutionHistory') {
  1279. // responseData = getSolutionHistory();
  1280. // }
  1281. events_child.send({ type: 'response', id, data: responseData });
  1282. }
  1283. else if (method == 'post') {
  1284. if (type == 'updateSolutions') {
  1285. updateSolutions(data.solutions, data.eventsLogsMap);
  1286. }
  1287. }
  1288. else if (method == 'response' && id && callbacks[id]) {
  1289. callbacks[id](data);
  1290. delete callbacks[id];
  1291. }
  1292. });
  1293. events_child.stderr?.on('data', data => {
  1294. Logs.out('events_child stderr', data.toString());
  1295. });
  1296. const settingUpdate = (fields) => {
  1297. updateSetting(fields);
  1298. postDataToChild('updateSetting', fields);
  1299. }
  1300. const syncSetting = async () => {
  1301. const setting = await Setting.get();
  1302. settingUpdate(setting.toObject());
  1303. }
  1304. syncSetting();
  1305. Setting.onUpdate(settingUpdate);
  1306. /**
  1307. * 保存GAMES数据到缓存文件
  1308. */
  1309. const saveGamesToCache = () => {
  1310. Cache.setData(GamesCacheFile, GAMES, err => {
  1311. if (err) {
  1312. Logs.out('Failed to save games cache:', err.message);
  1313. }
  1314. else {
  1315. Logs.out('Games cache saved successfully');
  1316. }
  1317. });
  1318. }
  1319. /**
  1320. * 从缓存文件加载GAMES数据
  1321. */
  1322. const loadGamesFromCache = () => {
  1323. const gamesCacheData = Cache.getData(GamesCacheFile, true) ?? {};
  1324. Object.keys(GAMES).forEach(key => {
  1325. if (key in gamesCacheData) {
  1326. GAMES[key] = gamesCacheData[key];
  1327. }
  1328. });
  1329. Logs.out('Games cache loaded successfully');
  1330. }
  1331. // 在模块加载时尝试从缓存恢复数据
  1332. loadGamesFromCache();
  1333. // 监听进程退出事件,保存GAMES数据
  1334. process.on('exit', saveGamesToCache);
  1335. process.on('SIGINT', () => {
  1336. process.exit(0);
  1337. });
  1338. process.on('SIGTERM', () => {
  1339. process.exit(0);
  1340. });
  1341. process.on('SIGUSR2', () => {
  1342. process.exit(0);
  1343. });
  1344. module.exports = {
  1345. updateLeaguesList, getFilteredLeagues,
  1346. updateGamesList, updateGamesEvents, updateBaseEvents,
  1347. getGamesRelation,
  1348. updateGamesResult,
  1349. updateOriginalData, getOriginalData,
  1350. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1351. getTotalProfitWithSid, getTotalProfitWithBetInfo, getTotalReplacement,
  1352. notifyException,
  1353. }