1
0
Fork 0
mirror of https://github.com/SunRed/haste-server.git synced 2024-11-01 01:30:21 +01:00

Merge branch 'master' of github.com:seejohnrun/haste-server

Conflicts:
	static/function-icons.png
This commit is contained in:
Brian Dawson 2012-01-22 23:42:41 -05:00
commit d2bd78956b
14 changed files with 207 additions and 108 deletions

View file

@ -1,6 +1,9 @@
# Haste
Haste is an open-source pastebin software written in node.js, which is easily installable in any network. It can be backed by either redis or filesystem, and has a very easy adapter interface for other stores. A publicly available version can be found at [hastebin.com](http://hastebin.com)
Haste is an open-source pastebin software written in node.js, which is easily
installable in any network. It can be backed by either redis or filesystem,
and has a very easy adapter interface for other stores. A publicly available
version can be found at [hastebin.com](http://hastebin.com)
Major design objectives:
@ -8,11 +11,13 @@ Major design objectives:
* Be really simple
* Be easy to set up and use
Haste works really well with a little utility called haste-client, allowing you to do things like:
Haste works really well with a little utility called haste-client, allowing you
to do things like:
`cat something | haste`
which will output a URL to share containing the contents of `cat something`'s STDOUT
which will output a URL to share containing the contents of `cat something`'s
STDOUT
## Tested Browsers
@ -35,7 +40,8 @@ which will output a URL to share containing the contents of `cat something`'s ST
* `maxLength` - maximum length of a paste (default none)
* `staticMaxAge` - max age for static assets (86400)
* `recompressStatisAssets` - whether or not to compile static js assets (true)
* `documents` - static documents to serve (ex: http://hastebin.com/about.com) in addition to static assets. These will never expire.
* `documents` - static documents to serve (ex: http://hastebin.com/about.com)
in addition to static assets. These will never expire.
* `storage` - storage options (see below)
* `logging` - logging preferences
* `keyGenerator` - key generator options (see below)
@ -63,13 +69,15 @@ Generates a random key
}
```
The _optional_ keySpace argument is a string of acceptable characters for the key.
The _optional_ keySpace argument is a string of acceptable characters
for the key.
## Storage
### File
To use file storage (the default) change the storage section in `config.js` to something like:
To use file storage (the default) change the storage section in `config.js` to
something like:
``` json
{
@ -82,9 +90,9 @@ Where `path` represents where you want the files stored
### Redis
To use redis storage you must install the redis package in npm globall using
To use redis storage you must install the redis package in npm
`npm install redis --global`
`npm install redis`
Once you've done that, your config section should look like:
@ -97,10 +105,35 @@ Once you've done that, your config section should look like:
}
```
You can also set an `expire` option to the number of seconds to expire keys in. This is off by default, but will constantly kick back expirations on each view or post.
You can also set an `expire` option to the number of seconds to expire keys in.
This is off by default, but will constantly kick back expirations on each view
or post.
All of which are optional except `type` with very logical default values.
### Memcached
To use memcached storage you must install the `memcache` package via npm
`npm install memcache`
Once you've done that, your config section should look like:
``` json
{
"type": "memcached",
"host": "127.0.0.1",
"port": 11211
}
```
You can also set an `expire` option to the number of seconds to expire keys in.
This behaves just like the redis expirations, but does not push expirations
forward on GETs.
All of which are optional except `type` with very logical default values.
## Author
John Crepezzi <john.crepezzi@gmail.com>
@ -111,11 +144,23 @@ John Crepezzi <john.crepezzi@gmail.com>
Copyright © 2011 John Crepezzi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the Software), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
### Other components:

View file

@ -1 +0,0 @@
* add feedback for errors to UI - esp. too long

View file

@ -1,33 +1,37 @@
# Haste
Sharing code is a good thing, and it should be _really_ easy to do it.
A lot of times, I want to show you something I'm seeing - and that's where we use pastebins.
A lot of times, I want to show you something I'm seeing - and that's where we
use pastebins.
Haste is the prettiest, easist to use pastebin ever made.
## Basic Usage
Type what you want me to see, click "Save", and then copy the URL. Send that URL
to someone and they'll see what you see.
Type what you want me to see, click "Save", and then copy the URL. Send that
URL to someone and they'll see what you see.
To make a new entry, click "New" (or type 'control + n')
## From the Console
Most of the time I want to show you some text, its coming from my current console session.
We should make it really easy to take code from the console and send it to people.
Most of the time I want to show you some text, its coming from my current
console session. We should make it really easy to take code from the console
and send it to people.
`cat something | haste` # http://hastebin.com/1238193
You can even take this a step further, and cut out the last step of copying the URL with:
You can even take this a step further, and cut out the last step of copying the
URL with:
* osx: `cat something | haste | pbcopy`
* linux: `cat something | haste | xsel`
After running that, the STDOUT output of `cat something` will show up at a URL which has
been conveniently copied to your clipboard.
After running that, the STDOUT output of `cat something` will show up at a URL
which has been conveniently copied to your clipboard.
That's all there is to that, and you can install it with `gem install haste` right now.
That's all there is to that, and you can install it with `gem install haste`
right now.
* osx: you will need to have an up to date version of Xcode
* linux: you will need to have rubygems and ruby-devel installed
@ -37,9 +41,10 @@ Pastes will stay for 30 days from their last view.
## Privacy
While the contents of hastebin.com are not directly crawled by any search robot that
obeys "robots.txt", there should be no great expectation of privacy. Post things at your
own risk. Not responsible for any loss of data or removed pastes.
While the contents of hastebin.com are not directly crawled by any search robot
that obeys "robots.txt", there should be no great expectation of privacy. Post
things at your own risk. Not responsible for any loss of data or removed
pastes.
## Open Source

View file

@ -60,7 +60,9 @@ DocumentHandler.prototype.handlePost = function(request, response) {
cancelled = true;
winston.warn('document >maxLength', { maxLength: _this.maxLength });
response.writeHead(400, { 'content-type': 'application/json' });
response.end(JSON.stringify({ message: 'Document exceeds maximum length.' }));
response.end(
JSON.stringify({ message: 'Document exceeds maximum length.' })
);
}
});
request.on('end', function(end) {
@ -86,9 +88,9 @@ DocumentHandler.prototype.handlePost = function(request, response) {
});
};
// Get a random key that hasn't been already used
// Keep choosing keys until one isn't taken
DocumentHandler.prototype.chooseKey = function(callback) {
var key = this.keyGenerator.createKey(this.keyLength);
var key = this.acceptableKey();
var _this = this;
this.store.get(key, function(ret) {
if (ret) {
@ -99,4 +101,8 @@ DocumentHandler.prototype.chooseKey = function(callback) {
});
};
DocumentHandler.prototype.acceptableKey = function() {
return this.keyGenerator.createKey(this.keyLength);
};
module.exports = DocumentHandler;

View file

@ -1,7 +1,7 @@
var fs = require('fs');
var crypto = require('crypto');
var winston = require('winston');
var hashlib = require('hashlib');
// For storing in files
// options[type] = file
@ -12,12 +12,21 @@ var FileDocumentStore = function(options) {
this.expire = options.expire;
};
// Save data in a file, key as md5 - since we don't know what we could be passed here
// Generate md5 of a string
FileDocumentStore.md5 = function(str) {
var md5sum = crypto.createHash('md5');
md5sum.update(str);
return md5sum.digest('hex');
};
// Save data in a file, key as md5 - since we don't know what we could
// be passed here
FileDocumentStore.prototype.set = function(key, data, callback, skipExpire) {
try {
var _this = this;
fs.mkdir(this.basePath, '700', function() {
fs.writeFile(_this.basePath + '/' + hashlib.md5(key), data, 'utf8', function(err) {
var fn = _this.basePath + '/' + _this.md5(key);
fs.writeFile(fn, data, 'utf8', function(err) {
if (err) {
callback(false);
}
@ -37,7 +46,8 @@ FileDocumentStore.prototype.set = function(key, data, callback, skipExpire) {
// Get data from a file from key
FileDocumentStore.prototype.get = function(key, callback, skipExpire) {
var _this = this;
fs.readFile(this.basePath + '/' + hashlib.md5(key), 'utf8', function(err, data) {
var fn = this.basePath + '/' + this.md5(key);
fs.readFile(fn, 'utf8', function(err, data) {
if (err) {
callback(false);
}

View file

@ -0,0 +1,45 @@
var memcached = require('memcache');
var winston = require('winston');
// Create a new store with options
var MemcachedDocumentStore = function(options) {
this.expire = options.expire;
if (!MemcachedDocumentStore.client) {
MemcachedDocumentStore.connect(options);
}
};
// Create a connection
MemcachedDocumentStore.connect = function(options) {
var host = options.host || '127.0.0.1';
var port = options.port || 11211;
this.client = new memcached.Client(port, host);
this.client.connect();
this.client.on('connect', function() {
winston.info('connected to memcached on ' + host + ':' + port);
});
this.client.on('error', function(e) {
winston.info('error connecting to memcached', { error: e });
});
};
// Save file in a key
MemcachedDocumentStore.prototype.set =
function(key, data, callback, skipExpire) {
MemcachedDocumentStore.client.set(key, data, function(err, reply) {
err ? callback(false) : callback(true);
}, skipExpire ? 0 : this.expire);
};
// Get a file from a key
MemcachedDocumentStore.prototype.get = function(key, callback, skipExpire) {
var _this = this;
MemcachedDocumentStore.client.get(key, function(err, reply) {
callback(err ? false : reply);
if (_this.expire && !skipExpire) {
winston.warn('store does not currently push forward expirations on GET');
}
});
};
module.exports = MemcachedDocumentStore;

View file

@ -1,6 +1,5 @@
var redis = require('redis');
var winston = require('winston');
var hashlib = require('hashlib');
// For storing in redis
// options[type] = redis
@ -24,7 +23,10 @@ RedisDocumentStore.connect = function(options) {
RedisDocumentStore.client = redis.createClient(port, host);
RedisDocumentStore.client.select(index, function(err, reply) {
if (err) {
winston.error('error connecting to redis index ' + index, { error: err.message });
winston.error(
'error connecting to redis index ' + index,
{ error: err.message }
);
process.exit(1);
}
else {

View file

@ -1,12 +1,17 @@
var RandomKeyGenerator = function(options) {
if (!options) {
options = {};
}
this.keyspace = options.keyspace || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
};
// Generate a random key
RandomKeyGenerator.prototype.createKey = function(keyLength) {
var text = '';
var index;
for (var i = 0; i < keyLength; i++) {
text += this.keyspace.charAt(Math.floor(Math.random() * this.keyspace.length));
index = Math.floor(Math.random() * this.keyspace.length);
text += this.keyspace.charAt(index);
}
return text;
};

View file

@ -19,13 +19,13 @@
"dependencies": {
"winston": "*",
"hashlib": "*",
"connect": "*",
"uglify-js": "*"
},
"devDependencies": {
"jasmine-node": "*"
"mocha": "*",
"should": "*"
},
"bundledDependencies": [],
@ -46,7 +46,7 @@
"scripts": {
"start": "node server.js",
"test": "jasmine-node spec"
"test": "mocha -r should spec/*"
}
}

View file

@ -34,7 +34,7 @@ if (!config.storage) {
if (!config.storage.type) {
config.storage.type = 'file';
}
var Store = require('./lib/' + config.storage.type + '_document_store');
var Store = require('./lib/document_stores/' + config.storage.type);
var preferredStore = new Store(config.storage);
// Compress the static javascript assets
@ -45,8 +45,10 @@ if (config.recompressStaticAssets) {
for (var i = 0; i < list.length; i++) {
var item = list[i];
var orig_code, ast;
if ((item.indexOf('.js') === item.length - 3) && (item.indexOf('.min.js') === -1)) {
dest = item.substring(0, item.length - 3) + '.min' + item.substring(item.length - 3);
if ((item.indexOf('.js') === item.length - 3) &&
(item.indexOf('.min.js') === -1)) {
dest = item.substring(0, item.length - 3) + '.min' +
item.substring(item.length - 3);
orig_code = fs.readFileSync('./static/' + item, 'utf8');
ast = jsp.parse(orig_code);
ast = pro.ast_mangle(ast);
@ -67,7 +69,10 @@ for (var name in config.documents) {
}, true);
}
else {
winston.warn('failed to load static document', { name: name, path: path });
winston.warn(
'failed to load static document',
{ name: name, path: path }
);
}
});
}
@ -103,7 +108,11 @@ connect.createServer(
// get documents
app.get('/documents/:id', function(request, response, next) {
var skipExpire = !!config.documents[request.params.id];
return documentHandler.handleGet(request.params.id, response, skipExpire);
return documentHandler.handleGet(
request.params.id,
response,
skipExpire
);
});
}),
// Otherwise, static

View file

@ -1,17 +1,20 @@
var DocumentHandler = require('../lib/document_handler');
var Generator = require('../lib/key_generators/random');
describe('document_handler', function() {
describe('randomKey', function() {
it('should choose a key of the proper length', function() {
var dh = new DocumentHandler({ keyLength: 6 });
expect(dh.randomKey().length).toBe(6);
var gen = new Generator();
var dh = new DocumentHandler({ keyLength: 6, keyGenerator: gen });
dh.acceptableKey().length.should.equal(6);
});
it('should choose a default key length', function() {
var dh = new DocumentHandler();
expect(dh.keyLength).toBe(DocumentHandler.defaultKeyLength);
var gen = new Generator();
var dh = new DocumentHandler({ keyGenerator: gen });
dh.keyLength.should.equal(DocumentHandler.defaultKeyLength);
});
});

View file

@ -1,4 +1,4 @@
var RedisDocumentStore = require('../lib/redis_document_store');
var RedisDocumentStore = require('../lib/document_stores/redis');
var winston = require('winston');
winston.remove(winston.transports.Console);
@ -15,73 +15,34 @@ describe('redis_document_store', function() {
describe('set', function() {
it('should be able to set a key and have an expiration set', function() {
it('should be able to set a key and have an expiration set', function(done) {
var store = new RedisDocumentStore({ expire: 10 });
runs(function() {
var _this = this;
store.set('hello1', 'world', function(worked) {
_this.result = worked;
});
});
waitsFor(function() {
return typeof(this.result) === 'boolean';
});
runs(function() {
var _this = this;
store.set('hello1', 'world', function() {
RedisDocumentStore.client.ttl('hello1', function(err, res) {
expect(res).toBeGreaterThan(1);
_this.done = true;
res.should.be.above(1);
done();
});
});
waitsFor(function() {
return this.done;
});
});
it('should not set an expiration when told not to', function() {
it('should not set an expiration when told not to', function(done) {
var store = new RedisDocumentStore({ expire: 10 });
runs(function() {
var _this = this;
store.set('hello2', 'world', function(worked) {
_this.result = worked;
}, true);
});
waitsFor(function() {
return typeof(this.result) === 'boolean';
});
runs(function() {
var _this = this;
store.set('hello2', 'world', function() {
RedisDocumentStore.client.ttl('hello2', function(err, res) {
expect(res).toBe(-1);
_this.done = true;
res.should.equal(-1);
done();
});
});
waitsFor(function() {
return this.done;
});
}, true);
});
it('should not set an expiration when expiration is off', function() {
it('should not set an expiration when expiration is off', function(done) {
var store = new RedisDocumentStore({ expire: false });
runs(function() {
var _this = this;
store.set('hello3', 'world', function(worked) {
_this.result = worked;
});
});
waitsFor(function() {
return typeof(this.result) === 'boolean';
});
runs(function() {
var _this = this;
store.set('hello3', 'world', function(worked) {
RedisDocumentStore.client.ttl('hello3', function(err, res) {
expect(res).toBe(-1);
_this.done = true;
res.should.equal(-1);
done();
});
});
waitsFor(function() {
return this.done;
});
});
});

View file

@ -4,6 +4,15 @@ var haste_document = function() {
this.locked = false;
};
// Escapes HTML tag characters
haste_document.prototype.htmlEscape = function(s) {
return s
.replace(/&/g, '&amp;')
.replace(/>/g, '&gt;')
.replace(/</g, '&lt;')
.replace(/"/g, '&quot;');
};
// Get this document from the server and lock it here
haste_document.prototype.load = function(key, callback, lang) {
var _this = this;
@ -17,7 +26,7 @@ haste_document.prototype.load = function(key, callback, lang) {
try {
var high;
if (lang === 'txt') {
high = { value: res.data };
high = { value: _this.htmlEscape(res.data) };
}
else if (lang) {
high = hljs.highlight(lang, res.data);

View file

@ -1 +1 @@
var haste_document=function(){this.locked=!1};haste_document.prototype.load=function(a,b,c){var d=this;$.ajax("/documents/"+a,{type:"get",dataType:"json",success:function(e){d.locked=!0,d.key=a,d.data=e.data;try{var f;c==="txt"?f={value:e.data}:c?f=hljs.highlight(c,e.data):f=hljs.highlightAuto(e.data)}catch(g){f=hljs.highlightAuto(e.data)}b({value:f.value,key:a,language:f.language||c,lineCount:e.data.split("\n").length})},error:function(a){b(!1)}})},haste_document.prototype.save=function(a,b){if(this.locked)return!1;this.data=a;var c=this;$.ajax("/documents",{type:"post",data:a,dataType:"json",success:function(d){c.locked=!0,c.key=d.key;var e=hljs.highlightAuto(a);b(null,{value:e.value,key:d.key,language:e.language,lineCount:a.split("\n").length})},error:function(a){try{b($.parseJSON(a.responseText))}catch(c){b({message:"Something went wrong!"})}}})};var haste=function(a,b){this.appName=a,this.baseUrl=window.location.href,this.$textarea=$("textarea"),this.$box=$("#box"),this.$code=$("#box code"),this.$linenos=$("#linenos"),this.options=b,this.configureShortcuts(),this.configureButtons(),b.twitter||$("#box2 .twitter").hide()};haste.prototype.setTitle=function(a){var b=a?this.appName+" - "+a:this.appName;document.title=b},haste.prototype.showMessage=function(a,b){var c=$('<li class="'+(b||"info")+'">'+a+"</li>");$("#messages").prepend(c),setTimeout(function(){c.slideUp("fast",function(){$(this).remove()})},3e3)},haste.prototype.lightKey=function(){this.configureKey(["new","save"])},haste.prototype.fullKey=function(){this.configureKey(["new","duplicate","twitter","link"])},haste.prototype.configureKey=function(a){var b,c=0;$("#box2 .function").each(function(){b=$(this);for(c=0;c<a.length;c++)if(b.hasClass(a[c]))return b.addClass("enabled"),!0;b.removeClass("enabled")})},haste.prototype.newDocument=function(a){this.$box.hide(),this.doc=new haste_document,a||window.history.pushState(null,this.appName,"/"),this.setTitle(),this.lightKey(),this.$textarea.val("").show("fast",function(){this.focus()}),this.removeLineNumbers()},haste.extensionMap={rb:"ruby",py:"python",pl:"perl",php:"php",scala:"scala",go:"go",xml:"xml",html:"xml",htm:"xml",css:"css",js:"javascript",vbs:"vbscript",lua:"lua",pas:"delphi",java:"java",cpp:"cpp",cc:"cpp",m:"objectivec",vala:"vala",cs:"cs",sql:"sql",sm:"smalltalk",lisp:"lisp",ini:"ini",diff:"diff",bash:"bash",sh:"bash",tex:"tex",erl:"erlang",hs:"haskell",md:"markdown",txt:""},haste.prototype.lookupExtensionByType=function(a){for(var b in haste.extensionMap)if(haste.extensionMap[b]===a)return b;return a},haste.prototype.lookupTypeByExtension=function(a){return haste.extensionMap[a]||a},haste.prototype.addLineNumbers=function(a){var b="";for(var c=0;c<a;c++)b+=(c+1).toString()+"<br/>";$("#linenos").html(b)},haste.prototype.removeLineNumbers=function(){$("#linenos").html("&gt;")},haste.prototype.loadDocument=function(a){var b=a.split(".",2),c=this;c.doc=new haste_document,c.doc.load(b[0],function(a){a?(c.$code.html(a.value),c.setTitle(a.key),c.fullKey(),c.$textarea.val("").hide(),c.$box.show().focus(),c.addLineNumbers(a.lineCount)):c.newDocument()},this.lookupTypeByExtension(b[1]))},haste.prototype.duplicateDocument=function(){if(this.doc.locked){var a=this.doc.data;this.newDocument(),this.$textarea.val(a)}},haste.prototype.lockDocument=function(){var a=this;this.doc.save(this.$textarea.val(),function(b,c){if(b)a.showMessage(b.message,"error");else if(c){a.$code.html(c.value),a.setTitle(c.key);var d="/"+c.key;c.language&&(d+="."+a.lookupExtensionByType(c.language)),window.history.pushState(null,a.appName+"-"+c.key,d),a.fullKey(),a.$textarea.val("").hide(),a.$box.show().focus(),a.addLineNumbers(c.lineCount)}})},haste.prototype.configureButtons=function(){var a=this;this.buttons=[{$where:$("#box2 .save"),label:"Save",shortcutDescription:"control + s",shortcut:function(a){return a.ctrlKey&&a.keyCode===83},action:function(){a.$textarea.val().replace(/^\s+|\s+$/g,"")!==""&&a.lockDocument()}},{$where:$("#box2 .new"),label:"New",shortcut:function(a){return a.ctrlKey&&a.keyCode===78},shortcutDescription:"control + n",action:function(){a.newDocument(!a.doc.key)}},{$where:$("#box2 .duplicate"),label:"Duplicate & Edit",shortcut:function(b){return a.doc.locked&&b.ctrlKey&&b.keyCode===68},shortcutDescription:"control + d",action:function(){a.duplicateDocument()}},{$where:$("#box2 .twitter"),label:"Twitter",shortcut:function(b){return a.options.twitter&&a.doc.locked&&b.ctrlKey&&b.keyCode==84},shortcutDescription:"control + t",action:function(){window.open("https://twitter.com/share?url="+encodeURI(window.location.href))}}];for(var b=0;b<this.buttons.length;b++)this.configureButton(this.buttons[b])},haste.prototype.configureButton=function(a){a.$where.click(function(b){b.preventDefault(),!a.clickDisabled&&$(this).hasClass("enabled")&&a.action()}),a.$where.mouseenter(function(b){$("#box3 .label").text(a.label),$("#box3 .shortcut").text(a.shortcutDescription||""),$("#box3").show(),$(this).append($("#pointer").remove().show())}),a.$where.mouseleave(function(a){$("#box3").hide(),$("#pointer").hide()})},haste.prototype.configureShortcuts=function(){var a=this;$(document.body).keydown(function(b){var c;for(var d=0;d<a.buttons.length;d++){c=a.buttons[d];if(c.shortcut&&c.shortcut(b)){b.preventDefault(),c.action();return}}})},$(function(){$("textarea").keydown(function(a){if(a.keyCode===9){a.preventDefault();var b=" ";if(document.selection)this.focus(),sel=document.selection.createRange(),sel.text=b,this.focus();else if(this.selectionStart||this.selectionStart=="0"){var c=this.selectionStart,d=this.selectionEnd,e=this.scrollTop;this.value=this.value.substring(0,c)+b+this.value.substring(d,this.value.length),this.focus(),this.selectionStart=c+b.length,this.selectionEnd=c+b.length,this.scrollTop=e}else this.value+=b,this.focus()}})})
var haste_document=function(){this.locked=!1};haste_document.prototype.htmlEscape=function(a){return a.replace(/&/g,"&amp;").replace(/>/g,"&gt;").replace(/</g,"&lt;").replace(/"/g,"&quot;")},haste_document.prototype.load=function(a,b,c){var d=this;$.ajax("/documents/"+a,{type:"get",dataType:"json",success:function(e){d.locked=!0,d.key=a,d.data=e.data;try{var f;c==="txt"?f={value:d.htmlEscape(e.data)}:c?f=hljs.highlight(c,e.data):f=hljs.highlightAuto(e.data)}catch(g){f=hljs.highlightAuto(e.data)}b({value:f.value,key:a,language:f.language||c,lineCount:e.data.split("\n").length})},error:function(a){b(!1)}})},haste_document.prototype.save=function(a,b){if(this.locked)return!1;this.data=a;var c=this;$.ajax("/documents",{type:"post",data:a,dataType:"json",success:function(d){c.locked=!0,c.key=d.key;var e=hljs.highlightAuto(a);b(null,{value:e.value,key:d.key,language:e.language,lineCount:a.split("\n").length})},error:function(a){try{b($.parseJSON(a.responseText))}catch(c){b({message:"Something went wrong!"})}}})};var haste=function(a,b){this.appName=a,this.baseUrl=window.location.href,this.$textarea=$("textarea"),this.$box=$("#box"),this.$code=$("#box code"),this.$linenos=$("#linenos"),this.options=b,this.configureShortcuts(),this.configureButtons(),b.twitter||$("#box2 .twitter").hide()};haste.prototype.setTitle=function(a){var b=a?this.appName+" - "+a:this.appName;document.title=b},haste.prototype.showMessage=function(a,b){var c=$('<li class="'+(b||"info")+'">'+a+"</li>");$("#messages").prepend(c),setTimeout(function(){c.slideUp("fast",function(){$(this).remove()})},3e3)},haste.prototype.lightKey=function(){this.configureKey(["new","save"])},haste.prototype.fullKey=function(){this.configureKey(["new","duplicate","twitter","link"])},haste.prototype.configureKey=function(a){var b,c=0;$("#box2 .function").each(function(){b=$(this);for(c=0;c<a.length;c++)if(b.hasClass(a[c]))return b.addClass("enabled"),!0;b.removeClass("enabled")})},haste.prototype.newDocument=function(a){this.$box.hide(),this.doc=new haste_document,a||window.history.pushState(null,this.appName,"/"),this.setTitle(),this.lightKey(),this.$textarea.val("").show("fast",function(){this.focus()}),this.removeLineNumbers()},haste.extensionMap={rb:"ruby",py:"python",pl:"perl",php:"php",scala:"scala",go:"go",xml:"xml",html:"xml",htm:"xml",css:"css",js:"javascript",vbs:"vbscript",lua:"lua",pas:"delphi",java:"java",cpp:"cpp",cc:"cpp",m:"objectivec",vala:"vala",cs:"cs",sql:"sql",sm:"smalltalk",lisp:"lisp",ini:"ini",diff:"diff",bash:"bash",sh:"bash",tex:"tex",erl:"erlang",hs:"haskell",md:"markdown",txt:""},haste.prototype.lookupExtensionByType=function(a){for(var b in haste.extensionMap)if(haste.extensionMap[b]===a)return b;return a},haste.prototype.lookupTypeByExtension=function(a){return haste.extensionMap[a]||a},haste.prototype.addLineNumbers=function(a){var b="";for(var c=0;c<a;c++)b+=(c+1).toString()+"<br/>";$("#linenos").html(b)},haste.prototype.removeLineNumbers=function(){$("#linenos").html("&gt;")},haste.prototype.loadDocument=function(a){var b=a.split(".",2),c=this;c.doc=new haste_document,c.doc.load(b[0],function(a){a?(c.$code.html(a.value),c.setTitle(a.key),c.fullKey(),c.$textarea.val("").hide(),c.$box.show().focus(),c.addLineNumbers(a.lineCount)):c.newDocument()},this.lookupTypeByExtension(b[1]))},haste.prototype.duplicateDocument=function(){if(this.doc.locked){var a=this.doc.data;this.newDocument(),this.$textarea.val(a)}},haste.prototype.lockDocument=function(){var a=this;this.doc.save(this.$textarea.val(),function(b,c){if(b)a.showMessage(b.message,"error");else if(c){a.$code.html(c.value),a.setTitle(c.key);var d="/"+c.key;c.language&&(d+="."+a.lookupExtensionByType(c.language)),window.history.pushState(null,a.appName+"-"+c.key,d),a.fullKey(),a.$textarea.val("").hide(),a.$box.show().focus(),a.addLineNumbers(c.lineCount)}})},haste.prototype.configureButtons=function(){var a=this;this.buttons=[{$where:$("#box2 .save"),label:"Save",shortcutDescription:"control + s",shortcut:function(a){return a.ctrlKey&&a.keyCode===83},action:function(){a.$textarea.val().replace(/^\s+|\s+$/g,"")!==""&&a.lockDocument()}},{$where:$("#box2 .new"),label:"New",shortcut:function(a){return a.ctrlKey&&a.keyCode===78},shortcutDescription:"control + n",action:function(){a.newDocument(!a.doc.key)}},{$where:$("#box2 .duplicate"),label:"Duplicate & Edit",shortcut:function(b){return a.doc.locked&&b.ctrlKey&&b.keyCode===68},shortcutDescription:"control + d",action:function(){a.duplicateDocument()}},{$where:$("#box2 .twitter"),label:"Twitter",shortcut:function(b){return a.options.twitter&&a.doc.locked&&b.ctrlKey&&b.keyCode==84},shortcutDescription:"control + t",action:function(){window.open("https://twitter.com/share?url="+encodeURI(window.location.href))}}];for(var b=0;b<this.buttons.length;b++)this.configureButton(this.buttons[b])},haste.prototype.configureButton=function(a){a.$where.click(function(b){b.preventDefault(),!a.clickDisabled&&$(this).hasClass("enabled")&&a.action()}),a.$where.mouseenter(function(b){$("#box3 .label").text(a.label),$("#box3 .shortcut").text(a.shortcutDescription||""),$("#box3").show(),$(this).append($("#pointer").remove().show())}),a.$where.mouseleave(function(a){$("#box3").hide(),$("#pointer").hide()})},haste.prototype.configureShortcuts=function(){var a=this;$(document.body).keydown(function(b){var c;for(var d=0;d<a.buttons.length;d++){c=a.buttons[d];if(c.shortcut&&c.shortcut(b)){b.preventDefault(),c.action();return}}})},$(function(){$("textarea").keydown(function(a){if(a.keyCode===9){a.preventDefault();var b=" ";if(document.selection)this.focus(),sel=document.selection.createRange(),sel.text=b,this.focus();else if(this.selectionStart||this.selectionStart=="0"){var c=this.selectionStart,d=this.selectionEnd,e=this.scrollTop;this.value=this.value.substring(0,c)+b+this.value.substring(d,this.value.length),this.focus(),this.selectionStart=c+b.length,this.selectionEnd=c+b.length,this.scrollTop=e}else this.value+=b,this.focus()}})})