Simple image host.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. var formidable = require("formidable");
  2. var crypto = require("crypto");
  3. var sessions = {};
  4. function templatify(str, args) {
  5. if (args == undefined)
  6. return str;
  7. for (var i in args) {
  8. str = str.split("{{"+i+"}}").join(args[i]);
  9. }
  10. return str;
  11. }
  12. module.exports = function(options) {
  13. this.req = options.req;
  14. this.res = options.res;
  15. this.templates = options.templates;
  16. this.views = options.views;
  17. this.db = options.db;
  18. this.conf = options.conf;
  19. //Handle cookies
  20. this.cookies = {};
  21. this.req.headers.cookie = this.req.headers.cookie || "";
  22. this.req.headers.cookie.split(/;\s*/).forEach(function(elem) {
  23. var pair = elem.split("=");
  24. this.cookies[pair[0]] = decodeURIComponent(pair[1]);
  25. }.bind(this));
  26. //Handle sessions
  27. if (sessions[this.cookies.session]) {
  28. this.session = sessions[this.cookies.session];
  29. } else {
  30. var key;
  31. do {
  32. key = crypto.randomBytes(64).toString("hex");
  33. } while (sessions[key]);
  34. sessions[key] = {};
  35. this.res.setHeader("Set-Cookie", "session="+key);
  36. //Delete session after a while
  37. setTimeout(function() {
  38. delete sessions[key];
  39. }, this.conf.session_timeout);
  40. }
  41. }
  42. module.exports.prototype = {
  43. end: function(str) {
  44. this.res.end(str);
  45. },
  46. succeed: function(obj) {
  47. obj = obj || {};
  48. obj.success = true;
  49. this.end(JSON.stringify(obj));
  50. },
  51. fail: function(err) {
  52. obj = {};
  53. obj.success = false;
  54. obj.error = err.toString();
  55. this.end(JSON.stringify(obj));
  56. },
  57. template: function(name, args) {
  58. var str = this.templates[name];
  59. if (!str)
  60. throw new Error("No such template: "+name);
  61. return templatify(str, args);
  62. },
  63. view: function(name, args) {
  64. var str = this.views[name];
  65. if (!str)
  66. throw new Error("No such view: "+name);
  67. return templatify(str, args);
  68. },
  69. getPostData: function(cb) {
  70. if (this.postData)
  71. return cb(null, this.postData.data, this.postData.files);
  72. if (this.req.method.toUpperCase() != "POST")
  73. return cb(new Error("Expected POST request, got "+this.req.method));
  74. var form = new formidable.IncomingForm();
  75. form.parse(this.req, function(err, data, files) {
  76. if (err) return cb(err);
  77. this.postData = {
  78. data: data,
  79. files: files
  80. }
  81. cb(null, data, files);
  82. }.bind(this));
  83. }
  84. }