skins.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.path_list[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. sendimage(http_status, image);
  41. } else {
  42. handle_default(404);
  43. }
  44. });
  45. } catch(e) {
  46. logging.error(uuid + " error:");
  47. logging.error(e);
  48. handle_default(500);
  49. }
  50. function handle_default(http_status) {
  51. if (def && def != "steve" && def != "alex") {
  52. logging.log("status: 301");
  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. logging.log("status: " + http_status);
  72. res.writeHead(http_status, {
  73. "Content-Type": "image/png",
  74. "Cache-Control": "max-age=" + config.browser_cache_time + ", public",
  75. "Response-Time": new Date() - start,
  76. "X-Storage-Type": "downloaded",
  77. "Access-Control-Allow-Origin": "*",
  78. "Etag": '"' + etag + '"'
  79. });
  80. res.end(http_status == 304 ? null : image);
  81. }
  82. };