skins.js 2.5 KB

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