cache.js 2.1 KB

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