cache.js 2.4 KB

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