capes.js 2.4 KB

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