cache.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. var config = require("./config");
  2. var redis = null;
  3. var fs = require("fs");
  4. // sets up redis connection
  5. // flushes redis when running on heroku (files aren't kept between pushes)
  6. function connect_redis() {
  7. console.log("connecting to redis...");
  8. if (process.env.REDISCLOUD_URL) {
  9. var redisURL = require("url").parse(process.env.REDISCLOUD_URL);
  10. redis = require("redis").createClient(redisURL.port, redisURL.hostname);
  11. redis.auth(redisURL.auth.split(":")[1]);
  12. } else {
  13. redis = require("redis").createClient();
  14. }
  15. redis.on("ready", function() {
  16. console.log("Redis connection established.");
  17. if(process.env.HEROKU) {
  18. console.log("Running on heroku, flushing redis");
  19. redis.flushall();
  20. }
  21. });
  22. redis.on("error", function (err) {
  23. console.error(err);
  24. });
  25. redis.on("end", function () {
  26. console.warn("Redis connection lost!");
  27. });
  28. }
  29. // sets the date of the face file belonging to +hash+ to now
  30. // the helms file is ignored because we only need 1 file to read/write from
  31. function update_file_date(hash) {
  32. if (hash) {
  33. var path = config.faces_dir + hash + ".png";
  34. fs.exists(path, function(exists) {
  35. if (exists) {
  36. var date = new Date();
  37. fs.utimes(path, date, date, function(err){
  38. if (err) {
  39. console.error(err);
  40. }
  41. });
  42. } else {
  43. console.error("Tried to update " + path + " date, but it doesn't exist");
  44. }
  45. });
  46. }
  47. }
  48. var exp = {};
  49. exp.get_redis = function() {
  50. return redis;
  51. };
  52. // sets the timestamp for +uuid+ and its face file's date to now
  53. exp.update_timestamp = function(uuid, hash) {
  54. console.log(uuid + " cache: updating timestamp");
  55. var time = new Date().getTime();
  56. redis.hmset(uuid, "t", time);
  57. update_file_date(hash);
  58. };
  59. // create the key +uuid+, store +hash+ and time
  60. exp.save_hash = function(uuid, hash) {
  61. console.log(uuid + " cache: saving hash");
  62. var time = new Date().getTime();
  63. redis.hmset(uuid, "h", hash, "t", time);
  64. };
  65. // get a details object for +uuid+
  66. // {hash: "0123456789abcdef", time: 1414881524512}
  67. // null when uuid unkown
  68. exp.get_details = function(uuid, callback) {
  69. redis.hgetall(uuid, function(err, data) {
  70. var details = null;
  71. if (data) {
  72. details = {
  73. hash: (data.h == "null" ? null : data.h),
  74. time: Number(data.t)
  75. };
  76. }
  77. callback(err, details);
  78. });
  79. };
  80. connect_redis();
  81. module.exports = exp;