skins.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 userId = (req.url.path_list[2] || "").split(".")[0];
  10. var def = req.url.query.default;
  11. var etag = null;
  12. var rid = req.id;
  13. if (!helpers.id_valid(userId)) {
  14. res.writeHead(422, {
  15. "Content-Type": "text/plain",
  16. "Response-Time": new Date() - start
  17. });
  18. res.end("Invalid ID");
  19. return;
  20. }
  21. // strip dashes
  22. userId = userId.replace(/-/g, "");
  23. logging.log(rid + "userid: " + userId);
  24. try {
  25. helpers.get_skin(rid, userId, function(err, hash, image) {
  26. if (err) {
  27. logging.error(rid + 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(rid + "etag: " + req.headers["if-none-match"]);
  39. logging.debug(rid + "matches: " + matches);
  40. sendimage(rid, http_status, image);
  41. } else {
  42. handle_default(rid, 404, userId);
  43. }
  44. });
  45. } catch(e) {
  46. logging.error(rid + "error: " + e.stack);
  47. handle_default(rid, 500, userId);
  48. }
  49. function handle_default(rid, http_status, userId) {
  50. if (def && def !== "steve" && def !== "alex") {
  51. logging.log(rid + "status: 301");
  52. res.writeHead(301, {
  53. "Cache-Control": "max-age=" + config.browser_cache_time + ", public",
  54. "Response-Time": new Date() - start,
  55. "X-Storage-Type": "downloaded",
  56. "X-Request-ID": rid,
  57. "Access-Control-Allow-Origin": "*",
  58. "Location": def
  59. });
  60. res.end();
  61. } else {
  62. def = def || skins.default_skin(userId);
  63. lwip.open("public/images/" + def + "_skin.png", function(err, image) {
  64. image.toBuffer("png", function(err, buffer) {
  65. sendimage(rid, http_status, buffer);
  66. });
  67. });
  68. }
  69. }
  70. function sendimage(rid, http_status, image) {
  71. logging.log(rid + "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. "X-Request-ID": rid,
  78. "Access-Control-Allow-Origin": "*",
  79. "Etag": '"' + etag + '"'
  80. });
  81. res.end(http_status === 304 ? null : image);
  82. }
  83. };