-
Notifications
You must be signed in to change notification settings - Fork 2
/
SportData.js
274 lines (210 loc) · 8.23 KB
/
SportData.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
const conf = require('ocore/conf.js');
const { default: axios } = require("axios");
const moment = require('moment');
const abbreviations = require('abbreviations');
const { soccerCompetitions } = require('abbreviations/soccerCompetitions');
const { uniq, isEmpty } = require('lodash');
const marketDB = require('./db')
const UPDATE_INTERVAL = 60 * 60 * 1000; // 1 hour in ms
class SportDataService {
constructor() {
this.calendar = {
soccer: []
};
this.championships = {
soccer: []
};
this.odds = { // by expected feed name
soccer: {
}
}
this.crests = {
soccer: {
}
}
this.footballApi = axios.create({
baseURL: `https://api.football-data.org`,
headers: {
['X-Auth-Token']: conf.footballDataApiKey
}
});
}
getCalendar(sport, championship, page) {
const limit = conf.limitMarketsOnPage;
const offset = (page - 1) * limit;
return (this.calendar[sport] || []).filter(({ championship: c }) => championship === 'all' || championship === c).slice(offset, offset + limit);
}
getCrest(sport, championship, team_id) {
if (sport in this.crests) {
if (championship in this.crests[sport]) {
if(`${team_id}` in this.crests[sport][championship]){
return this.crests[sport][championship][`${team_id}`];
}
}
}
return null
}
async getOdds(sport, feed_name) {
if (this.odds[sport]) {
if (this.odds[sport][feed_name]) {
return this.odds[sport][feed_name];
} else {
return await marketDB.api.getBookmakerOddsByFeedName(feed_name);
}
} else {
return null;
}
}
getCalendarLength(sport, championship) {
if (this.calendar[sport]) {
const sportCalendar = this.calendar[sport] || [];
if (championship !== 'all') {
return sportCalendar.filter(({ championship: c }) => c === championship).length
} else {
return sportCalendar.length;
}
}
return 0
}
getChampionships(sport) {
return sport ? (this.championships[sport] || []) : this.championships;
}
updater() {
if (!this.intervalId) {
this.intervalId = setInterval(this.updateSoccerCalendar.bind(this), UPDATE_INTERVAL);
}
}
async getSoccerMatchesByCompetition(competitionId) {
return await this.footballApi.get(`/v4/competitions/${competitionId}/matches?status=SCHEDULED`).then(({ data }) => data);
}
getFeedNameByMatches(championship, matchObj) {
if (!abbreviations.soccer[matchObj.homeTeam.id] || !abbreviations.soccer[matchObj.awayTeam.id] || !matchObj.utcDate) return null;
const homeTeam = abbreviations.soccer[matchObj.homeTeam.id].abbreviation;
const awayTeam = abbreviations.soccer[matchObj.awayTeam.id].abbreviation;
return `${championship}_${homeTeam}_${awayTeam}_${moment.utc(matchObj.utcDate).format("YYYY-MM-DD")}`
}
getChampionshipBySoccerCompetitionId(competitionId) {
if (competitionId === 2000) return 'WC';
if (competitionId === 2001) return 'CL';
if (competitionId === 2002) return 'BL1';
if (competitionId === 2003) return 'DED';
if (competitionId === 2013) return 'BSA';
if (competitionId === 2014) return 'PD';
if (competitionId === 2015) return 'FL1';
if (competitionId === 2016) return 'ELC';
if (competitionId === 2017) return 'PPL';
if (competitionId === 2019) return 'SA';
if (competitionId === 2021) return 'PL';
if (competitionId === 2044) return 'CSL';
if (competitionId === 2029) return 'BSB';
if (competitionId === 2024) return 'ASL';
if (competitionId === 2152) return 'CLI';
if (competitionId === 2018) return 'EC';
return null;
}
async getSoccerCalendar() {
let newData = [];
const odds = {};
const competitionsGetter = soccerCompetitions.map((id) => this.getSoccerMatchesByCompetition(id).then((data = {}) => {
const { competition, matches } = data;
const championship = this.getChampionshipBySoccerCompetitionId(id);
matches.forEach(matchObject => {
const feed_name = this.getFeedNameByMatches(championship, matchObject);
if (!conf.sportOracleAddress) {
console.error('no sport oracle', conf.sportOracleAddress);
}
const oddsObj = matchObject.odds;
if (feed_name) {
newData.push({
feed_name,
event_date: moment.utc(matchObject.utcDate).unix(),
expect_datafeed_value: abbreviations.soccer[matchObject.homeTeam.id].abbreviation,
yes_team: matchObject.homeTeam.name,
no_team: matchObject.awayTeam.name,
yes_team_id: matchObject.homeTeam.id,
no_team_id: matchObject.awayTeam.id,
oracle: conf.sportOracleAddress,
championship,
league_emblem: competition.emblem,
league: competition.name,
venue: matchObject.venue
});
odds[feed_name] = {
yes_odds: oddsObj ? oddsObj.homeWin : null,
no_odds: oddsObj ? oddsObj.awayWin : null,
draw_odds: oddsObj ? oddsObj.draw : null,
}
}
});
}));
await Promise.all(competitionsGetter);
return [newData, odds];
}
getChampionshipInfo(sport, championship) {
if (this.championships[sport]) {
const championshipInfo = this.championships[sport].find(({ code }) => code === championship);
return championshipInfo || {}
} else {
return {};
}
}
async getSoccerChampionshipsInfo() {
return await this.footballApi.get('/v4/competitions').then(({ data }) => data.competitions).then(async (competitions) => {
const crestsGetters = [];
competitions.map(({ code, id }) => {
crestsGetters.push(this.footballApi.get(`/v4/competitions/${id}/teams`).then(({ data }) => {
if (!this.crests.soccer[code]) this.crests.soccer[code] = {};
data?.teams.map(({ id, crest }) => {
this.crests.soccer[code][id] = crest;
})
}));
});
await Promise.all(crestsGetters);
return competitions;
}).catch((error) => {
console.error(error);
return [];
});
}
async updateSoccerCalendar() {
try {
const existingSportMarkets = await marketDB.api.getAllMarkets({ oracles: [conf.sportOracleAddress] });
const feedNamesOfExistingSportMarkets = existingSportMarkets.map(({ feed_name }) => feed_name);
const [soccerCalendar, odds] = await this.getSoccerCalendar();
const existCompetitions = feedNamesOfExistingSportMarkets.map((feed_name) => feed_name.split("_")[0]);
this.calendar.soccer = soccerCalendar.filter(({ feed_name }) => !feedNamesOfExistingSportMarkets.includes(feed_name)).sort((a, b) => a.event_date - b.event_date);
this.calendar.soccer.forEach(({ feed_name }) => existCompetitions.push(feed_name.split("_")[0]));
const soccerChampionships = uniq(existCompetitions);
const championshipsInfo = await this.getSoccerChampionshipsInfo();
this.calendar.soccer.forEach(({ yes_team_id, no_team_id, championship }, index) => {
this.calendar.soccer[index].yes_crest_url = this.getCrest('soccer', championship, yes_team_id);
this.calendar.soccer[index].no_crest_url = this.getCrest('soccer', championship, no_team_id);
});
if (!isEmpty(championshipsInfo)) {
this.championships.soccer = soccerChampionships.map((leagueName) => {
const info = championshipsInfo.find(({ code }) => code === leagueName) || {};
return ({
code: leagueName,
name: info.name || null,
emblem: info.emblem || null
})
})
}
this.odds.soccer = odds;
const now = moment.utc().unix();
const marketsWaitingForOddsUpdate = existingSportMarkets.filter(({ event_date, feed_name }) => (event_date > now) && (feed_name in odds));
const updatedOddsData = {};
marketsWaitingForOddsUpdate.forEach(({ feed_name }) => {
updatedOddsData[feed_name] = odds[feed_name];
});
marketDB.api.updateOdds(updatedOddsData);
} catch (err) {
console.error('update sportData error', err);
}
}
async init() {
await this.updateSoccerCalendar();
if (!this.intervalId) this.updater();
}
}
exports.sportDataService = new SportDataService();