forked from SkyCryptWebsite/SkyCrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtexture.js
More file actions
73 lines (58 loc) · 1.59 KB
/
Copy pathtexture.js
File metadata and controls
73 lines (58 loc) · 1.59 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
import axios from "axios";
import cors from "cors";
import express from "express";
import fs from "fs-extra";
import * as app from "../app.js";
import * as helper from "../helper.js";
const router = express.Router();
router.use(cors());
router.all("/:textureId", cors(), async (req, res, next) => {
try {
const { textureId } = req.params;
if (!/^[0-9a-fA-F]+$/.test(textureId)) {
handleError(res, new Error("invalid texture id: " + textureId), 400);
return;
}
const texture = getTexture(textureId);
if (!texture) {
handleError(res, new Error("texture not found"), 404);
return;
}
res.set("X-Cluster-ID", `${helper.getClusterId()}`);
res.setHeader("Cache-Control", `public, max-age=${app.MAX_MAX_AGE}`);
res.contentType("image/png");
res.send(texture);
} catch (e) {
next(e);
}
});
async function getTexture(textureId) {
const filePath = helper.getCacheFilePath(app.CACHE_PATH, "texture", textureId);
let file;
try {
file = await fs.readFile(filePath);
} catch (e) {
try {
file = (await axios.get(`https://textures.minecraft.net/texture/${textureId}`, { responseType: "arraybuffer" }))
.data;
fs.writeFile(filePath, file, (err) => {
if (err) {
console.error(err);
}
});
} catch (e) {
return null;
}
}
return file;
}
router.use((err, req, res, next) => {
handleError(res, err);
});
export function handleError(res, err, status = 500, logged = true) {
if (logged) {
console.error(err);
}
res.status(status).send(err.message);
}
export { router };