capes.js 2.4 KB

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