capes.js 2.5 KB

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