skins.js 2.6 KB

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