main.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. import 'dotenv/config';
  2. import { pinnacleRequest, getPsteryRelations, updateBaseEvents, notifyException } from "./libs/pinnacleClient.js";
  3. import { Logs } from "./libs/logs.js";
  4. import { getData, setData } from "./libs/cache.js";
  5. const gamesMapCacheFile = 'data/gamesCache.json';
  6. const globalDataCacheFile = 'data/globalDataCache.json';
  7. const TP = 'ps_9_9_1';
  8. const IS_DEV = process.env.NODE_ENV == 'development';
  9. const GLOBAL_DATA = {
  10. filtedLeagues: [],
  11. filtedGames: [],
  12. gamesMap: {},
  13. straightFixturesVersion: 0,
  14. straightFixturesCount: 0,
  15. specialFixturesVersion: 0,
  16. specialFixturesCount: 0,
  17. straightOddsVersion: 0,
  18. // straightOddsCount: 0,
  19. specialsOddsVersion: 0,
  20. // specialsOddsCount: 0,
  21. requestErrorCount: 0,
  22. loopActive: false,
  23. loopResultTime: 0,
  24. };
  25. const resetVersionsCount = () => {
  26. GLOBAL_DATA.straightFixturesVersion = 0;
  27. GLOBAL_DATA.specialFixturesVersion = 0;
  28. GLOBAL_DATA.straightOddsVersion = 0;
  29. GLOBAL_DATA.specialsOddsVersion = 0;
  30. GLOBAL_DATA.straightFixturesCount = 0;
  31. GLOBAL_DATA.specialFixturesCount = 0;
  32. }
  33. const incrementVersionsCount = () => {
  34. GLOBAL_DATA.straightFixturesCount = 0;
  35. GLOBAL_DATA.specialFixturesCount = 0;
  36. }
  37. /**
  38. * 获取指定时区当前日期或时间
  39. * @param {number} offsetHours - 时区相对 UTC 的偏移(例如:-4 表示 GMT-4)
  40. * @param {boolean} [withTime=false] - 是否返回完整时间(默认只返回日期)
  41. * @returns {string} 格式化的日期或时间字符串
  42. */
  43. const getDateInTimezone = (offsetHours, withTime = false) => {
  44. const nowUTC = new Date();
  45. const targetTime = new Date(nowUTC.getTime() + offsetHours * 60 * 60 * 1000);
  46. const year = targetTime.getUTCFullYear();
  47. const month = String(targetTime.getUTCMonth() + 1).padStart(2, '0');
  48. const day = String(targetTime.getUTCDate()).padStart(2, '0');
  49. if (!withTime) {
  50. return `${year}-${month}-${day}`;
  51. }
  52. const hours = String(targetTime.getUTCHours()).padStart(2, '0');
  53. const minutes = String(targetTime.getUTCMinutes()).padStart(2, '0');
  54. const seconds = String(targetTime.getUTCSeconds()).padStart(2, '0');
  55. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  56. }
  57. const pinnacleGet = async (endpoint, params) => {
  58. return pinnacleRequest({
  59. endpoint,
  60. params,
  61. username: process.env.PINNACLE_USERNAME,
  62. password: process.env.PINNACLE_PASSWORD,
  63. proxy: process.env.NODE_HTTP_PROXY,
  64. })
  65. .catch(err => {
  66. const source = { endpoint, params };
  67. if (err?.response?.data) {
  68. const data = err.response.data;
  69. Object.assign(source, { data });
  70. }
  71. err.source = source;
  72. return Promise.reject(err);
  73. });
  74. };
  75. // const pinnaclePost = async(endpoint, data) => {
  76. // return pinnacleRequest({
  77. // endpoint,
  78. // data,
  79. // method: 'POST',
  80. // username: process.env.PINNACLE_USERNAME,
  81. // password: process.env.PINNACLE_PASSWORD,
  82. // proxy: process.env.NODE_HTTP_PROXY,
  83. // });
  84. // };
  85. const isArrayEqualUnordered = (arr1, arr2) => {
  86. if (arr1.length !== arr2.length) return false;
  87. const s1 = [...arr1].sort();
  88. const s2 = [...arr2].sort();
  89. return s1.every((v, i) => v === s2[i]);
  90. }
  91. const getFiltedGames = () => {
  92. return new Promise(resolve => {
  93. const updateFiltedGames = () => {
  94. getPsteryRelations()
  95. .then(res => {
  96. if (res.statusCode !== 200) {
  97. throw new Error(res.message);
  98. }
  99. // Logs.outDev('update filted games', res.data);
  100. const games = res.data.map(game => {
  101. const { eventId, leagueId } = game?.rel?.ps ?? {};
  102. return {
  103. eventId,
  104. leagueId,
  105. };
  106. });
  107. const newFiltedLeagues = [...new Set(games.map(game => game.leagueId).filter(leagueId => leagueId))];
  108. if (!isArrayEqualUnordered(newFiltedLeagues, GLOBAL_DATA.filtedLeagues)) {
  109. Logs.outDev('filted leagues changed', newFiltedLeagues);
  110. resetVersionsCount();
  111. GLOBAL_DATA.filtedLeagues = newFiltedLeagues;
  112. }
  113. GLOBAL_DATA.filtedGames = games.map(game => game.eventId).filter(eventId => eventId);
  114. resolve();
  115. setTimeout(updateFiltedGames, 1000 * 60);
  116. })
  117. .catch(err => {
  118. Logs.err('failed to update filted games:', err.message);
  119. setTimeout(updateFiltedGames, 1000 * 5);
  120. });
  121. }
  122. updateFiltedGames();
  123. });
  124. }
  125. const getStraightFixtures = async () => {
  126. if (!GLOBAL_DATA.filtedLeagues.length) {
  127. return Promise.reject(new Error('no filted leagues'));
  128. }
  129. const leagueIds = GLOBAL_DATA.filtedLeagues.join(',');
  130. let since = GLOBAL_DATA.straightFixturesVersion;
  131. if (GLOBAL_DATA.straightFixturesCount >= 12) {
  132. since = 0;
  133. GLOBAL_DATA.straightFixturesCount = 0;
  134. }
  135. if (since == 0) {
  136. Logs.outDev('full update straight fixtures');
  137. }
  138. return pinnacleGet('/v3/fixtures', { sportId: 29, leagueIds, since })
  139. .then(data => {
  140. const { league, last } = data;
  141. if (!last) {
  142. return {};
  143. }
  144. GLOBAL_DATA.straightFixturesVersion = last;
  145. const games = league?.map(league => {
  146. const { id: leagueId, events } = league;
  147. return events?.map(event => {
  148. const { starts } = event;
  149. const timestamp = new Date(starts).getTime();
  150. return { leagueId, ...event, timestamp };
  151. });
  152. })
  153. .flat() ?? [];
  154. const update = since == 0 ? 'full' : 'increment';
  155. return { games, update };
  156. });
  157. }
  158. const updateStraightFixtures = async () => {
  159. return getStraightFixtures()
  160. .then(data => {
  161. const { games, update } = data;
  162. const { gamesMap } = GLOBAL_DATA;
  163. if (games?.length) {
  164. games.forEach(game => {
  165. const { id } = game;
  166. if (!gamesMap[id]) {
  167. gamesMap[id] = game;
  168. }
  169. else {
  170. Object.assign(gamesMap[id], game);
  171. }
  172. });
  173. }
  174. if (update && update == 'full') {
  175. const gamesSet = new Set(games.map(game => game.id));
  176. Object.keys(gamesMap).forEach(key => {
  177. if (!gamesSet.has(+key)) {
  178. delete gamesMap[key];
  179. }
  180. });
  181. }
  182. });
  183. }
  184. const getStraightOdds = async () => {
  185. if (!GLOBAL_DATA.filtedLeagues.length) {
  186. return Promise.reject(new Error('no filted leagues'));
  187. }
  188. const leagueIds = GLOBAL_DATA.filtedLeagues.join(',');
  189. const since = GLOBAL_DATA.straightOddsVersion;
  190. // if (GLOBAL_DATA.straightOddsCount >= 27) {
  191. // since = 0;
  192. // GLOBAL_DATA.straightOddsCount = 3;
  193. // }
  194. if (since == 0) {
  195. Logs.outDev('full update straight odds');
  196. }
  197. return pinnacleGet('/v3/odds', { sportId: 29, oddsFormat: 'Decimal', leagueIds, since })
  198. .then(data => {
  199. const { leagues, last } = data;
  200. if (!last) {
  201. return [];
  202. }
  203. GLOBAL_DATA.straightOddsVersion = last;
  204. const games = leagues?.flatMap(league => league.events);
  205. return games?.map(item => {
  206. const { periods, ...rest } = item;
  207. const period = periods?.find(period => period.number == 0);
  208. if (!period) {
  209. return rest;
  210. }
  211. return { ...rest, period };
  212. }) ?? [];
  213. });
  214. }
  215. const updateStraightOdds = async () => {
  216. return getStraightOdds()
  217. .then(games => {
  218. if (games.length) {
  219. const { gamesMap } = GLOBAL_DATA;
  220. games.forEach(game => {
  221. const { id, ...rest } = game;
  222. const localGame = gamesMap[id];
  223. if (localGame) {
  224. Object.assign(localGame, rest);
  225. }
  226. });
  227. }
  228. });
  229. }
  230. const getSpecialFixtures = async () => {
  231. if (!GLOBAL_DATA.filtedLeagues.length) {
  232. return Promise.reject(new Error('no filted leagues'));
  233. }
  234. const leagueIds = GLOBAL_DATA.filtedLeagues.join(',');
  235. let since = GLOBAL_DATA.specialFixturesVersion;
  236. if (GLOBAL_DATA.specialFixturesCount >= 18) {
  237. since = 0;
  238. GLOBAL_DATA.specialFixturesCount = 6;
  239. }
  240. if (since == 0) {
  241. Logs.outDev('full update special fixtures');
  242. }
  243. return pinnacleGet('/v2/fixtures/special', { sportId: 29, leagueIds, since })
  244. .then(data => {
  245. const { leagues, last } = data;
  246. if (!last) {
  247. return [];
  248. }
  249. GLOBAL_DATA.specialFixturesVersion = last;
  250. const specials = leagues?.map(league => {
  251. const { specials } = league;
  252. return specials?.filter(special => special.event)
  253. .map(special => {
  254. const { event: { id: eventId }, ...rest } = special ?? { event: {} };
  255. return { eventId, ...rest };
  256. }) ?? [];
  257. })
  258. .flat()
  259. .filter(special => {
  260. if (special.name != 'Winning Margin' && special.name != 'Exact Total Goals') {
  261. return false;
  262. }
  263. return true;
  264. }) ?? [];
  265. const update = since == 0 ? 'full' : 'increment';
  266. return { specials, update };
  267. });
  268. }
  269. const mergeContestants = (localContestants=[], remoteContestants=[]) => {
  270. const localContestantsMap = new Map(localContestants.map(contestant => [contestant.id, contestant]));
  271. remoteContestants.forEach(contestant => {
  272. const localContestant = localContestantsMap.get(contestant.id);
  273. if (localContestant) {
  274. Object.assign(localContestant, contestant);
  275. }
  276. else {
  277. localContestants.push(contestant);
  278. }
  279. });
  280. const remoteContestantsMap = new Map(remoteContestants.map(contestant => [contestant.id, contestant]));
  281. for (let i = localContestants.length - 1; i >= 0; i--) {
  282. if (!remoteContestantsMap.has(localContestants[i].id)) {
  283. localContestants.splice(i, 1);
  284. }
  285. }
  286. return localContestants;
  287. }
  288. const updateSpecialFixtures = async () => {
  289. return getSpecialFixtures()
  290. .then(data => {
  291. const { specials, update } = data;
  292. if (specials?.length) {
  293. const { gamesMap } = GLOBAL_DATA;
  294. const gamesSpecialsMap = {};
  295. specials.forEach(special => {
  296. const { eventId } = special;
  297. if (!gamesSpecialsMap[eventId]) {
  298. gamesSpecialsMap[eventId] = {};
  299. }
  300. if (special.name == 'Winning Margin') {
  301. gamesSpecialsMap[eventId].winningMargin = special;
  302. }
  303. else if (special.name == 'Exact Total Goals') {
  304. gamesSpecialsMap[eventId].exactTotalGoals = special;
  305. }
  306. });
  307. Object.keys(gamesSpecialsMap).forEach(eventId => {
  308. if (!gamesMap[eventId]) {
  309. return;
  310. }
  311. if (!gamesMap[eventId].specials) {
  312. gamesMap[eventId].specials = {};
  313. }
  314. const localSpecials = gamesMap[eventId].specials;
  315. const remoteSpecials = gamesSpecialsMap[eventId];
  316. if (localSpecials.winningMargin && remoteSpecials.winningMargin) {
  317. const { contestants: winningMarginContestants, ...winningMarginRest } = remoteSpecials.winningMargin;
  318. Object.assign(localSpecials.winningMargin, winningMarginRest);
  319. mergeContestants(localSpecials.winningMargin.contestants, winningMarginContestants);
  320. }
  321. // else if (localSpecials.winningMargin && !remoteSpecials.winningMargin) {
  322. // Logs.outDev('delete winningMargin', localSpecials.winningMargin);
  323. // delete localSpecials.winningMargin;
  324. // }
  325. else if (remoteSpecials.winningMargin) {
  326. localSpecials.winningMargin = remoteSpecials.winningMargin;
  327. }
  328. if (localSpecials.exactTotalGoals && remoteSpecials.exactTotalGoals) {
  329. const { contestants: exactTotalGoalsContestants, ...exactTotalGoalsRest } = remoteSpecials.exactTotalGoals;
  330. Object.assign(localSpecials.exactTotalGoals, exactTotalGoalsRest);
  331. mergeContestants(localSpecials.exactTotalGoals.contestants, exactTotalGoalsContestants);
  332. }
  333. // else if (localSpecials.exactTotalGoals && !remoteSpecials.exactTotalGoals) {
  334. // Logs.outDev('delete exactTotalGoals', localSpecials.exactTotalGoals);
  335. // delete localSpecials.exactTotalGoals;
  336. // }
  337. else if (remoteSpecials.exactTotalGoals) {
  338. localSpecials.exactTotalGoals = remoteSpecials.exactTotalGoals;
  339. }
  340. });
  341. }
  342. });
  343. }
  344. const getSpecialsOdds = async () => {
  345. if (!GLOBAL_DATA.filtedLeagues.length) {
  346. return Promise.reject(new Error('no filted leagues'));
  347. }
  348. const leagueIds = GLOBAL_DATA.filtedLeagues.join(',');
  349. const since = GLOBAL_DATA.specialsOddsVersion;
  350. // if (GLOBAL_DATA.specialsOddsCount >= 33) {
  351. // since = 0;
  352. // GLOBAL_DATA.specialsOddsCount = 9;
  353. // }
  354. if (since == 0) {
  355. Logs.outDev('full update specials odds');
  356. }
  357. return pinnacleGet('/v2/odds/special', { sportId: 29, oddsFormat: 'Decimal', leagueIds, since })
  358. .then(data => {
  359. const { leagues, last } = data;
  360. if (!last) {
  361. return [];
  362. }
  363. GLOBAL_DATA.specialsOddsVersion = last;
  364. return leagues?.flatMap(league => league.specials);
  365. });
  366. }
  367. const updateSpecialsOdds = async () => {
  368. return getSpecialsOdds()
  369. .then(specials => {
  370. if (specials.length) {
  371. const { gamesMap } = GLOBAL_DATA;
  372. const contestants = Object.values(gamesMap)
  373. .filter(game => game.specials)
  374. .map(game => {
  375. const { specials } = game;
  376. const contestants = Object.values(specials).map(special => {
  377. const { contestants } = special;
  378. return contestants.map(contestant => [contestant.id, contestant]);
  379. });
  380. return contestants;
  381. }).flat(2);
  382. const contestantsMap = new Map(contestants);
  383. const lines = specials.flatMap(special => special.contestantLines);
  384. lines.forEach(line => {
  385. const { id, handicap, lineId, max, price } = line;
  386. const contestant = contestantsMap.get(id);
  387. if (!contestant) {
  388. return;
  389. }
  390. contestant.handicap = handicap;
  391. contestant.lineId = lineId;
  392. contestant.max = max;
  393. contestant.price = price;
  394. });
  395. }
  396. });
  397. }
  398. const getInRunning = async () => {
  399. return pinnacleGet('/v2/inrunning')
  400. .then(data => {
  401. const sportId = 29;
  402. const leagues = data.sports?.find(sport => sport.id == sportId)?.leagues ?? [];
  403. return leagues.filter(league => {
  404. const { id } = league;
  405. const filtedLeaguesSet = new Set(GLOBAL_DATA.filtedLeagues);
  406. return filtedLeaguesSet.has(id);
  407. }).flatMap(league => league.events);
  408. });
  409. }
  410. const updateInRunning = async () => {
  411. return getInRunning()
  412. .then(games => {
  413. if (!games.length) {
  414. return;
  415. }
  416. const { gamesMap } = GLOBAL_DATA;
  417. games.forEach(game => {
  418. const { id, state, elapsed } = game;
  419. const localGame = gamesMap[id];
  420. if (localGame) {
  421. Object.assign(localGame, { state, elapsed });
  422. }
  423. });
  424. });
  425. }
  426. const ratioAccept = (ratio) => {
  427. if (ratio > 0) {
  428. return 'a';
  429. }
  430. return '';
  431. }
  432. const ratioString = (ratio) => {
  433. ratio = Math.abs(ratio);
  434. ratio = ratio.toString();
  435. ratio = ratio.replace(/\./, '');
  436. return ratio;
  437. }
  438. const parseSpreads = (spreads, wm) => {
  439. // 让分盘
  440. if (!spreads?.length) {
  441. return null;
  442. }
  443. const events = {};
  444. spreads.forEach(spread => {
  445. const { hdp, home, away } = spread;
  446. // if (!(hdp % 1) || !!(hdp % 0.5)) {
  447. // // 整数或不能被0.5整除的让分盘不处理
  448. // return;
  449. // }
  450. const ratio_ro = hdp;
  451. const ratio_r = ratio_ro - wm;
  452. events[`ior_r${ratioAccept(ratio_r)}h_${ratioString(ratio_r)}`] = {
  453. v: home,
  454. r: wm != 0 ? `ior_r${ratioAccept(ratio_ro)}h_${ratioString(ratio_ro)}` : undefined
  455. };
  456. events[`ior_r${ratioAccept(-ratio_r)}c_${ratioString(ratio_r)}`] = {
  457. v: away,
  458. r: wm != 0 ? `ior_r${ratioAccept(-ratio_ro)}c_${ratioString(ratio_ro)}` : undefined
  459. };
  460. });
  461. return events;
  462. }
  463. const parseMoneyline = (moneyline) => {
  464. // 胜平负
  465. if (!moneyline) {
  466. return null;
  467. }
  468. const { home, away, draw } = moneyline;
  469. return {
  470. 'ior_mh': { v: home },
  471. 'ior_mc': { v: away },
  472. 'ior_mn': { v: draw },
  473. }
  474. }
  475. const parseTotals = (totals) => {
  476. // 大小球盘
  477. if (!totals?.length) {
  478. return null;
  479. }
  480. const events = {};
  481. totals.forEach(total => {
  482. const { points, over, under } = total;
  483. events[`ior_ouc_${ratioString(points)}`] = { v: over };
  484. events[`ior_ouh_${ratioString(points)}`] = { v: under };
  485. });
  486. return events;
  487. }
  488. const parsePeriod = (period, wm) => {
  489. const { cutoff='', status=0, spreads=[], moneyline={}, totals=[] } = period;
  490. const cutoffTime = new Date(cutoff).getTime();
  491. const nowTime = Date.now();
  492. if (status != 1 || cutoffTime < nowTime) {
  493. return null;
  494. }
  495. const events = {};
  496. Object.assign(events, parseSpreads(spreads, wm));
  497. Object.assign(events, parseMoneyline(moneyline));
  498. Object.assign(events, parseTotals(totals));
  499. return events;
  500. }
  501. const parseWinningMargin = (winningMargin, home, away) => {
  502. const { cutoff='', status='', contestants=[] } = winningMargin;
  503. const cutoffTime = new Date(cutoff).getTime();
  504. const nowTime = Date.now();
  505. if (status != 'O' || cutoffTime < nowTime || !contestants?.length) {
  506. return null;
  507. }
  508. const events = {};
  509. contestants.forEach(contestant => {
  510. const { name, price } = contestant;
  511. const nr = name.match(/\d+$/)?.[0];
  512. if (!nr) {
  513. return;
  514. }
  515. let side;
  516. if (name.startsWith(home)) {
  517. side = 'h';
  518. }
  519. else if (name.startsWith(away)) {
  520. side = 'c';
  521. }
  522. else {
  523. return;
  524. }
  525. events[`ior_wm${side}_${nr}`] = { v: price };
  526. });
  527. return events;
  528. }
  529. const parseExactTotalGoals = (exactTotalGoals) => {
  530. const { cutoff='', status='', contestants=[] } = exactTotalGoals;
  531. const cutoffTime = new Date(cutoff).getTime();
  532. const nowTime = Date.now();
  533. if (status != 'O' || cutoffTime < nowTime || !contestants?.length) {
  534. return null;
  535. }
  536. const events = {};
  537. contestants.forEach(contestant => {
  538. const { name, price } = contestant;
  539. if (+name >= 1 && +name <= 7) {
  540. events[`ior_ot_${name}`] = { v: price };
  541. }
  542. });
  543. return events;
  544. }
  545. const parseRbState = (state) => {
  546. let stage = null;
  547. if (state == 1) {
  548. stage = '1H';
  549. }
  550. else if (state == 2) {
  551. stage = 'HT';
  552. }
  553. else if (state == 3) {
  554. stage = '2H';
  555. }
  556. else if (state >= 4) {
  557. stage = 'ET';
  558. }
  559. return stage;
  560. }
  561. const parseGame = (game) => {
  562. const { eventId=0, originId=0, period={}, specials={}, home, away, marketType, state, elapsed, homeScore=0, awayScore=0 } = game;
  563. const { winningMargin={}, exactTotalGoals={} } = specials;
  564. const wm = homeScore - awayScore;
  565. const score = `${homeScore}-${awayScore}`;
  566. const events = parsePeriod(period, wm) ?? {};
  567. const stage = parseRbState(state);
  568. const retime = elapsed ? `${elapsed}'` : '';
  569. const evtime = Date.now();
  570. Object.assign(events, parseWinningMargin(winningMargin, home, away));
  571. Object.assign(events, parseExactTotalGoals(exactTotalGoals));
  572. return { eventId, originId, events, evtime, stage, retime, score, wm, marketType };
  573. }
  574. const getGames = () => {
  575. const { filtedGames, gamesMap } = GLOBAL_DATA;
  576. const filtedGamesSet = new Set(filtedGames);
  577. const nowTime = Date.now();
  578. const gamesData = {};
  579. Object.values(gamesMap).forEach(game => {
  580. const { id, liveStatus, parentId, resultingUnit, timestamp } = game;
  581. if (resultingUnit !== 'Regular') {
  582. return false; // 非常规赛事不处理
  583. }
  584. const gmtMinus4Date = getDateInTimezone(-4);
  585. const todayEndTime = new Date(`${gmtMinus4Date} 23:59:59 GMT-4`).getTime();
  586. const tomorrowEndTime = todayEndTime + 24 * 60 * 60 * 1000;
  587. if (liveStatus == 1 && timestamp < nowTime) {
  588. game.marketType = 2; // 滚球赛事
  589. }
  590. else if (liveStatus != 1 && timestamp > nowTime && timestamp <= todayEndTime) {
  591. game.marketType = 1; // 今日赛事
  592. }
  593. else if (liveStatus != 1 && timestamp > todayEndTime && timestamp <= tomorrowEndTime) {
  594. game.marketType = 0; // 明日早盘赛事
  595. }
  596. else {
  597. game.marketType = -1; // 非近期赛事
  598. }
  599. if (game.marketType < 0) {
  600. return false; // 非近期赛事不处理
  601. }
  602. let actived = false;
  603. if (liveStatus != 1 && filtedGamesSet.has(id)) {
  604. actived = true; // 在赛前列表中
  605. game.eventId = id;
  606. game.originId = 0;
  607. }
  608. else if (liveStatus == 1 && filtedGamesSet.has(parentId)) {
  609. actived = true; // 在滚球列表中
  610. game.eventId = parentId;
  611. game.originId = id;
  612. }
  613. if (actived) {
  614. const gameInfo = parseGame(game);
  615. const { marketType, ...rest } = gameInfo;
  616. if (!gamesData[marketType]) {
  617. gamesData[marketType] = [];
  618. }
  619. gamesData[marketType].push(rest);
  620. }
  621. });
  622. return gamesData;
  623. }
  624. const pinnacleDataLoop = () => {
  625. updateStraightFixtures()
  626. .then(() => {
  627. return Promise.all([
  628. updateStraightOdds(),
  629. updateSpecialFixtures(),
  630. updateInRunning(),
  631. ]);
  632. })
  633. .then(() => {
  634. return updateSpecialsOdds();
  635. })
  636. .then(() => {
  637. if (!GLOBAL_DATA.loopActive) {
  638. GLOBAL_DATA.loopActive = true;
  639. Logs.out('loop active');
  640. notifyException('Pinnacle API startup.');
  641. }
  642. if (GLOBAL_DATA.requestErrorCount > 0) {
  643. GLOBAL_DATA.requestErrorCount = 0;
  644. Logs.out('request error count reset');
  645. }
  646. const nowTime = Date.now();
  647. const loopDuration = nowTime - GLOBAL_DATA.loopResultTime;
  648. GLOBAL_DATA.loopResultTime = nowTime;
  649. if (loopDuration > 15000) {
  650. Logs.out('loop duration is too long', loopDuration);
  651. }
  652. else {
  653. Logs.outDev('loop duration', loopDuration);
  654. }
  655. const { straightFixturesVersion: sfv, specialFixturesVersion: pfv, straightOddsVersion: sov, specialsOddsVersion: pov } = GLOBAL_DATA;
  656. const timestamp = Math.max(sfv, pfv, sov, pov);
  657. const games = getGames();
  658. const data = { games, timestamp, tp: TP };
  659. updateBaseEvents(data);
  660. if (IS_DEV) {
  661. setData(gamesMapCacheFile, GLOBAL_DATA.gamesMap)
  662. .then(() => {
  663. Logs.outDev('games map saved');
  664. })
  665. .catch(err => {
  666. Logs.err('failed to save games map', err.message);
  667. });
  668. }
  669. })
  670. .catch(err => {
  671. Logs.err(err.message, err.source);
  672. GLOBAL_DATA.requestErrorCount++;
  673. if (GLOBAL_DATA.loopActive && GLOBAL_DATA.requestErrorCount > 5) {
  674. const exceptionMessage = 'request errors have reached the limit';
  675. Logs.out(exceptionMessage);
  676. GLOBAL_DATA.loopActive = false;
  677. Logs.out('loop inactive');
  678. notifyException(`Pinnacle API paused. ${exceptionMessage}. ${err.message}`);
  679. }
  680. })
  681. .finally(() => {
  682. const { loopActive } = GLOBAL_DATA;
  683. let loopDelay = 1000 * 5;
  684. if (!loopActive) {
  685. loopDelay = 1000 * 60;
  686. resetVersionsCount();
  687. }
  688. else {
  689. incrementVersionsCount();
  690. }
  691. setTimeout(pinnacleDataLoop, loopDelay);
  692. });
  693. }
  694. /**
  695. * 缓存GLOBAL_DATA数据到文件
  696. */
  697. const saveGlobalDataToCache = async () => {
  698. return setData(globalDataCacheFile, GLOBAL_DATA);
  699. }
  700. const loadGlobalDataFromCache = async () => {
  701. return getData(globalDataCacheFile)
  702. .then(data => {
  703. if (!data) {
  704. return;
  705. }
  706. Object.keys(GLOBAL_DATA).forEach(key => {
  707. if (key in data) {
  708. GLOBAL_DATA[key] = data[key];
  709. }
  710. });
  711. });
  712. }
  713. // 监听进程退出事件,保存GLOBAL_DATA数据
  714. const saveExit = (code) => {
  715. saveGlobalDataToCache()
  716. .then(() => {
  717. Logs.out('global data saved');
  718. })
  719. .catch(err => {
  720. Logs.err('failed to save global data', err.message);
  721. })
  722. .finally(() => {
  723. process.exit(code);
  724. });
  725. }
  726. process.on('SIGINT', () => {
  727. saveExit(0);
  728. });
  729. process.on('SIGTERM', () => {
  730. saveExit(0);
  731. });
  732. process.on('SIGUSR2', () => {
  733. saveExit(0);
  734. });
  735. (() => {
  736. if (!process.env.PINNACLE_USERNAME || !process.env.PINNACLE_PASSWORD) {
  737. Logs.err('USERNAME or PASSWORD is not set');
  738. return;
  739. }
  740. loadGlobalDataFromCache()
  741. .then(() => {
  742. Logs.out('global data loaded');
  743. })
  744. .catch(err => {
  745. Logs.err('failed to load global data', err.message);
  746. })
  747. .finally(() => {
  748. GLOBAL_DATA.loopResultTime = Date.now();
  749. GLOBAL_DATA.loopActive = true;
  750. return getFiltedGames();
  751. })
  752. .then(pinnacleDataLoop);
  753. })();