From 9bb31f57226877f78f23fb766773aa8486297bb7 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Thu, 30 Jun 2011 00:52:42 +0200 Subject: initial commit --- lib/main.js | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 lib/main.js (limited to 'lib/main.js') diff --git a/lib/main.js b/lib/main.js new file mode 100644 index 0000000..6e2f36a --- /dev/null +++ b/lib/main.js @@ -0,0 +1,103 @@ +var http = require('http'), +router = require('choreographer').router(), +qs = require('querystring'), +uuid = require(__dirname + '/uuid'), +hl = require(__dirname + '/highlight'), +kyoto = require('kyoto'); + +var db = new kyoto.open(__dirname + '/../db/pastes.kch', 'a+', kyotoOpen); + +function generateId(callback) { + var id = uuid.generate(14); + db.get(id, function(err, value) { + if (value) { + generateId(); + } + else { + callback(id); + } + }); +} + +function getPaste(plain, req, res, paste) { + db.get(paste, function(err, value) { + if (err) { + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.end('404: ' + req.url + ' not found:\n' + err + '\n'); + } + else { + var data = JSON.parse(value); + if (plain) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(data.content); + } + else { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write(hl.highlight(data.content, data.language)); + } + res.end('\n'); + } + }); +} + +router + .get('/plain/*', function(req, res, paste) { + getPaste(true, req, res, paste); + }) + .get('/get/*', function(req, res, paste) { + getPaste(false, req, res, paste); + }) + .get('/', function(req, res) { + }) + .post('/add', function(req, res) { + var content = ''; + + req.on('data', function(chunk) { + content += chunk; + }); + + req.on('end', function() { + var post = qs.parse(content); + + generateId(function(id) { + var data = { + content: post.content, + language: post.language, + time: Date() + }; + db.set(id, JSON.stringify(data), function(err) { + if (err) { + res.writeHead(500, {'Content-Type': 'text/plain'}); + res.write(err); + res.end('\n'); + } + else { + console.log('new paste: %s', id); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(id); + res.end('\n'); + } + }); + }); + }); + }) + .notFound(function(req, res) { + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.end('404: ' + req.url + ' not found.\n'); + }); + + +function kyotoOpen(err) { + if (err) throw err; + + http.createServer(router).listen(8080); + console.log('Listening on port 8080...'); +} + +process.on('uncaughtException', function(exeption) { + process.exit(1); +}); + +process.on('exit', function() { + db.close(function(err) { console.log(err); }); +}); -- cgit v1.2.3