capes.js 2.1 KB

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