Fix replacing images in presence data with splatoon3.ink links

This commit is contained in:
Samuel Elliott 2022-11-02 01:19:18 +00:00
parent 0e33825d27
commit d573cf4dd0
No known key found for this signature in database
GPG Key ID: 8420C7CDE43DC4D6
2 changed files with 14 additions and 4 deletions

View File

@ -231,6 +231,10 @@ class Server extends HttpServer {
this.handlePresenceStreamRequest(req, res, req.params.user)));
}
protected encodeJsonForResponse(data: unknown, space?: number) {
return JSON.stringify(data, replacer, space);
}
async handleAllUsersRequest(req: Request, res: Response) {
if (!this.allow_all_users) {
throw new ResponseError(403, 'forbidden');
@ -477,6 +481,7 @@ class Server extends HttpServer {
const result = await this.handlePresenceRequest(req, res, presence_user_nsaid);
const stream = new EventStreamResponse(req, res);
stream.json_replacer = replacer;
stream.sendEvent(null, 'debug: timestamp ' + new Date().toISOString());
@ -574,7 +579,7 @@ function createFestVoteTeam(
}
function replacer(key: string, value: any) {
if (key === 'image' || key.endsWith('Image') && value && typeof value === 'object' && 'url' in value) {
if ((key === 'image' || key.endsWith('Image')) && value && typeof value === 'object' && 'url' in value) {
return {
...value,
url: getSplatoon3inkUrl(value.url),

View File

@ -35,8 +35,11 @@ export class HttpServer {
protected sendJsonResponse(res: Response, data: {}, status?: number) {
if (status) res.statusCode = status;
res.setHeader('Content-Type', 'application/json');
res.end(res.req.headers['accept']?.match(/\/html\b/i) ?
JSON.stringify(data, null, 4) : JSON.stringify(data));
res.end(this.encodeJsonForResponse(data, res.req.headers['accept']?.match(/\/html\b/i) ? 4 : 0));
}
protected encodeJsonForResponse(data: unknown, space?: number) {
return JSON.stringify(data, null, space);
}
protected handleRequestError(req: Request, res: Response, err: unknown) {
@ -86,6 +89,8 @@ export class ResponseError extends Error {
}
export class EventStreamResponse {
json_replacer: ((key: string, value: unknown) => any) | null = null;
constructor(
readonly req: Request,
readonly res: Response,
@ -96,7 +101,7 @@ export class EventStreamResponse {
sendEvent(event: string | null, ...data: unknown[]) {
if (event) this.res.write('event: ' + event + '\n');
for (const d of data) this.res.write('data: ' + JSON.stringify(d) + '\n');
for (const d of data) this.res.write('data: ' + JSON.stringify(d, this.json_replacer ?? undefined) + '\n');
this.res.write('\n');
}
}