GamesPs.js 42 KB

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