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); }); });