| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359 |
- const axios = require('axios');
- const Logs = require('../libs/logs');
- const Cache = require('../libs/cache');
- const Setting = require('./Setting');
- const { eventSolutions } = require('../triangle/eventSolutions');
- const { calcTotalProfit, calcTotalProfitWithFixedFirst } = require('../triangle/totalProfitCalc');
- const { getSetting, updateSetting } = require('../triangle/settings');
- const fs = require('fs');
- const path = require('path');
- const GamesCacheFile = path.join(__dirname, '../data/games.cache');
- const DevGameTastFile = path.join(__dirname, '../data/gameTast.json');
- const childOptions = process.env.NODE_ENV == 'development' ? {
- execArgv: ['--inspect=9230'],
- stdio: ['pipe', 'pipe', 'pipe', 'ipc']
- } : {};
- const { fork } = require('child_process');
- const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
- const PS_IOR_KEYS = [
- ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
- ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
- ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
- ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
- ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
- ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
- ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
- ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
- ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
- ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
- ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
- ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
- ];
- const IOR_KEYS_TYPE = {
- A: 1, L: 1,
- D: 2, K: 2,
- }
- // 测试环境
- // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
- const IS_DEV = process.env.NODE_ENV == 'development';
- const BASE_API_URL = IS_DEV ? 'https://api.qboss.vip/api' : 'http://172.17.222.37/api';
- const GAMES = {
- Leagues: {},
- Baselist: {},
- Relations: {},
- Solutions: {},
- ObOriginalData: {},
- UpdateTimestamp: {},
- };
- const Request = {
- callbacks: {},
- count: 0,
- }
- /**
- * 精确浮点数字
- * @param {number} number
- * @param {number} x
- * @returns {number}
- */
- const fixFloat = (number, x=2) => {
- return parseFloat(number.toFixed(x));
- }
- /**
- * 获取市场类型
- */
- const getMarketType = (mk) => {
- if (mk == 0) {
- return 'early';
- }
- else if (mk == 2) {
- return 'rollball';
- }
- return 'today';
- }
- /**
- * 获取策略类型
- */
- const getRuleType = (rule) => {
- const rulePrefix = rule.split(':')[0];
- return IOR_KEYS_TYPE[rulePrefix];
- }
- /**
- * 关键词匹配比赛
- */
- const matchGame = (relation, sk) => {
- const keys = [];
- Object.keys(relation).forEach(platform => {
- const { leagueName, teamHomeName, teamAwayName } = relation[platform];
- if (platform == 'ps') {
- keys.push(leagueName);
- }
- keys.push(teamHomeName, teamAwayName);
- });
- return keys.some(key => key.includes(sk));
- }
- /**
- * 同步联赛列表
- */
- const syncLeaguesList = ({ mk, leagues }) => {
- if (IS_DEV) {
- return Logs.out('syncLeaguesList', { mk, leagues });
- }
- axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
- .then(res => {
- // Logs.out('syncLeaguesList', res.data);
- })
- .catch(err => {
- Logs.out('syncLeaguesList', err.message);
- });
- }
- /**
- * 更新联赛列表
- */
- const updateLeaguesList = ({ mk, leagues, platform='ps' }) => {
- const { Leagues } = GAMES;
- if (!Leagues[platform]) {
- Leagues[platform] = {};
- }
- const leaguesMap = Leagues[platform];
- const nowTime = Date.now();
- const expireTime = nowTime - 1000 * 60 * 5;
- if (!leaguesMap[mk]) {
- leaguesMap[mk] = {
- timestamp: 0,
- leagues: [],
- };
- }
- if (leaguesMap[mk].timestamp < expireTime ||
- JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
- leaguesMap[mk].leagues = leagues;
- leaguesMap[mk].timestamp = nowTime;
- if (platform == 'ps') {
- syncLeaguesList({ mk, leagues });
- }
- return leagues.length;
- }
- return 0;
- }
- /**
- * 获取筛选过的联赛
- */
- const getFilteredLeagues = async (mk) => {
- return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
- .then(res => {
- if (res.data.code == 0) {
- return res.data.data;
- }
- return Promise.reject(new Error(res.data.message));
- });
- }
- /**
- * 更新OB原始数据
- */
- const updateOriginalData = ({ leagues, matches }) => {
- const { ObOriginalData } = GAMES;
- ObOriginalData.leagues = leagues;
- ObOriginalData.matches = matches;
- ObOriginalData.timestamp = Date.now();
- }
- /**
- * 获取OB原始数据
- */
- const getOriginalData = () => {
- const { ObOriginalData } = GAMES;
- return ObOriginalData;
- }
- /**
- * 同步比赛列表到服务器
- */
- const syncGamesList = ({ platform, mk, games }) => {
- if (IS_DEV) {
- return Logs.out('syncGamesList', { platform, mk, games });
- }
- axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
- .then(res => {
- // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
- })
- .catch(err => {
- Logs.out('syncGamesList', { platform, mk }, err.message);
- });
- }
- /**
- * 同步基准比赛列表
- */
- const syncBaseList = ({ marketType, games }) => {
- const baseList = GAMES.Baselist;
- // 直接创建新列表
- if (!baseList[marketType]) {
- baseList[marketType] = games;
- return;
- }
- const newMap = new Map(games.map(item => [item.eventId, item]));
- // 删除不存在的项
- for (let i = baseList[marketType].length - 1; i >= 0; i--) {
- if (!newMap.has(baseList[marketType][i].eventId)) {
- baseList[marketType].splice(i, 1);
- }
- }
- // 添加或更新
- const oldIds = new Set(baseList[marketType].map(item => item.eventId));
- games.forEach(game => {
- if (!oldIds.has(game.eventId)) {
- // 添加新项
- baseList[marketType].push(game);
- }
- });
- }
- /**
- * 清理基准比赛列表
- */
- // const cleanupBaseList = () => {
- // const baseList = GAMES.Baselist;
- // const nowTime = Date.now();
- // const expireTime = nowTime - 1000*60*60*3;
- // Object.keys(baseList).forEach(marketType => {
- // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
- // });
- // }
- /**
- * 更新比赛列表
- */
- const updateGamesList = (({ platform, mk, games } = {}) => {
- return new Promise((resolve, reject) => {
- if (!platform || !games) {
- return reject(new Error('PLATFORM_GAMES_INVALID'));
- }
- syncGamesList({ platform, mk, games });
- resolve();
- });
- });
- /**
- * 提交盘口数据
- */
- // const submitOdds = ({ platform, mk, games }) => {
- // if (IS_DEV) {
- // return Logs.out('syncOdds', { platform, mk, games });
- // }
- // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
- // .then(res => {
- // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
- // })
- // .catch(err => {
- // Logs.out('syncOdds', { platform, mk }, err.message);
- // });
- // }
- /**
- * 同步基准盘口
- */
- const syncBaseEvents = ({ mk, games, outrights }) => {
- Logs.out('syncBaseEvents', { mk, games });
- const {
- expireTimeEvents, expireTimeSpecial,
- subsidyTime, subsidyAmount,
- subsidyRbWmAmount, subsidyRbOtAmount
- } = getSetting();
- const nowTime = Date.now();
- const marketType = getMarketType(mk);
- const baseList = GAMES.Baselist;
- if (!baseList[marketType]) {
- return 0;
- }
- const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
- games?.forEach(game => {
- const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
- const baseGame = baseMap.get(eventId);
- if (baseGame) {
- const { mk, timestamp } = baseGame;
- const isRb = (mk == 2);
- const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
- Object.keys(events).forEach(ior => {
- if (isRb && (ior.startsWith('ior_r') || ior.startsWith('ior_m') || ior.startsWith('ior_wm')) && subsidyRbWmAmount) {
- // 滚球胜平负
- const sourceOdds = events[ior].v;
- events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
- events[ior].s = sourceOdds
- }
- else if (isRb && ior.startsWith('ior_ot') && subsidyRbOtAmount) {
- // 滚球进球数
- const sourceOdds = events[ior].v;
- events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
- events[ior].s = sourceOdds
- }
- else if (!isRb && isSubsidy && ior.startsWith('ior_ot') && subsidyAmount) {
- // 赛前进球数
- const sourceOdds = events[ior].v;
- events[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
- events[ior].s = sourceOdds
- }
- });
- baseGame.originId = originId;
- baseGame.stage = stage;
- baseGame.retime = retime;
- baseGame.score = score;
- baseGame.wm = wm;
- baseGame.evtime = evtime;
- baseGame.events = events;
- }
- });
- outrights?.forEach(outright => {
- const { parentId, sptime, special } = outright;
- const baseGame = baseMap.get(parentId);
- if (baseGame) { // 赛前特殊盘口
- const { timestamp } = baseGame;
- const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
- if (isSubsidy) {
- Object.keys(special).forEach(ior => {
- if (ior.startsWith('ior_ot') && subsidyAmount) {
- const sourceOdds = special[ior].v;
- special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
- special[ior].s = sourceOdds
- }
- });
- }
- baseGame.sptime = sptime;
- baseGame.special = special;
- }
- else {
- const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
- const originBaseGame = originBaseMap.get(parentId);
- if (originBaseGame) { // 滚球特殊盘口
- Object.keys(special).forEach(ior => {
- if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
- const sourceOdds = special[ior].v;
- special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
- special[ior].s = sourceOdds
- }
- else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
- const sourceOdds = special[ior].v;
- special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
- special[ior].s = sourceOdds
- }
- });
- originBaseGame.sptime = sptime;
- originBaseGame.special = special;
- }
- }
- });
- if (games?.length) {
- const gamesList = baseList[marketType]?.map(game => {
- const { evtime, events, sptime, special, ...gameInfo } = game;
- const expireTimeEv = nowTime - expireTimeEvents;
- const expireTimeSP = nowTime - expireTimeSpecial;
- let odds = {};
- if (evtime > expireTimeEv) {
- odds = { ...odds, ...events };
- }
- if (sptime > expireTimeSP) {
- odds = { ...odds, ...special };
- }
- const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
- let match = keys.map(key => {
- return {
- key,
- value: odds[key]?.v ?? 0,
- origin: odds[key]?.r,
- source: odds[key]?.s,
- }
- });
- if (label == 'jqs') {
- match = match.filter(item => item.value !== 0);
- }
- return {
- label,
- match
- };
- }).filter(item => {
- if (item.label == 'jqs') {
- return item.match.length;
- }
- else {
- return item.match.every(entry => entry.value !== 0);
- }
- });
- game.matches = matches; // matches 也记录下来
- let uptime = evtime ?? 0;
- return { ...gameInfo, matches, uptime };
- });
- // if (gamesList.filter(item => item.uptime > 0).length) {
- // // if (mk == 2) {
- // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
- // // }
- // submitOdds({ platform: 'ps', mk, games: gamesList });
- // }
- const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
- if (!relatedGames.length) {
- return 0;
- }
- let update = 0;
- const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
- gamesList?.forEach(game => {
- const { eventId, matches, uptime, stage, retime, score, wm } = game;
- const relatedGame = relatedMap.get(eventId);
- if (relatedGame) {
- const events = {};
- matches.forEach(({ label, match }) => {
- match.forEach(({ key, value, origin, source }) => {
- events[key] = {
- v: value,
- r: origin,
- s: source
- };
- });
- });
- relatedGame.evtime = uptime;
- relatedGame.events = events;
- relatedGame.stage = stage;
- relatedGame.retime = retime;
- relatedGame.score = score;
- relatedGame.wm = wm;
- update ++;
- }
- });
- return update;
- }
- }
- const updateBaseEvents = ({ games, timestamp }) => {
- return new Promise((resolve, reject) => {
- if (!games) {
- return reject(new Error('GAMES_INVALID'));
- }
- if (!timestamp) {
- return reject(new Error('TIMESTAMP_INVALID'));
- }
- let update = 0;
- const { UpdateTimestamp } = GAMES;
- const tp = 'ps_9_9';
- if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
- UpdateTimestamp[tp] = timestamp;
- }
- else {
- return resolve({ update });
- }
- Object.keys(games).forEach(mk => {
- update += syncBaseEvents({ mk, games: games[mk] ?? [] });
- });
- resolve({ update });
- });
- }
- const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
- return new Promise((resolve, reject) => {
- if (!platform || (!games && !outrights)) {
- return reject(new Error('PLATFORM_GAMES_INVALID'));
- }
- const { UpdateTimestamp } = GAMES;
- if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
- // Logs.out('updateGamesEvents', { tp, timestamp });
- UpdateTimestamp[tp] = timestamp;
- }
- else {
- return resolve({ update: 0 });
- }
- if (platform == 'ps') {
- const update = syncBaseEvents({ mk, games, outrights });
- return resolve({ update });
- }
- const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
- if (!relatedGames.length) {
- return resolve({ update: 0 });
- }
- const updateCount = {
- update: 0
- };
- const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
- games?.forEach(game => {
- const { eventId, evtime, events, stage, retime, score, wm } = game;
- const relatedGame = relatedMap.get(eventId);
- if (relatedGame) {
- relatedGame.evtime = evtime;
- relatedGame.events = events;
- relatedGame.stage = stage;
- relatedGame.retime = retime;
- relatedGame.score = score;
- relatedGame.wm = wm;
- updateCount.update ++;
- }
- });
- outrights?.forEach(outright => {
- const { parentId, sptime, special } = outright;
- const relatedGame = relatedMap.get(parentId);
- if (relatedGame) {
- relatedGame.sptime = sptime;
- relatedGame.special = special;
- updateCount.update ++;
- }
- });
- resolve(updateCount);
- });
- }
- /**
- * 获取比赛盘口
- */
- const getGamesEvents = ({ platform, relIds = [] } = {}) => {
- if (!relIds.length) {
- return null;
- }
- const idSet = new Set(relIds);
- const relations = { ...GAMES.Relations };
- Object.keys(relations).forEach(id => {
- if (idSet.size && !idSet.has(+id)) {
- delete relations[id];
- }
- });
- if (platform) {
- return Object.values(relations).map(rel => rel[platform] ?? {});
- }
- const gamesEvents = {};
- Object.values(relations).forEach(({ rel }) => {
- Object.keys(rel).forEach(platform => {
- const game = rel[platform] ?? {};
- const { eventId, events, special } = game;
- if (!gamesEvents[platform]) {
- gamesEvents[platform] = {};
- }
- gamesEvents[platform][eventId] = { ...events, ...special };
- });
- });
- return gamesEvents;
- }
- /**
- * 获取关联比赛
- */
- const getDevGameTast = () => {
- return new Promise((resolve) => {
- const data = Cache.getData(DevGameTastFile, true);
- resolve({data});
- });
- }
- const fetchGamesRelation = async (mk='') => {
- const getGameTast = Promise.all([
- getDevGameTast(),
- axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, { proxy: false })
- ]);
- return getGameTast.then(([res1, res2]) => {
- const resData = res1.data ?? res2.data;
- if (resData.code == 0) {
- const nowTime = Date.now();
- const gamesRelation = resData.data?.filter(item => {
- const timestamp = new Date(item.timestamp).getTime();
- if (nowTime > timestamp) {
- item.mk = 2;
- }
- item.timestamp = timestamp;
- const expireTime = timestamp + 1000*60*60*3;
- return expireTime > nowTime;
- }).map(item => {
- const {
- id, mk, league_name,
- event_id: ps_event_id,
- league_id: ps_league_id,
- team_home_name: ps_team_home_name,
- team_away_name: ps_team_away_name,
- ob_event_id, ob_league_id,
- ob_team_home_name,
- ob_team_away_name,
- hg_event_id, hg_league_id,
- hg_team_home_name,
- hg_team_away_name,
- timestamp,
- } = item;
- const rel = {
- ps: {
- eventId: +ps_event_id,
- leagueId: +ps_league_id,
- leagueName: league_name,
- teamHomeName: ps_team_home_name,
- teamAwayName: ps_team_away_name,
- timestamp
- },
- ob: ob_event_id ? {
- eventId: +ob_event_id,
- leagueId: +ob_league_id,
- leagueName: league_name,
- teamHomeName: ob_team_home_name,
- teamAwayName: ob_team_away_name,
- timestamp
- } : null,
- hg: hg_event_id ? {
- eventId: +hg_event_id,
- leagueId: +hg_league_id,
- leagueName: league_name,
- teamHomeName: hg_team_home_name,
- teamAwayName: hg_team_away_name,
- timestamp
- } : null
- };
- return { id: ps_event_id, mk, rel, timestamp };
- }) ?? [];
- return gamesRelation;
- }
- return Promise.reject(new Error(resData.message));
- });
- }
- const getGamesRelation = ({ mk=-1, ids, listEvents } = {}) => {
- let idsSet = null;
- if (ids?.length) {
- idsSet = new Set(ids);
- }
- const relations = Object.values(GAMES.Relations).filter(item => {
- if (idsSet && !idsSet.has(item.id)) {
- return false;
- }
- return mk == -1 || item.mk == mk;
- }).sort((a, b) => a.timestamp - b.timestamp);
- if (listEvents) {
- return relations;
- }
- const gamesRelation = relations.map(item => {
- const { rel, ...relationInfo } = item;
- const tempRel = { ...rel };
- Object.keys(tempRel).forEach(platform => {
- const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
- tempRel[platform] = gameInfo;
- });
- return { ...relationInfo, rel: tempRel };
- });
- return gamesRelation;
- }
- /**
- * 定时更新关联比赛列表
- */
- const updateGamesRelation = () => {
- fetchGamesRelation()
- .then(gamesRelation => {
- const baseList = {};
- gamesRelation.map(item => {
- const baseGame = item.rel?.['ps'] ?? {};
- return { ...baseGame, mk: item.mk };
- }).forEach(item => {
- const marketType = getMarketType(item.mk);
- if (!baseList[marketType]) {
- baseList[marketType] = [];
- }
- baseList[marketType].push(item);
- });
- Object.keys(baseList).forEach(marketType => {
- syncBaseList({ marketType, games: baseList[marketType] });
- });
- const updateCount = {
- add: 0,
- update: 0,
- delete: 0
- };
- gamesRelation.forEach(item => {
- const { id, mk } = item;
- const oldItem = GAMES.Relations[id];
- if (!oldItem) {
- GAMES.Relations[id] = item;
- updateCount.add ++;
- }
- else if (oldItem.mk != mk) {
- GAMES.Relations[id] = item;
- updateCount.update ++;
- }
- });
- const relations = new Set(gamesRelation.map(item => +item.id));
- Object.keys(GAMES.Relations).forEach(id => {
- if (!relations.has(+id)) {
- delete GAMES.Relations[id];
- updateCount.delete ++;
- }
- });
- if (updateCount.add || updateCount.update || updateCount.delete) {
- Logs.out('updateGamesRelation', updateCount);
- }
- else {
- Logs.outDev('updateGamesRelation', updateCount);
- }
- })
- .catch(err => {
- Logs.out('updateGamesRelation', err.message);
- })
- .finally(() => {
- setTimeout(updateGamesRelation, 60000);
- });
- }
- updateGamesRelation();
- const gamesRelationCleanup = () => {
- const relations = Object.values(GAMES.Relations);
- const expireTime = Date.now() - 1000*60;
- relations.forEach(item => {
- const { rel } = item;
- Object.keys(rel).forEach(platform => {
- const { evtime, sptime } = rel[platform];
- if (evtime && evtime < expireTime) {
- delete rel[platform].events;
- delete rel[platform].evtime;
- }
- if (sptime && sptime < expireTime) {
- delete rel[platform].special;
- delete rel[platform].sptime;
- }
- });
- });
- }
- /**
- * 同步比赛结果
- */
- const syncGamesResult = async (result) => {
- if (IS_DEV) {
- return Logs.out('updateGamesResult', result);
- }
- // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
- // .then(res => {
- // // Logs.out('syncMatchResult', res.data);
- // })
- // .catch(err => {
- // Logs.out('syncMatchResult', err.message);
- // });
- }
- /**
- * 更新比赛结果
- */
- const updateGamesResult = (result) => {
- syncGamesResult(result);
- return Promise.resolve();
- }
- /**
- * 同步中单方案
- */
- // const syncSolutions = (solutions) => {
- // if (IS_DEV) {
- // return Logs.out('syncSolutions', solutions);
- // }
- // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
- // .then(res => {
- // // Logs.out('syncSolutions', res.data);
- // })
- // .catch(err => {
- // Logs.out('syncSolutions', err.message);
- // });
- // }
- /**
- * 更新中单方案
- */
- const getCprKey = (cpr) => {
- const { k, p, v } = cpr;
- return `${k}_${p}_${v}`;
- }
- const compareCpr = (cpr1, cpr2) => {
- const key1 = getCprKey(cpr1);
- const key2 = getCprKey(cpr2);
- return key1 === key2;
- }
- const updateSolutions = (solutions, eventsLogsMap) => {
- if (solutions?.length) {
- const solutionsHistory = GAMES.Solutions;
- const updateIds = { add: [], update: [], retain: [], remove: [] }
- solutions.forEach(item => {
- const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
- if (!solutionsHistory[sid]) {
- solutionsHistory[sid] = item;
- updateIds.add.push(sid);
- return;
- }
- const historySolution = solutionsHistory[sid];
- if (historySolution.sol.win_average !== win_average ||
- historySolution.sol.win_profit_rate !== win_profit_rate ||
- !compareCpr(historySolution.cpr, cpr)) {
- solutionsHistory[sid] = item;
- updateIds.update.push(sid);
- return;
- }
- const { timestamp } = item;
- historySolution.timestamp = timestamp;
- updateIds.retain.push(sid);
- });
- const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
- Object.keys(solutionsHistory).forEach(sid => {
- if (!solutionsMap.has(sid)) {
- delete solutionsHistory[sid];
- updateIds.remove.push(sid);
- }
- });
- const solutionUpdate = {};
- Object.keys(updateIds).forEach(key => {
- if (key == 'retain' || key == 'remove') {
- solutionUpdate[key] = updateIds[key];
- }
- else {
- solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
- }
- });
- // syncSolutions(solutionUpdate);
- if (updateIds.add.length / solutions.length > 0.25 ||
- updateIds.remove.length / solutions.length > 0.25
- ) {
- const { expireEvents, removeEvents } = eventsLogsMap;
- const expireEvemtsMap = {};
- expireEvents.forEach(item => {
- const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
- if (!expireEvemtsMap[mk]) {
- expireEvemtsMap[mk] = {};
- }
- if (!expireEvemtsMap[mk][platform]) {
- expireEvemtsMap[mk][platform] = {};
- }
- if (!expireEvemtsMap[mk][platform].list) {
- expireEvemtsMap[mk][platform].list = [];
- }
- if (!expireEvemtsMap[mk][platform].evtime) {
- expireEvemtsMap[mk][platform].evtime = evtime;
- }
- if (!expireEvemtsMap[mk][platform].sptime) {
- expireEvemtsMap[mk][platform].sptime = sptime;
- }
- expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
- });
- Object.keys(expireEvemtsMap).forEach(mk => {
- Object.keys(expireEvemtsMap[mk]).forEach(platform => {
- Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
- mk, platform,
- expireEvemtsMap[mk][platform].list.length,
- expireEvemtsMap[mk][platform].evtime,
- expireEvemtsMap[mk][platform].sptime,
- )
- });
- });
- Logs.out('solutions add %d, update %d, retain %d, remove %d',
- updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
- }
- else {
- Logs.outDev('solutions update complete', updateIds);
- }
- }
- }
- /**
- * 获取中单方案
- */
- const getSolutions = async ({ win_min, with_events, mk=-1 }) => {
- // Logs.out('getSolutions', win_min);
- const filterMarketType = +mk;
- const { minShowAmount } = getSetting();
- const solutionsList = Object.values(GAMES.Solutions);
- const gamesRelation = getGamesRelation();
- const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
- const mkCount = {
- all: 0,
- rollball: 0,
- today: 0,
- early: 0,
- }
- let solutions = solutionsList.filter(item => {
- const { sol: { win_average } } = item;
- return win_average >= (win_min ?? minShowAmount);
- })
- .map(item => {
- const { info: { id } } = item;
- const { mk, rel } = relationsMap.get(id);
- const marketType = getMarketType(mk);
- mkCount.all ++;
- mkCount[marketType] ++;
- return {
- ...item,
- info: { id, mk, ...rel }
- }
- });
- if (mk >= 0) {
- solutions = solutions.filter(item => {
- const { info: { mk } } = item;
- return mk == filterMarketType;
- });
- }
- solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
- const relIds = solutions.map(item => item.info.id);
- let gamesEvents;
- if (with_events) {
- gamesEvents = getGamesEvents({ relIds });
- }
- return { solutions, gamesEvents, mkCount };
- }
- /**
- * 获取中单方案并按照比赛分组
- */
- const getGamesSolutions = async ({ win_min, with_events, mk=-1, tp=0, sk }) => {
- const filterMarketType = +mk;
- const filterDataType = +tp;
- const { minShowAmount } = getSetting();
- const solutionsList = Object.values(GAMES.Solutions);
- const gamesRelation = getGamesRelation({ listEvents: with_events });
- const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
- const mkCount = {
- all: 0,
- rollball: 0,
- today: 0,
- early: 0,
- }
- const solutionsMap = {};
- solutionsList.forEach(item => {
- const { info: { id }, ...solution } = item;
- const { rule, sol: { win_average } } = solution;
- const ruleType = getRuleType(rule);
- if ((filterDataType == 0 || filterDataType == ruleType) && (!!sk || win_average >= (win_min ?? minShowAmount))) {
- const gameRelation = relationsMap.get(id);
- if (!solutionsMap[id]) {
- solutionsMap[id] = { ...gameRelation, solutions: [] };
- }
- solutionsMap[id].solutions.push(solution);
- }
- })
- const gamesSolutions = Object.values(solutionsMap)
- .filter(item => {
- const { mk, rel, solutions } = item;
- const marketType = getMarketType(mk);
- if (!sk || matchGame(rel, sk)) {
- mkCount.all ++;
- mkCount[marketType] ++;
- solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
- return filterMarketType == -1 || filterMarketType == mk;
- }
- return false;
- })
- .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
- return { gamesSolutions, mkCount };
- }
- /**
- * 获取单个中单方案
- */
- const getSolution = async (sid) => {
- if (!sid) {
- return Promise.reject(new Error('sid is required'));
- }
- const solution = GAMES.Solutions[sid];
- if (!solution) {
- return Promise.reject(new Error('solution not found'));
- }
- return solution;
- }
- /**
- * 通过比赛 ID 获取中单方案
- */
- const getSolutionsByIds = async (ids) => {
- const baseList = Object.values(GAMES.Baselist).flat();
- const baseMap = new Map(baseList.map(item => [item.eventId, item]));
- const result = {};
- ids.forEach(id => {
- const baseGame = baseMap.get(id);
- result[id] = {};
- result[id].matches = baseGame?.matches ?? [];
- result[id].sols = [];
- });
- Object.values(GAMES.Solutions).forEach(item => {
- const { info: { id } } = item;
- if (result[id]) {
- result[id].sols.push(item);
- }
- });
- return result;
- }
- /**
- * 清理中单方案
- */
- const solutionsCleanup = () => {
- const solutionsHistory = GAMES.Solutions;
- const updateIds = { remove: [] }
- Object.keys(solutionsHistory).forEach(sid => {
- const { timestamp } = solutionsHistory[sid];
- const nowTime = Date.now();
- if (nowTime - timestamp > 1000*60) {
- delete solutionsHistory[sid];
- updateIds.remove.push(sid);
- return;
- }
- const solution = solutionsHistory[sid];
- const eventTime = solution.info.timestamp;
- if (nowTime > eventTime) {
- delete solutionsHistory[sid];
- updateIds.remove.push(sid);
- }
- });
- // if (updateIds.remove.length) {
- // syncSolutions(updateIds);
- // }
- }
- /**
- * 清理更新时间戳
- */
- const cleanupUpdateTimestamp = () => {
- const updateTimestamp = GAMES.UpdateTimestamp;
- const nowTime = Date.now();
- const expireTime = nowTime - 1000*60;
- Object.keys(updateTimestamp).forEach(key => {
- if (updateTimestamp[key] < expireTime) {
- delete updateTimestamp[key];
- }
- });
- }
- /**
- * 定时清理中单方案
- * 定时清理盘口信息
- */
- setInterval(() => {
- // cleanupBaseList();
- solutionsCleanup();
- gamesRelationCleanup();
- cleanupUpdateTimestamp();
- }, 1000*30);
- /**
- * 获取综合利润
- */
- const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
- const { innerDefaultAmount, innerRebateRatio } = getSetting();
- inner_base = inner_base ? +inner_base : innerDefaultAmount;
- inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
- const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
- return profit;
- }
- /**
- * 通过 sid 获取综合利润
- */
- const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
- const preSolution = GAMES.Solutions[sid1];
- const subSolution = GAMES.Solutions[sid2];
- const sol1 = preSolution?.sol;
- const sol2 = subSolution?.sol;
- if (!sol1) {
- return Promise.reject(new Error('sid1 已失效'));
- }
- if (!sol2) {
- return Promise.reject(new Error('sid2 已失效'));
- }
- const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
- return { profit, solutions: [preSolution, subSolution] };
- }
- /**
- * 通过盘口信息获取综合利润
- */
- const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
- if (!betInfo1?.cross_type) {
- return Promise.reject(new Error('第一个下注信息无效'));
- }
- if (!betInfo2?.cross_type) {
- return Promise.reject(new Error('第二个下注信息无效'));
- }
- const { innerDefaultAmount, innerRebateRatio } = getSetting();
- inner_base = inner_base ? +inner_base : innerDefaultAmount;
- inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
- if (fixed) {
- return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
- }
- const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
- return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
- }
- /**
- * 同步Qboss平台配置
- */
- const syncQbossConfig = () => {
- const setting = getSetting();
- if (!setting.syncSettingEnabled) {
- // Logs.outDev('syncQbossConfig disabled');
- return setTimeout(syncQbossConfig, 1000*5);
- }
- axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
- .then(res => {
- const { data } = res;
- if (!data?.data) {
- throw new Error('syncQbossConfig data is empty');
- }
- const {
- qboss_return_ratio,
- ob_return_ratio, ob_return_type,
- hg_return_ratio, hg_return_type,
- qboss_jq_add_odds, qboss_jq_add_hours,
- qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
- } = data.data;
- const qbossSetting = {
- innerRebateRatio: +qboss_return_ratio,
- obRebateRatio: +ob_return_ratio,
- obRebateType: +ob_return_type,
- hgRebateRatio: +hg_return_ratio,
- hgRebateType: +hg_return_type,
- subsidyTime: +qboss_jq_add_hours,
- subsidyAmount: +qboss_jq_add_odds,
- subsidyRbWmAmount: +qboss_gq_add_dy_odds,
- subsidyRbOtAmount: +qboss_gq_add_jq_odds,
- };
- const settingFields = {};
- let needUpdate = false;
- Object.keys(qbossSetting).forEach(key => {
- if (qbossSetting[key] !== setting[key]) {
- settingFields[key] = qbossSetting[key];
- needUpdate = true;
- }
- });
- if (needUpdate) {
- Setting.update(settingFields);
- // Logs.outDev('syncQbossConfig', settingFields);
- }
- // else {
- // Logs.outDev('syncQbossConfig no change');
- // }
- })
- .catch(err => {
- Logs.out('syncQbossConfig error', err.message);
- })
- .finally(() => {
- setTimeout(syncQbossConfig, 1000*15);
- });
- }
- syncQbossConfig();
- /**
- * 异常通知
- */
- const notifyException = (message) => {
- if (IS_DEV) {
- return Logs.out('notifyException', { message });
- }
- const chat_id = -1003032820471;
- axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
- .then(() => {
- Logs.out('notifyException', '通知成功');
- })
- .catch(err => {
- Logs.out('notifyException', err.message);
- });
- }
- /**
- * 从子进程获取数据
- */
- const getDataFromChild = (type, callback) => {
- const id = ++Request.count;
- Request.callbacks[id] = callback;
- events_child.send({ method: 'get', id, type });
- }
- /**
- * 向子进程发送数据
- */
- const postDataToChild = (type, data) => {
- events_child.send({ method: 'post', type, data });
- }
- /**
- * 处理子进程消息
- */
- events_child.on('message', async (message) => {
- const { callbacks } = Request;
- const { method, id, type, data } = message;
- if (method == 'get' && id) {
- let responseData = null;
- if (type == 'getGamesRelation') {
- responseData = getGamesRelation({ listEvents: true });
- }
- else if (type == 'getSetting') {
- responseData = getSetting();
- }
- // else if (type == 'getSolutionHistory') {
- // responseData = getSolutionHistory();
- // }
- events_child.send({ type: 'response', id, data: responseData });
- }
- else if (method == 'post') {
- if (type == 'updateSolutions') {
- updateSolutions(data.solutions, data.eventsLogsMap);
- }
- }
- else if (method == 'response' && id && callbacks[id]) {
- callbacks[id](data);
- delete callbacks[id];
- }
- });
- events_child.stderr?.on('data', data => {
- Logs.out('events_child stderr', data.toString());
- });
- const settingUpdate = (fields) => {
- updateSetting(fields);
- postDataToChild('updateSetting', fields);
- }
- const syncSetting = async () => {
- const setting = await Setting.get();
- settingUpdate(setting.toObject());
- }
- syncSetting();
- Setting.onUpdate(settingUpdate);
- /**
- * 保存GAMES数据到缓存文件
- */
- const saveGamesToCache = () => {
- Cache.setData(GamesCacheFile, GAMES, err => {
- if (err) {
- Logs.out('Failed to save games cache:', err.message);
- }
- else {
- Logs.out('Games cache saved successfully');
- }
- });
- }
- /**
- * 从缓存文件加载GAMES数据
- */
- const loadGamesFromCache = () => {
- const gamesCacheData = Cache.getData(GamesCacheFile, true);
- Object.keys(GAMES).forEach(key => {
- if (gamesCacheData[key]) {
- GAMES[key] = gamesCacheData[key];
- }
- });
- Logs.out('Games cache loaded successfully');
- }
- // 在模块加载时尝试从缓存恢复数据
- loadGamesFromCache();
- // 监听进程退出事件,保存GAMES数据
- process.on('exit', saveGamesToCache);
- process.on('SIGINT', () => {
- process.exit(0);
- });
- process.on('SIGTERM', () => {
- process.exit(0);
- });
- process.on('SIGUSR2', () => {
- process.exit(0);
- });
- module.exports = {
- updateLeaguesList, getFilteredLeagues,
- updateGamesList, updateGamesEvents, updateBaseEvents,
- getGamesRelation,
- updateGamesResult,
- updateOriginalData, getOriginalData,
- getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
- getTotalProfitWithSid,
- getTotalProfitWithBetInfo,
- notifyException,
- }
|