skins.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var router = require("express").Router();
  2. var networking = require("../modules/networking");
  3. var logging = require("../modules/logging");
  4. var helpers = require("../modules/helpers");
  5. var config = require("../modules/config");
  6. var skins = require("../modules/skins");
  7. /* GET skin request. */
  8. router.get("/:uuid.:ext?", function(req, res) {
  9. var uuid = req.params.uuid;
  10. var def = req.query.default;
  11. var start = new Date();
  12. var etag = null;
  13. if (!helpers.uuid_valid(uuid)) {
  14. res.status(422).send("422 Invalid UUID");
  15. return;
  16. }
  17. // strip dashes
  18. uuid = uuid.replace(/-/g, "");
  19. try {
  20. helpers.get_skin(uuid, function(err, hash, image) {
  21. logging.log(uuid);
  22. if (err) {
  23. logging.error(err);
  24. }
  25. etag = hash && hash.substr(0, 32) || "none";
  26. var matches = req.get("If-None-Match") == "\"" + etag + "\"";
  27. if (image) {
  28. var http_status = 200;
  29. if (matches) {
  30. http_status = 304;
  31. } else if (err) {
  32. http_status = 503;
  33. }
  34. logging.log("matches: " + matches);
  35. logging.log("Etag: " + req.get("If-None-Match"));
  36. logging.log("status: " + http_status);
  37. sendimage(http_status, image);
  38. } else {
  39. handle_default(404);
  40. }
  41. });
  42. } catch(e) {
  43. logging.error("Error!");
  44. logging.error(e);
  45. handle_default(500);
  46. }
  47. function handle_default(http_status) {
  48. if (def && def != "steve" && def != "alex") {
  49. res.writeHead(301, {
  50. "Cache-Control": "max-age=" + config.browser_cache_time + ", public",
  51. "Response-Time": new Date() - start,
  52. "X-Storage-Type": "downloaded",
  53. "Access-Control-Allow-Origin": "*",
  54. "Location": def
  55. });
  56. res.end();
  57. } else {
  58. def = def || skins.default_skin(uuid);
  59. skins.resize_img("public/images/" + def + ".png", size, function(err, image) {
  60. sendimage(http_status, image);
  61. });
  62. }
  63. }
  64. function sendimage(http_status, image) {
  65. res.writeHead(http_status, {
  66. "Content-Type": "image/png",
  67. "Cache-Control": "max-age=" + config.browser_cache_time + ", public",
  68. "Response-Time": new Date() - start,
  69. "X-Storage-Type": "downloaded",
  70. "Access-Control-Allow-Origin": "*",
  71. "Etag": "\"" + etag + "\""
  72. });
  73. res.end(http_status == 304 ? null : image);
  74. }
  75. });
  76. module.exports = router;