-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
295 lines (263 loc) 路 8.22 KB
/
Copy pathapp.js
File metadata and controls
295 lines (263 loc) 路 8.22 KB
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
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const process = require('process'); // Required to mock environment variables
// [START gae_storage_app]
const { format } = require('util');
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');
const vision = require('@google-cloud/vision');
const httpClient = require('https');
// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const { Storage } = require('@google-cloud/storage');
// Instantiate a storage client
const storage = new Storage();
const app = express();
app.set('view engine', 'pug');
app.use(bodyParser.json());
// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize: 10 * 1024 * 1024, // no larger than 10mb, you can change as needed.
},
});
const teamNameMap = {
"NJD": 1,
"NYI": 2,
"NYR": 3,
"PHI": 4,
"PIT": 5,
"BOS": 6,
"BUF": 7,
"MTL": 8,
"OTT": 9,
"TOR": 10,
"CAR": 12,
"FLA": 13,
"TBL": 14,
"WSH": 15,
"CHI": 16,
"DET": 17,
"NSH": 18,
"STL": 19,
"CGY": 20,
"COL": 21,
"EDM": 22,
"VAN": 23,
"ANA": 24,
"DAL": 25,
"LAK": 26,
"SJS": 28,
"CBJ": 29,
"MIN": 30,
"WPG": 52,
"ARI": 53,
"VGK": 54,
};
const longToShortMap = {
"New Jersey Devils": "NJD",
"New York Islanders": "NYI",
"New York Rangers": "NYR",
"Philadelphia Flyers": "PHI",
"Pittsburgh Penguins": "PIT",
"Boston Bruins": "BOS",
"Buffalo Sabres": "BUF",
"Montr茅al Canadiens": "MTL",
"Ottawa Senators": "OTT",
"Toronto Maple Leafs": "TOR",
"Carolina Hurricanes": "CAR",
"Florida Panthers": "FLA",
"Tampa Bay Lightning": "TBL",
"Washington Capitals": "WSH",
"Chicago Blackhawks": "CHI",
"Detroit Red Wings": "DET",
"Nashville Predators": "NSH",
"St. Louis Blues": "STL",
"Calgary Flames": "CGY",
"Colorado Avalanche": "COL",
"Edmonton Oilers": "EDM",
"Vancouver Canucks": "VAN",
"Anaheim Ducks": "ANA",
"Dallas Stars": "DAL",
"Los Angeles Kings": "LAK",
"San Jose Sharks": "SJS",
"Columbus Blue Jackets": "CBJ",
"Minnesota Wild": "MIN",
"Winnipeg Jets": "WPG",
"Arizona Coyotes": "ARI",
"Vegas Golden Knights": "VGK",
};
// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);
// Display a form for uploading files.
app.get('/', (req, res) => {
res.render('form.pug');
});
app.get('/game', async (req, res) => {
let gameId = req.query.gameId;
res.status(200).json(await getGameStats(gameId));
});
// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
if (!req.file) {
res.status(400).send('No file uploaded.');
return;
}
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.file.originalname);
const blobStream = blob.createWriteStream({
resumable: false,
});
blobStream.on('error', err => {
next(err);
});
blobStream.on('finish', async () => {
// The public URL can be used to directly access the file via HTTP.
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
);
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
const [result] = await client.textDetection(publicUrl);
const detections = result.textAnnotations;
console.log(detections);
let teamIds;
if (detections.length > 0) {
teamIds = await getTeamIdsFromText(detections[0].description);
} else {
res.status(404).send({ error: "No text in image" });
}
res.status(200).json(teamIds);
});
blobStream.end(req.file.buffer);
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END gae_storage_app]
module.exports = app;
const getTeamIdsFromText = async (description) => {
let words = description.split(/[\s\n]+/);
console.log(words);
let teams = [];
words.forEach((word) => {
if (teamNameMap.hasOwnProperty(word)) {
teams.push(teamNameMap[word]);
};
});
if (teams.length === 0) return {};
return await getCurrentGame(teams[0]);
// return teams;
};
async function getCurrentGame(teamID) {
return new Promise((resolve, reject) => {
let requestURL = "https://statsapi.web.nhl.com/api/v1/teams/" + teamID + "?expand=team.schedule.next&&expand=team.schedule.previous";
httpClient.get(requestURL, (res) => {
let body = "";
res.on('data', (chunk) => {
body += chunk;
})
res.on('end', async () => {
try {
let json = JSON.parse(body);
let gameId;
let nextGame = (json['teams'][0]['nextGameSchedule']['dates'][0]['games'][0]);
if (nextGame['status']['abstractGameState'] == "Live") {
gameId = nextGame['gamePk'];
} else {
let prevGame = (json['teams'][0]['previousGameSchedule']['dates'][0]['games'][0]);
gameId = prevGame['gamePk'];
}
console.log(gameId);
let retVal = await getGameStats(gameId);
return resolve(retVal);
}
catch (err) {
console.log(err);
reject(err);
}
})
});
});
}
async function getGameStats(gameID) {
return new Promise((resolve, reject) => {
let requestURL = "https://statsapi.web.nhl.com/api/v1/game/" + gameID + "/boxscore";
httpClient.get(requestURL, (res) => {
let body = "";
res.on('data', (chunk) => {
body += chunk;
})
res.on('end', () => {
try {
let json = JSON.parse(body);
console.log(json);
return resolve(formatJson(json, gameID));
}
catch (err) {
console.log(err);
reject(err);
}
})
});
});
}
function formatJson(json, gameId) {
let obj = {
"gameId": gameId.toString(),
"home": {
"name": "",
"abbreviation": "",
"onIce": [], //fullName, number, positionCode
"goals": "",
},
"away": {
"name": "",
"abbreviation": "",
"onIce": [],
"goals": "",
}
};
obj['home']['name'] = json['teams']['home']['team']['name'];
obj['away']['name'] = json['teams']['away']['team']['name'];
obj['home']['onIce'] = json['teams']['home']['onIce'].map((playerId) => {
let player = json['teams']['home']['players']['ID' + playerId]['person'];
let fullName = player['fullName'];
let number = player['primaryNumber'];
let positionCode = player['primaryPosition']['code'];
return { fullName, number, positionCode };
});
obj['away']['onIce'] = json['teams']['away']['onIce'].map((playerId) => {
let player = json['teams']['away']['players']['ID' + playerId]['person'];
let fullName = player['fullName'];
let number = player['primaryNumber'];
let positionCode = player['primaryPosition']['code'];
return { fullName, number, positionCode };
});
obj['home']['goals'] = json['teams']['home']['teamStats']['teamSkaterStats']['goals'];
obj['away']['goals'] = json['teams']['away']['teamStats']['teamSkaterStats']['goals'];
obj['home']['abbreviation'] = longToShortMap[obj['home']['name']];
obj['away']['abbreviation'] = longToShortMap[obj['away']['name']];
return obj;
}