Simple image host.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

context.js 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. var formidable = require("formidable");
  2. var crypto = require("crypto");
  3. var zlib = require("zlib");
  4. var preprocess = require("./preprocess.js");
  5. var sessions = {};
  6. function templatify(str, args, ctx, env) {
  7. env.url = ctx.req.url;
  8. str = preprocess(str, {
  9. session: function(key) {
  10. ctx.cachable = false;
  11. return ctx.session[key];
  12. },
  13. arg: function(key) {
  14. return ctx.htmlEntities(args[key]);
  15. },
  16. noescape: args,
  17. env: env,
  18. template: function(key) {
  19. return ctx.template(key);
  20. }
  21. });
  22. return str;
  23. }
  24. var cache = {};
  25. module.exports = function(options) {
  26. this.req = options.req;
  27. this.res = options.res;
  28. this.templates = options.templates;
  29. this.views = options.views;
  30. this.db = options.db;
  31. this.conf = options.conf;
  32. this.query = this.req.url.split("?")[1] || "";
  33. this.shouldGzip = /gzip/.test(this.req.headers["accept-encoding"]);
  34. this.cachable = true;
  35. this.statusCode = 200;
  36. this.headers = {};
  37. if (this.conf.debug)
  38. this.startTime = new Date();
  39. //Handle cookies
  40. this.cookies = {};
  41. this.req.headers.cookie = this.req.headers.cookie || "";
  42. this.req.headers.cookie.split(/;\s*/).forEach(function(elem) {
  43. var pair = elem.split("=");
  44. this.cookies[pair[0]] = decodeURIComponent(pair[1]);
  45. }.bind(this));
  46. //Handle sessions
  47. var key;
  48. if (sessions[this.cookies.session]) {
  49. key = this.cookies.session;
  50. } else {
  51. do {
  52. key = crypto.randomBytes(64).toString("hex");
  53. } while (sessions[key]);
  54. sessions[key] = {};
  55. this.res.setHeader("Set-Cookie", "session="+key);
  56. //Delete session after a while
  57. setTimeout(function() {
  58. delete sessions[key];
  59. }, this.conf.session_timeout);
  60. }
  61. this.session = sessions[key];
  62. //Reset session delete timer
  63. if (this.session._timeout)
  64. clearTimeout(this.session._timeout);
  65. this.session._timeout = setTimeout(function() {
  66. delete sessions[key];
  67. }, this.conf.session_timeout);
  68. }
  69. module.exports.prototype = {
  70. _end: function(str) {
  71. if (this.conf.debug) {
  72. var ms = (new Date().getTime() - this.startTime.getTime());
  73. console.log(
  74. ms+" millisecond(s)\t"+
  75. (this.statusCode || 200)+"\t"+
  76. this.req.url
  77. );
  78. } else {
  79. console.log(this.req.url);
  80. }
  81. this.res.writeHead(this.statusCode, this.headers);
  82. this.res.end(str);
  83. },
  84. end: function(str, alreadyGzipped) {
  85. if (!this.shouldGzip)
  86. return this._end(str);
  87. this.setHeader("Content-Encoding", "gzip");
  88. if (alreadyGzipped)
  89. return this._end(str);
  90. zlib.gzip(str, function(err, res) {
  91. if (err)
  92. throw err;
  93. this._end(res);
  94. }.bind(this));
  95. },
  96. succeed: function(obj) {
  97. obj = obj || {};
  98. obj.success = true;
  99. this.setHeader("Content-Type", "application/json");
  100. this.end(JSON.stringify(obj));
  101. },
  102. fail: function(err) {
  103. console.log("Sending error to client:");
  104. console.trace(err);
  105. this.setHeader("Content-Type", "application/json");
  106. obj = {};
  107. obj.success = false;
  108. obj.error = err.toString();
  109. this.end(JSON.stringify(obj));
  110. },
  111. template: function(name, args) {
  112. var str = this.templates[name];
  113. if (!str)
  114. throw new Error("No such template: "+name);
  115. return templatify(str, args, this, {template: name});
  116. },
  117. view: function(name, args) {
  118. var str = this.views[name];
  119. if (!str)
  120. throw new Error("No such view: "+name);
  121. if (name === "404")
  122. this.setStatus(404);
  123. return templatify(str, args, this, {view: name});
  124. },
  125. getPostData: function(cb) {
  126. if (this.postData)
  127. return cb(null, this.postData.data, this.postData.files);
  128. if (this.req.method.toUpperCase() != "POST")
  129. return cb(new Error("Expected POST request, got "+this.req.method));
  130. var form = new formidable.IncomingForm();
  131. form.parse(this.req, function(err, data, files) {
  132. if (err) return cb(err);
  133. this.postData = {
  134. data: data,
  135. files: files
  136. }
  137. cb(null, data, files);
  138. }.bind(this));
  139. },
  140. setStatus: function(code) {
  141. this.statusCode = code;
  142. },
  143. setHeader: function(key, val) {
  144. this.headers[key] = val;
  145. },
  146. login: function(username, id) {
  147. this.session.loggedIn = true;
  148. this.session.username = username;
  149. this.session.userId = id;
  150. },
  151. logout: function() {
  152. this.session.loggedIn = false;
  153. delete this.session.username;
  154. delete this.session.userId;
  155. },
  156. async: function(n, cb) {
  157. if (typeof n !== "number")
  158. throw new Error("Expected number, got "+typeof n);
  159. if (n < 1)
  160. return cb();
  161. var res = {};
  162. var errs = {};
  163. var errnum = 0;
  164. return function(key, val, err) {
  165. if (key)
  166. res[key] = val;
  167. if (err)
  168. errs[key] = err;
  169. if (n === 1)
  170. cb((errnum ? errs : null), res);
  171. else
  172. n -= 1;
  173. }
  174. },
  175. htmlEntities: function(arg) {
  176. if (typeof arg === "string") {
  177. return arg.replace(/&/g, "&amp;")
  178. .replace(/</g, "&lt;")
  179. .replace(/>/g, "&gt;")
  180. .replace(/"/g, "&quot;");
  181. } else {
  182. return arg;
  183. }
  184. }
  185. }