skins.js 2.5 KB

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