-
Notifications
You must be signed in to change notification settings - Fork 10
/
api.php
executable file
·352 lines (290 loc) · 11.1 KB
/
api.php
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
<?php
require_once("config.php");
require_once("src/autoload.php");
require_once("vendor/autoload.php");
use BlueHerons\StatTracker\Agent;
use BlueHerons\StatTracker\OCR;
use BlueHerons\StatTracker\StatTracker;
use Curl\Curl;
use Endroid\QrCode\QrCode;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
$StatTracker = new StatTracker();
// Assert that token and stat parameters, if present, match expected format
$validateRequest = function(Request $request, Silex\Application $StatTracker) {
function validateParameter($param, $regex) {
if (strlen($param) > 0) {
return preg_match($regex, $param) === 1;
}
else {
return true;
}
}
// Ensure {token} is 64 hexidecimal digits
if (!validateParameter($request->get("token"), "/^[a-f0-9]{64}$/i")) { return $StatTracker->abort(400); }
// Ensure {stat} is alpha characters and an underscore
if (!validateParameter($request->get("stat"), "/^[a-z_]+$/")) { return $StatTracker->abort(400); }
};
$StatTracker->after(function (Request $request, Response $response) {
$response->headers->set("Access-Control-Allow-Origin", "*");
});
$StatTracker->get("/api/team/profile", function() use ($StatTracker) {
$data = $StatTracker->getTeamStats();
return $StatTracker->json($data, 200, array(
"Cache-Control" => "max-age=86400, public"
));
});
$StatTracker->get("/api/{token}/profile/{when}.{format}", function($token, $when, $format) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
$response = new stdClass;
$response->agent = $agent->name;
$t = new stdClass;
if ($StatTracker->isValidDate($when)) {
$ts = $agent->getUpdateTimestamp($when, true);
if ($ts == null) {
return $StatTracker->abort(403);
}
else {
$response->date = date("c", $ts);
$response->badges = $agent->getBadges($when, true);
$response->stats = $agent->getStats($when, true);
}
}
else if ($when == "latest") {
$response->date = date("c", $agent->getUpdateTimestamp());
$response->badges = $agent->getBadges();
$response->stats = $agent->getStats("latest", true);
}
else {
return $StatTracker->abort(403);
}
switch ($format) {
case "json":
return $StatTracker->json($response);
break;
}
})->before($validateRequest)
->assert("format", "json")
->assert("when", "latest|[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")
->value ("format", "json")
->value ("when", "latest");
// Retrieve basic information about the agent
$StatTracker->get("/api/{token}", function($token) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
return $StatTracker->json($agent);
})->before($validateRequest);
$StatTracker->match("/api/{token}/token", function(Request $request, $token) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
switch ($request->getMethod()) {
case "GET":
$name = strtoupper(substr(str_shuffle(md5(time() . $token . rand())), 0, 6));
$token = $agent->createToken($name);
$url = sprintf("%s://%s", $request->getScheme(), $request->getHost());
$url = $url . $request->getBaseUrl() . "/";
$uri = "stattracker://token?token=%s&name=%s&agent=%s&issuer=%s";
$uri = sprintf($uri, $token, $name, $agent->name, urlencode($url));
$qr = new QRCode();
$qr->setText($uri)
->setSize(200)
->setPadding(10);
if ($token === false) {
return new Response(null, 202);
}
else {
$data = array(
"name" => $name,
"token" => $token,
"qr" => $qr->getDataUri(),
"uri" => $uri
);
return $StatTracker->json($data);
}
break;
case "DELETE":
if (!$request->request->has("name")) {
return $StatTracker->abort(400);
}
$name = strtoupper($request->request->get("name"));
$r = $agent->revokeToken($name);
if ($r === true) {
return new Response(null, 200);
}
else {
return new Response(null, 401);
}
break;
}
})->method("GET|DELETE");
// Retrieve badge information for the agent
$StatTracker->get("/api/{token}/badges/{what}", function(Request $request, $token, $what) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
$limit = is_numeric($request->query->get("limit")) ? (int)$request->query->get("limit") : 4;
if (preg_match("/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/", $what)) {
$data = $agent->getBadges($what);
}
else if ($what == "upcoming") {
$data = $agent->getUpcomingBadges($limit);
}
else {
$data = $agent->getBadges();
}
return $StatTracker->json($data);
})->before($validateRequest)
->assert("what", "today|upcoming|[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")
->value("what", "today");
$StatTracker->get("/api/{token}/distribution/{stat1}/{stat2}/{factor}", function($token, $stat1, $stat2, $factor) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
$data = $StatTracker->getDistribution($stat1, $stat2, $factor);
$response = JsonResponse::create();
$response->setEncodingOptions($response->getEncodingOptions() | JSON_NUMERIC_CHECK);
$response->setData($data);
return $response;
})->before($validateRequest);
// Retrieve ratio information for the agent
$StatTracker->get("/api/{token}/ratios", function($token) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
$data = $agent->getRatios();
return $StatTracker->json($data);
})->before($validateRequest);
// Retrieve raw or compiled data for a single stat for the agent
$StatTracker->get("/api/{token}/{stat}/{view}/{when}.{format}", function($token, $stat, $view, $when, $format) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
else if (!$StatTracker->isValidStat($stat)) {
return $StatTracker->abort(404);
}
$data = "";
switch ($view) {
case "breakdown":
$when = filter_var($when, FILTER_SANITIZE_NUMBER_INT);
$when = is_numeric($when) ? $when : 0;
$data = $agent->getAPBreakdown($when);
break;
case "leaderboard":
$data = $StatTracker->getLeaderboard($stat, $when);
break;
case "prediction":
$data = $agent->getPrediction($stat);
break;
case "trend":
$data = $agent->getTrend($stat, $when);
break;
case "graph":
$data = $agent->getGraphData($stat);
break;
case "raw":
$agent->getStat($stat);
$data = new stdClass();
$data->value = $agent->stats[$stat];
$data->timestamp = $agent->getUpdateTimestamp();
break;
}
$response = JsonResponse::create();
$response->setEncodingOptions($response->getEncodingOptions() | JSON_NUMERIC_CHECK);
$response->setData($data);
return $response;
})->before($validateRequest)
->assert("view", "breakdown|leaderboard|prediction|trend|graph")
->value("stat", "ap")
->value("view", "raw")
->value("when", "most-recent")
->value("format", "json");
// Allow agents to submit stats
$StatTracker->post("/api/{token}/submit", function(Request $request, $token) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
// Filter out keys that do not represent stats
$data = array_intersect_key($_POST, array_merge(StatTracker::getStats(), array("date"=>"")));
$response = new stdClass();
$response->error = false;
$allow_lower_values = filter_var($request->query->get("allow_lower_values", false), FILTER_VALIDATE_BOOLEAN);
try {
$result = $agent->updateStats($data, $allow_lower_values);
if ($result === true) {
$response->message = sprintf("Your stats for %s have been received.", date("l, F j", strtotime($data['date'])));
if (!$agent->hasSubmitted()) {
$response->message .= " Since this was your first submission, predictions are not available. Submit again tomorrow to see your predictions.";
}
$StatTracker['session']->set("agent", Agent::lookupAgentByToken($token));
}
else {
$response->error = true;
$response->message = $result;
}
}
catch (Exception $e) {
$response->error = true;
$response->message = $e->getMessage();
}
return $StatTracker->json($response);
})->before($validateRequest);
$StatTracker->post("/api/{token}/ocr", function(Request $request, $token) use ($StatTracker) {
$agent = Agent::lookupAgentByToken($token);
if (!$agent->isValid()) {
return $StatTracker->abort(403);
}
$content_type = explode(";", $request->headers->get("content_type"))[0];
$file = UPLOAD_DIR . uniqid("ocr_") . ".png";
switch ($content_type) {
case "application/x-www-form-urlencoded":
// Not a file upload, but a POST of bytes
$hndl = fopen($file, "w+");
fwrite($hndl, file_get_contents("php://input"));
fclose($hndl);
break;
case "multipart/form-data":
// Typically an HTTP file upload
if ($_FILES['screenshot']['error'] !== 0) {
$response = $StatTracker->json(array(
"error" => $StatTracker->getFileUploadError($_FILES['screenshot']['error'])
));
// Need to append two newlines
$response->setContent($response->getContent() . PHP_EOL . PHP_EOL);
return $response;
}
else {
move_uploaded_file($_FILES['screenshot']['tmp_name'], $file);
}
break;
default:
return $StatTracker->abort(400, "Bad request " . $content_type);
break;
}
$processImageAsync = function() use ($StatTracker, $file) {
// This method will print the results to the output stream
$StatTracker->scanProfileScreenshot($file, true);
};
if (filter_var($request->query->get("async", true), FILTER_VALIDATE_BOOLEAN)) {
return $StatTracker->stream($processImageAsync, 200, array ("Content-type" => "application/octet-stream"));
}
else {
return $StatTracker->json(array("stats" => $StatTracker->scanProfileScreenshot($file, false)));
}
})->before($validateRequest);
$StatTracker->after(function (Request $request, Response $response) {
$response->headers->set("Cache-control", "max-age=". (60 * 60 * 6) .", private");
$response->headers->set("Expires", date("D, d M Y H:i:s e", time() + 60 * 60 * 6));
});
$StatTracker->run();
?>