-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
202 lines (154 loc) · 5.07 KB
/
app.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
const express = require("express");
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", express.static(__dirname + "/front"));
app.get("/", function(_, res) {
res.sendFile(path.join(__dirname, "/index.html"));
});
app.use((_, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Hold cached responses from zplwii.xyz/api/groups
const groupResponses = [];
// Holds the b64 img data
const responseByFc = {};
const base64toBlob = function(data) {
const bytes = atob(data);
let length = bytes.length;
let out = new Uint8Array(length);
while (length--) {
out[length] = bytes.charCodeAt(length);
}
return new Blob([out]);
};
async function fetchImgAsBase64(url) {
try {
const response = await fetch(url);
if (!response.ok)
return null;
return btoa(String.fromCharCode(...new Uint8Array(await response.arrayBuffer())));
}
catch {
return null;
}
}
async function getMii(miiSpec) {
const fc = miiSpec[0];
const data = miiSpec[1];
const formData = new FormData;
formData.append("data", base64toBlob(data), "mii.dat");
formData.append("platform", "wii");
try {
// fc is used to cache responses on the server
const response = await fetch("https://miicontestp.wii.rc24.xyz/cgi-bin/studio.cgi", {
method: "POST",
body: formData,
});
if (!response.ok) {
console.error("Bad response from qrcode.rc24.xyz, status code: " + response.status);
return [fc, null];
}
const json = await response.json();
if (!json || !json.mii) {
console.error("Malformed JSON response from qrcode.rc24.xyz");
return [fc, null];
}
const miiImageUrl = `https://studio.mii.nintendo.com/miis/image.png?data=${json.mii}&type=face&expression=normal&width=270&bgColor=FFFFFF00&clothesColor=default&cameraXRotate=0&cameraYRotate=0&cameraZRotate=0&characterXRotate=0&characterYRotate=0&characterZRotate=0&lightDirectionMode=none&instanceCount=1&instanceRotationMode=model`;
const b64 = await fetchImgAsBase64(miiImageUrl);
responseByFc[fc] = b64;
return [fc, b64];
}
catch (e) {
console.log("Unable to get mii, error: " + e);
return [fc, null];
}
}
app.post("/qrcoderc24", async function(req, res) {
if (!req.body || typeof (req.body) != "object") {
res.sendStatus(400);
return;
}
const resBody = {};
const reqsToMake = [];
for (const fc in req.body) {
if (!req.body.hasOwnProperty(fc))
continue;
const cached = responseByFc[fc];
if (cached) {
resBody[fc] = cached;
continue;
}
reqsToMake.push([fc, req.body[fc]]);
}
function procMiiResponse(miiRes) {
resBody[miiRes[0]] = miiRes[1];
}
if (reqsToMake.length != 0) {
const tasks = reqsToMake.map(getMii);
const resp = await Promise.all(tasks);
resp.forEach(procMiiResponse);
}
res.send(JSON.stringify(resBody));
});
app.get("/groups", function(req, res) {
var id = groupResponses[groupResponses.length - 1].id;
if (req.query.id) {
id = parseInt(req.query.id, 10);
if (req.query.id == "min")
id = groupResponses[0].id;
else if (id == NaN) {
res.sendStatus(400);
return;
}
}
const idx = id - groupResponses[0].id;
if (idx < 0 || idx > 60) {
res.status(400);
res.send(`Response does not exist for id ${id}, is your id too far back?`);
return;
}
const response = groupResponses[idx];
if (!response) {
res.status(404);
res.send(`Response does not exist for id ${id}, but it should. Is zplwii.xyz down or is it just not populated yet?`);
return;
}
// Minimum allowed id at a given time
response.minimum_id = groupResponses[0].id;
res.set({
["Cache-Control"]: "no-cache, no-store, must-revalidate",
["Expires"]: 0,
});
res.send(JSON.stringify(response));
});
var id = 0;
function updateCachedGroups(response) {
const len = groupResponses.push({ timestamp: Date.now(), rooms: response, id: id });
console.log(`Updated groups (${response != null ? "successfully" : "unsuccessfully"}): Time is ${new Date(Date.now())}, id is ${id}`);
id++;
if (len > 60)
groupResponses.shift();
}
async function updateGroups() {
try {
const response = await fetch("http://zplwii.xyz/api/groups");
var json = null;
if (!response.ok)
console.error("Failed to retrieve groups!");
else
json = await response.json();
updateCachedGroups(json);
}
catch (e) {
console.error(e);
updateCachedGroups(null);
}
}
// Once a minute
setInterval(updateGroups, 60000);
// Initial call
updateGroups();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));