forked from jclarke0000/MMM-MyScoreboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SNET.js
434 lines (347 loc) · 12.1 KB
/
SNET.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
-------------------------------------
Provider for Sportsnet Scoreboard
-------------------------------------
Provides scores for
NHL (National Hockey League)
NFL (National Football League)
NBA (National Basketball Association)
CFL (Canadian Football League)
MLS (Major League Soccer)
MLB (Major League Baseball)
All sports are provided in a single feed at
https://mobile-statsv2.sportsnet.ca/ticker
The feed takes one parameter:
day - YYYY-MM-DD (e.g. 2018-11-20)
It's also possible to request individual leagues with the
"league" parameter, but for some sports, more than one day's
worth of games are returned (e.g. CFL, NFL). This becomes
tricky when time zones come into effect, since the date stamps
are provided in UTC, and would report the next day's
games for anything 7:00 PM ET or later. It was easier
to continue to use the independent poll that was used with the
old feed.
Sportsnet's Scoreboard feed is free and clear, so please
do not modify this to hammer the API with a flood of calls.
Doing so may trigger Sportsnet to lock down the API.
Since this feed gets all the sports at once, the data
feed works independent of the front end's poll for
score updates. Polling for scores is kicked off the
first time the front end asks for data, but after that,
this module will keep a local data object up to date.
Subsequent requests from the front end will be queried
against this data object.
*/
const request = require("request");
const moment = require("moment-timezone");
const parseJSON = require("json-parse-async");
module.exports = {
PROVIDER_NAME: "SNET",
/*
Please don't make this any more frequent. If you have a
browser open to Sportsnet.ca, this feed gets pinged every
10 seconds. Keeping ours to every minute should keep us
under the radar, but will still give us timely information.
In any case, the front end asks for data every 2 minutes,
so making this any more frequent doesn't change anything.
*/
POLL_FREQUENCY: 60 * 1000, //every 30 seconds.
scoresObj: null,
dataPollStarted: false,
gameDate: null,
getScores: function(league, teams, gameDate, callback) {
var self = this;
this.gameDate = moment(gameDate);
if (this.scoresObj == null) {
//start the data poll. Set a timer to check every second to see if the scoresObj gets populated.
if (!this.dataPollStarted) {
this.startDataPoll();
}
var waitForDataTimer = setInterval(function() {
if (self.scoresObj != null) {
clearInterval(waitForDataTimer);
waitForDataTimer = null;
callback(self.getLeague(league, teams));
}
}, 1000);
} else {
callback(self.getLeague(league, teams));
}
},
startDataPoll: function() {
this.dataPollStarted = true;
this.getData();
var self = this;
setInterval(function() {
self.getData();
}, this.POLL_FREQUENCY);
},
getData: function() {
// console.log("Get SNET JSON");
var self = this;
var url = "https://mobile-statsv2.sportsnet.ca/ticker?day=" + this.gameDate.format("YYYY-MM-DD");
request({url: url, method: "GET"}, function(r_err, response, body) {
if(!r_err && response.statusCode == 200) {
parseJSON(body, function(p_err, content) {
if (p_err) {
console.log( "[MMM-MyScoreboard] " + moment().format("D-MMM-YY HH:mm") + " ** ERROR ** Couldn't parse data for provider SNET: " + p_err );
} else if (content.data) {
self.scoresObj = content;
}
});
} else {
console.log( "[MMM-MyScoreboard] " + moment().format("D-MMM-YY HH:mm") + " ** ERROR ** Couldn't retrieve data for provider SNET: " + r_err );
}
});
},
getLeague: function(league, teams) {
var self = this;
var filteredGames = this.scoresObj.data.games.filter(function(game) {
return(game.league.toUpperCase() == league.toUpperCase() &&
(teams == null || teams.indexOf(game.home_team.short_name.toUpperCase()) != -1 ||
teams.indexOf(game.visiting_team.short_name.toUpperCase()) != -1) );
});
/*
now sort the array by start time so that the games always appear
in the same order regardless of status. Sort it first by start
time, then by visting team short code.
*/
filteredGames.sort(function(a,b) {
var aTime = moment(a.timestamp * 1000);
var bTime = moment(b.timestamp * 1000);
//first sort by start time
if (aTime.isBefore(bTime)) {
return -1;
}
if (aTime.isAfter(bTime)) {
return 1;
}
//start times are the same. Now sort by team short codes
if (a.visiting_team.short_name < b.visiting_team.short_name) {
return -1;
}
if (a.visiting_team.short_name > b.visiting_team.short_name) {
return 1;
}
return 0;
});
var formattedGames = [];
var localTZ = moment.tz.guess();
filteredGames.forEach(function(game) {
var gameState;
var status = [];
var classes = [];
switch(game.game_status) {
case "Pre-Game":
gameState = 0; //not started
//Feed provides all game times in Eastern Time
status.push(moment(game.timestamp * 1000).tz(localTZ).format("h:mm a"));
break;
case "In-Progress":
gameState = 1; //in-progress
/*
You'd think that since Sportsnet's feed returns all
sports at once that we could handle every sport the
same way. Alas, there are too many small differences
between the sports, even though they don't need to
be there. So it's easier to handle each league
piecemeal instead of having a sea of IF...THEN blocks.
*/
switch (league) {
case "NHL":
/*
We can use game.period_status to handle a
couple of special cases. Otherwise we
display game.clock and feed game.period
into the getPeriod() routine.
*/
if (game.shootout == true) {
status.push("SHOOTOUT");
} else if (game.overtime == true) {
status.push(game.clock);
status.push("OT");
} else if (game.clock == "0:00") {
status.push("END");
status.push(self.getPeriod(league, game.period));
} else {
status.push(game.clock);
status.push(self.getPeriod(league, game.period));
}
break;
case "MLB":
/*
game.period_status property will say "TOP 1st"
or "BOT 3rd" etc. Break out "TOP" or "BOT", and
then feed game.period into the getPeriod() routine
to format ordinals with the <sup> wrapper.
*/
status.push(game.period_status && game.period_status.split(" ")[0]);
status.push(self.getPeriod(league, game.period));
break;
case "MLS":
if (game.clock == "Half") {
status.push("HALFTIME");
} else {
status.push(game.clock);
}
break;
case "NFL":
case "CFL":
case "NBA":
/*
Sigh. You'd think Sportnet would reuse the
"Half-Over" array for games at halftime. But
for some weird reason it only uses it for
soccer. Also, the feed doesn't provide a
period-status property, so we need to rely
on the clock and period properties to build
the status.
Luckily, NFL, CFL, and NBA can all be handled
the same way. No need to break them out into
their own special cases.
*/
if (game.clock == "0:00" && game.period == 2) {
status.push("HALFTIME");
} else if (game.clock == "0:00") {
status.push("END");
status.push(self.getPeriod(league, game.period));
} else {
status.push(game.clock);
status.push(self.getPeriod(league, game.period));
}
break;
}
break;
case "Half-Over":
gameState = 1; //in-progress
status.push("HALFTIME");
break;
case "Delayed":
gameState = 1; //in-progress
classes.push("delay");
status.push("Delay");
break;
case "Postponed":
gameState = 0;
status.push("Postponed");
break;
case "Final":
gameState = 2; //final
status.push("Final" + self.getFinalOT(league, game));
break;
default:
gameState = 0;
status.push(moment(game.timestamp * 1000).tz(localTZ).format("h:mm a"));
break;
}
/*
URLs to logo images are available in the feed, but they are a bit too low
quaity for some of the templates. However, logos are available at higher
resolution if we replace "59x59" with "200x200" in the path.
*/
var formattedGame = {
classes: classes,
gameMode: gameState,
hTeam: game.home_team.short_name.toUpperCase(),
vTeam: game.visiting_team.short_name.toUpperCase(),
hTeamLong: game.home_team.short_name == "TBD" ? "TBD" : self.titleCase(game.home_team.name),
vTeamLong: game.visiting_team.short_name == "TBD" ? "TBD" : self.titleCase(game.visiting_team.name),
hScore: game.home_team.score,
vScore: game.visiting_team.score,
status: status
};
formattedGames.push(formattedGame);
});
return formattedGames;
},
getFinalOT: function(league, game) {
switch (league) {
case "NHL":
if (game.shootout == true) {
return " (SO)";
} else if (game.overtime == true) {
return " (OT)";
} else if (game.period == 4) {
return " (OT)";
} else if (game.period > 4) {
return " (" + (game.period - 3) + "OT)";
}
break;
case "MLB":
if (game.period > 9) {
return " (" + game.period + ")";
}
break;
case "NFL":
case "CFL":
case "NBA":
if (game.period > 4) {
return " (OT)";
}
break;
case "MLS":
if (game.period > 2) {
return " (ET)";
}
break;
}
return "";
},
getOrdinal: function(p) {
var mod10 = p % 10;
var mod100 = p % 100;
if (mod10 == 1 && mod100 != 11) {
return p + "<sup>ST</sup>";
}
if (mod10 == 2 && mod100 != 12) {
return p + "<sup>ND</sup>";
}
if (mod10 == 3 && mod100 != 13) {
return p + "<sup>RD</sup>";
}
return p + "<sup>TH</sup>";
},
getPeriod: function(league, p) {
//check for overtime, otherwise return ordinal
switch (league) {
case "NFL":
case "NBA":
case "CFL":
if (p == 5) {
return ("OT");
} else if (p > 5) {
return (p - 4) + "OT";
}
break;
case "NHL":
if (p == 4) {
return ("OT");
} else if (p > 4) {
return (p - 3) + "OT";
}
break;
case "MLS" :
if (p > 2) {
return ("ET");
}
break;
}
return this.getOrdinal(p);
},
titleCase: function(str) {
if (str == null || str == undefined) {
return "";
}
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
// two-letter portions are all upper case (e.g.: the "FC" in Toronto FC)
if (splitStr[i].length <= 2) {
splitStr[i] = splitStr[i].toUpperCase();
} else {
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
}
// Directly return the joined string
return splitStr.join(" ");
}
};