1
0
mirror of https://github.com/Tygs/0bin.git synced 2023-08-10 21:13:00 +03:00

#21 - Resize too big images before upload

This commit is contained in:
Rémy HUBSCHER 2013-01-19 19:40:44 +01:00
parent d57595297e
commit b729a678ea
2 changed files with 687 additions and 624 deletions

View File

@ -1,13 +1,16 @@
/*global sjcl:true, jQuery:true, $:true, lzw:true, zerobin:true, ZeroClipboard:true, vizhash:true, prettyPrint:true, confirm:true */ /*global sjcl:true, jQuery:true, $:true, lzw:true, zerobin:true, ZeroClipboard:true, vizhash:true, prettyPrint:true, confirm:true */
;(function(){ ;
"use strict"; (function () {
"use strict";
/* Start random number generator seeding ASAP */ /* Start random number generator seeding ASAP */
sjcl.random.startCollectors(); sjcl.random.startCollectors();
/* Ensure jquery use cache for ajax requests */ /* Ensure jquery use cache for ajax requests */
$.ajaxSetup({ cache: true }); $.ajaxSetup({
cache: true
});
/** Create a function that create inline callbacks. /** Create a function that create inline callbacks.
We use it to create callbacks for onliners with static arguments We use it to create callbacks for onliners with static arguments
E.G: E.G:
$('stuff').hide(function()(console.log(1, 2, 3))) $('stuff').hide(function()(console.log(1, 2, 3)))
@ -16,52 +19,63 @@ $.ajaxSetup({ cache: true });
$('stuff').hide(mkcb(console.log, 1, 2, 3)) $('stuff').hide(mkcb(console.log, 1, 2, 3))
*/ */
function mkcb(func){ function mkcb(func) {
var args = arguments; var args = arguments;
return function(){ return function () {
return func.apply(func, Array.prototype.slice.call(args, 1)); return func.apply(func, Array.prototype.slice.call(args, 1));
}; };
} }
/*************************** /***************************
**** 0bin utilities *** **** 0bin utilities ***
****************************/ ***************************/
window.zerobin = { window.zerobin = {
/** Base64 + compress + encrypt, with callbacks before each operation, /** Base64 + compress + encrypt, with callbacks before each operation,
and all of them are executed in a timed continuation to give and all of them are executed in a timed continuation to give
a change to the UI to respond. a change to the UI to respond.
*/ */
version: '0.1.1', version: '0.1.1',
encrypt: function(key, content, toBase64Callback, encrypt: function (key, content, toBase64Callback,
compressCallback, encryptCallback, doneCallback) { compressCallback, encryptCallback, doneCallback) {
setTimeout (function(){ setTimeout(function () {
content = sjcl.codec.utf8String.toBits(content); content = sjcl.codec.utf8String.toBits(content);
if (toBase64Callback) {toBase64Callback();} if (toBase64Callback) {
toBase64Callback();
}
setTimeout(function(){ setTimeout(function () {
content = sjcl.codec.base64.fromBits(content); content = sjcl.codec.base64.fromBits(content);
if (compressCallback) {compressCallback();} if (compressCallback) {
compressCallback();
}
setTimeout(function(){ setTimeout(function () {
content = lzw.compress(content); // content = lzw.compress(content); // Create a bug with JPG
if (encryptCallback) {encryptCallback();} if (encryptCallback) {
encryptCallback();
}
setTimeout(function(){ setTimeout(function () {
try { try {
content = sjcl.encrypt(key, content); content = sjcl.encrypt(key, content);
} catch (e) { } catch (e) {
$('input, textarea, select, button').prop('disabled', false);
zerobin.progressBar('form.well .progress').container.hide();
zerobin.message('error', 'Paste could not be encrypted. Aborting.', zerobin.message('error', 'Paste could not be encrypted. Aborting.',
'Error'); 'Error');
} }
if (doneCallback) {doneCallback(content);} if (doneCallback) {
doneCallback(content);
}
}, 250); }, 250);
}, 250); }, 250);
@ -79,39 +93,40 @@ window.zerobin = {
useful, this code is starting be difficult to read. If anyone read this useful, this code is starting be difficult to read. If anyone read this
and got a suggestion, by all means, speak your mind. and got a suggestion, by all means, speak your mind.
*/ */
decrypt: function(key, content, errorCallback, uncompressCallback, decrypt: function (key, content, errorCallback, uncompressCallback,
fromBase64Callback, toStringCallback, doneCallback) { fromBase64Callback, toStringCallback, doneCallback) {
/* Decrypt */ /* Decrypt */
setTimeout(function(){ setTimeout(function () {
try { try {
content = sjcl.decrypt(key, content); content = sjcl.decrypt(key, content);
if (uncompressCallback) {uncompressCallback();} if (uncompressCallback) {
uncompressCallback();
}
/* Decompress */ /* Decompress */
setTimeout(function(){ setTimeout(function () {
try { try {
content = lzw.decompress(content); content = lzw.decompress(content);
if (fromBase64Callback) {fromBase64Callback();} if (fromBase64Callback) {
fromBase64Callback();
}
/* From base 64 to bits */ /* From base 64 to bits */
setTimeout(function(){ setTimeout(function () {
try { try {
content = sjcl.codec.base64.toBits(content); content = sjcl.codec.base64.toBits(content);
if (toStringCallback) {toStringCallback();} if (toStringCallback) {
toStringCallback();
}
/* From bits to string */ /* From bits to string */
setTimeout(function(){ setTimeout(function () {
try { try {
content = sjcl.codec.utf8String.fromBits(content); content = sjcl.codec.utf8String.fromBits(content);
if (doneCallback) {doneCallback(content);} if (doneCallback) {
doneCallback(content);
}
} catch (err) { } catch (err) {
errorCallback(err); errorCallback(err);
} }
@ -139,39 +154,44 @@ window.zerobin = {
/** Create a random base64 string long enought to be suitable as /** Create a random base64 string long enought to be suitable as
an encryption key */ an encryption key */
makeKey: function() { makeKey: function () {
return sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0); return sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
}, },
getFormatedDate: function(date){ getFormatedDate: function (date) {
date = date || new Date(); date = date || new Date();
return ((date.getMonth() +1 ) + '-' + return ((date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear());
date.getDate() + '-' + date.getFullYear());
}, },
getFormatedTime: function(date){ getFormatedTime: function (date) {
date = date || new Date(); date = date || new Date();
var h = date.getHours(), var h = date.getHours(),
m = date.getMinutes(), m = date.getMinutes(),
s = date.getSeconds(); s = date.getSeconds();
if (h < 10) {h = "0" + h;} if (h < 10) {
if (m < 10) {m = "0" + m;} h = "0" + h;
if (s < 10) {s = "0" + s;} }
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
return h + ":" + m + ":" + s; return h + ":" + m + ":" + s;
}, },
numOrdA: function(a, b){ numOrdA: function (a, b) {
return (a-b); return (a - b);
}, },
/** Return a reverse sorted list of all the keys in local storage that /** Return a reverse sorted list of all the keys in local storage that
are prefixed with with the passed version (default being this lib are prefixed with with the passed version (default being this lib
version) */ version) */
getLocalStorageKeys: function(){ getLocalStorageKeys: function () {
var version = 'zerobinV0.1'; var version = 'zerobinV0.1';
var keys = []; var keys = [];
for (var key in localStorage){ for (var key in localStorage) {
if (key.indexOf(version) !== -1){ if (key.indexOf(version) !== -1) {
keys.push(key); keys.push(key);
} }
} }
@ -181,9 +201,9 @@ window.zerobin = {
}, },
/** Get a tinyurl using JSONP */ /** Get a tinyurl using JSONP */
getTinyURL: function(longURL, success) { getTinyURL: function (longURL, success) {
var api = 'http://is.gd/create.php?format=json&url='; var api = 'http://is.gd/create.php?format=json&url=';
$.getJSON(api + encodeURIComponent(longURL) + '&callback=?', function(data){ $.getJSON(api + encodeURIComponent(longURL) + '&callback=?', function (data) {
success(data.shorturl); success(data.shorturl);
}); });
}, },
@ -191,21 +211,21 @@ window.zerobin = {
/** Check for browser support of the named featured. Store the result /** Check for browser support of the named featured. Store the result
and add a class to the html tag with the result */ and add a class to the html tag with the result */
support: { support: {
localStorage: (function(){ localStorage: (function () {
var val = !!(localStorage); var val = !! (localStorage);
$('html').addClass((val ? '' : 'no-') + 'local-storage'); $('html').addClass((val ? '' : 'no-') + 'local-storage');
return val; return val;
})(), })(),
history: (function(){ history: (function () {
var val = !!(window.history && history.pushState); var val = !! (window.history && history.pushState);
$('html').addClass((val ? '' : 'no-') + 'history'); $('html').addClass((val ? '' : 'no-') + 'history');
return val; return val;
})(), })(),
fileUpload: (function(){ fileUpload: (function () {
var w = window; var w = window;
var val = !!(w.File && w.FileReader && w.FileList && w.Blob); var val = !! (w.File && w.FileReader && w.FileList && w.Blob);
$('html').addClass((val ? '' : 'no-') + 'file-upload'); $('html').addClass((val ? '' : 'no-') + 'file-upload');
return val; return val;
})() })()
@ -213,11 +233,10 @@ window.zerobin = {
/** Store the paste of a URL in local storate, with a storage format /** Store the paste of a URL in local storate, with a storage format
version prefix and the paste date as the key */ version prefix and the paste date as the key */
storePaste: function(url, date){ storePaste: function (url, date) {
date = date || new Date(); date = date || new Date();
date = (date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date = (date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + zerobin.getFormatedTime(date));
date.getDate() + ' ' + zerobin.getFormatedTime(date));
var keys = zerobin.getLocalStorageKeys(); var keys = zerobin.getLocalStorageKeys();
@ -232,22 +251,25 @@ window.zerobin = {
If the paste is from today, date format should be "at hh:ss", If the paste is from today, date format should be "at hh:ss",
else it should be "the mm-dd-yyy" else it should be "the mm-dd-yyy"
*/ */
getPreviousPastes: function(){ getPreviousPastes: function () {
var pastes = [], var pastes = [],
keys = zerobin.getLocalStorageKeys(), keys = zerobin.getLocalStorageKeys(),
today = zerobin.getFormatedDate(); today = zerobin.getFormatedDate();
$.each(keys, function(i, key){ $.each(keys, function (i, key) {
var pasteDateTime = key.replace(/^[^#]+#/, ''); var pasteDateTime = key.replace(/^[^#]+#/, '');
var displayDate = pasteDateTime.match(/^(\d+)-(\d+)-(\d+)\s/); var displayDate = pasteDateTime.match(/^(\d+)-(\d+)-(\d+)\s/);
displayDate = displayDate[2] + '-' + displayDate[3] + '-' + displayDate[1]; displayDate = displayDate[2] + '-' + displayDate[3] + '-' + displayDate[1];
var prefix = 'the '; var prefix = 'the ';
if (displayDate === today){ if (displayDate === today) {
displayDate = pasteDateTime.split(' ')[1]; displayDate = pasteDateTime.split(' ')[1];
prefix = 'at '; prefix = 'at ';
} }
pastes.push({displayDate: displayDate, prefix: prefix, pastes.push({
link: localStorage.getItem(key)}); displayDate: displayDate,
prefix: prefix,
link: localStorage.getItem(key)
});
}); });
return pastes; return pastes;
@ -259,12 +281,12 @@ window.zerobin = {
This function use a closure to store a <div> parent for the <a> This function use a closure to store a <div> parent for the <a>
because IE requires the link be processed by it's HTML parser because IE requires the link be processed by it's HTML parser
for the URL to be parsed. */ for the URL to be parsed. */
parseUrl: (function(){ parseUrl: (function () {
var div = document.createElement('div'); var div = document.createElement('div');
div.innerHTML = "<a></a>"; div.innerHTML = "<a></a>";
return function(url){ return function (url) {
div.firstChild.href = url; div.firstChild.href = url;
div.innerHTML = div.innerHTML; div.innerHTML = div.innerHTML;
return div.firstChild; return div.firstChild;
@ -272,27 +294,27 @@ window.zerobin = {
})(), })(),
getPasteId: function(url){ getPasteId: function (url) {
var loc = url ? zerobin.parseUrl(url) : window.location; var loc = url ? zerobin.parseUrl(url) : window.location;
return loc.pathname.replace(/\/|paste/g, ''); return loc.pathname.replace(/\/|paste/g, '');
}, },
getPasteKey: function(url){ getPasteKey: function (url) {
var loc = url ? zerobin.parseUrl(url) : window.location; var loc = url ? zerobin.parseUrl(url) : window.location;
return loc.hash.replace('#', '').replace(/(\?|&).*$/, ''); return loc.hash.replace('#', '').replace(/(\?|&).*$/, '');
}, },
/** Return the paste content stripted from any code coloration */ /** Return the paste content stripted from any code coloration */
getPasteContent: function(){ getPasteContent: function () {
var copy = '' ; var copy = '';
$("#paste-content li").each(function(index) { $("#paste-content li").each(function (index) {
copy = copy + $(this).text().replace(/[\u00a0]+/g, ' ') + '\n'; copy = copy + $(this).text().replace(/[\u00a0]+/g, ' ') + '\n';
}); });
return copy; return copy;
}, },
/** Return an approximate estimate the number of bytes in a text */ /** Return an approximate estimate the number of bytes in a text */
count: function(text, options) { count: function (text, options) {
// Set option defaults // Set option defaults
var crlf = /(\r?\n|\r)/g; var crlf = /(\r?\n|\r)/g;
var whitespace = /(\r?\n|\r|\s+)/g; var whitespace = /(\r?\n|\r|\s+)/g;
@ -306,32 +328,42 @@ window.zerobin = {
return length + nonAscii + Math.max(0, options.lineBreaks * (lineBreaks - 1)); return length + nonAscii + Math.max(0, options.lineBreaks * (lineBreaks - 1));
}, },
/** Create a message, style it and insert it in the alert box */ /** Create a message, style it and insert it in the alert box */
message: function(type, message, title, flush, callback) { message: function (type, message, title, flush, callback) {
$(window).scrollTop(0); $(window).scrollTop(0);
if (flush) {$('.alert-'+type).remove();} if (flush) {
$('.alert-' + type).remove();
}
var $message = $('#alert-template').clone().attr('id', null) var $message = $('#alert-template').clone().attr('id', null)
.addClass('alert alert-' + type); .addClass('alert alert-' + type);
$('.message', $message).html(message); $('.message', $message).html(message);
if (title) {$('.title', $message).html(title);} if (title) {
else {$('.title', $message).remove();} $('.title', $message).html(title);
} else {
$('.title', $message).remove();
}
$message.prependTo($('#main')).show('fadeUp', callback); $message.prependTo($('#main')).show('fadeUp', callback);
}, },
/** Return a progress bar object */ /** Return a progress bar object */
progressBar: function(selector){ progressBar: function (selector) {
var $container = $(selector); var $container = $(selector);
var bar = {container: $container, elem: $container.find('.bar')}; var bar = {
bar.set = function(text, rate){bar.elem.text(text).css('width', rate);}; container: $container,
elem: $container.find('.bar')
};
bar.set = function (text, rate) {
bar.elem.text(text).css('width', rate);
};
return bar; return bar;
}, },
/** Return an integer ranking the probability this text is any kind of /** Return an integer ranking the probability this text is any kind of
source code. */ source code. */
isCode: function(text){ isCode: function (text) {
var code_chars = /[A-Z]{3}[A-Z]+|\.[a-z]|[=:<>{}\[\]$_'"&]| {2}|\t/g; var code_chars = /[A-Z]{3}[A-Z]+|\.[a-z]|[=:<>{}\[\]$_'"&]| {2}|\t/g;
var comments = /(:?\/\*|<!--)(:?.|\n)*?(:?\*\/|-->)|(\/\/|#)(.*?)\n/g; var comments = /(:?\/\*|<!--)(:?.|\n)*?(:?\*\/|-->)|(\/\/|#)(.*?)\n/g;
@ -340,7 +372,7 @@ window.zerobin = {
var total = 0; var total = 0;
var size = 0; var size = 0;
var m = text.match(comments); var m = text.match(comments);
if (m){ if (m) {
total += text.match(comments).length; total += text.match(comments).length;
} }
text = text.replace(comments, ''); text = text.replace(comments, '');
@ -359,65 +391,96 @@ window.zerobin = {
}, },
// prevent defaults // prevent defaults
ignoreDrag: function(e) { ignoreDrag: function (e) {
e.originalEvent.stopPropagation(); e.originalEvent.stopPropagation();
e.originalEvent.preventDefault(); e.originalEvent.preventDefault();
}, },
// Handle Drop // Handle Drop
handleDrop: function(e) { handleDrop: function (e) {
zerobin.ignoreDrag(e); zerobin.ignoreDrag(e);
zerobin.upload(e.originalEvent.dataTransfer.files); zerobin.upload(e.originalEvent.dataTransfer.files);
$("#content").removeClass('hover'); $("#content").removeClass('hover');
}, },
handleDragOver: function(e) { handleDragOver: function (e) {
zerobin.ignoreDrag(e); zerobin.ignoreDrag(e);
$(this).addClass('hover'); $(this).addClass('hover');
}, },
handleDragLeave: function(e) { handleDragLeave: function (e) {
zerobin.ignoreDrag(e); zerobin.ignoreDrag(e);
$(this).removeClass('hover'); $(this).removeClass('hover');
}, },
upload: function(files) { upload: function (files) {
var current_file = files[0]; var current_file = files[0];
var reader = new FileReader(); var reader = new FileReader();
if(current_file.type.indexOf('image') == 0) { if (current_file.type.indexOf('image') == 0) {
reader.onload = function(event) { reader.onload = function (event) {
$('#content').val(event.target.result).trigger('change'); var image = new Image();
image.src = event.target.result;
image.onload = function() {
var maxWidth = 1024,
maxHeight = 1024,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
image.width = imageWidth;
image.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
var paste = canvas.toDataURL(current_file.type);
$('#content').val(paste).trigger('change');
$('#content').hide(); $('#content').hide();
var img = $('<img/>'); $(image).css('max-width', '742px');
$(img).attr('src', event.target.result); $('#content').after(image);
$(img).css('max-width', '742px'); }
$('#content').after(img); }
};
reader.readAsDataURL(current_file); reader.readAsDataURL(current_file);
} else { } else {
reader.onload = function(event) { reader.onload = function (event) {
$('#content').val(event.target.result).trigger('change'); $('#content').val(event.target.result).trigger('change');
}; };
reader.readAsText(current_file); reader.readAsText(current_file);
} }
} }
}; };
/*************************** /***************************
**** On document ready *** **** On document ready ***
****************************/ ****************************/
$(function(){ $(function () {
/** /**
On the create paste page: On the create paste page:
On click on the send button, compress and encrypt data before On click on the send button, compress and encrypt data before
posting it using ajax. Then redirect to the address of the posting it using ajax. Then redirect to the address of the
newly created paste, adding the key in the hash. newly created paste, adding the key in the hash.
*/ */
$('.btn-primary').live("click", function(e){ $('.btn-primary').live("click", function (e) {
e.preventDefault(); e.preventDefault();
var paste = $('textarea').val(); var paste = $('textarea').val();
@ -447,37 +510,38 @@ $('.btn-primary').live("click", function(e){
mkcb(bar.set, 'Encrypting...', '85%'), mkcb(bar.set, 'Encrypting...', '85%'),
/* This block deal with sending the data, redirection or error handling */ /* This block deal with sending the data, redirection or error handling */
function(content){ function (content) {
bar.set('Sending...', '95%'); bar.set('Sending...', '95%');
var data = {content: content, expiration: expiration}; var data = {
content: content,
expiration: expiration
};
var sizebytes = zerobin.count(JSON.stringify(data)); var sizebytes = zerobin.count(JSON.stringify(data));
var oversized = sizebytes > zerobin.max_size; // 100kb - the others header information var oversized = sizebytes > zerobin.max_size; // 100kb - the others header information
var readableFsize = Math.round(sizebytes / 1024); var readableFsize = Math.round(sizebytes / 1024);
var readableMaxsize = Math.round(zerobin.max_size / 1024); var readableMaxsize = Math.round(zerobin.max_size / 1024);
if(oversized) { if (oversized) {
bar.container.hide(); bar.container.hide();
$form.prop('disabled', false); $form.prop('disabled', false);
zerobin.message('error', zerobin.message('error', ('The encrypted file was <strong class="file-size">' + readableFsize +
('The encrypted file was <strong class="file-size">' + readableFsize + '</strong>KB. You have reached the maximum size limit of ' + readableMaxsize + 'KB.'),
'</strong>KB. You have reached the maximum size limit of '+readableMaxsize+'KB.'),
'Warning!', true); 'Warning!', true);
return; return;
} }
$.post('/paste/create', data) $.post('/paste/create', data)
.error(function(error) { .error(function (error) {
$form.prop('disabled', false); $form.prop('disabled', false);
bar.container.hide(); bar.container.hide();
zerobin.message( zerobin.message(
'error', 'error',
'Paste could not be saved. Please try again later.', 'Paste could not be saved. Please try again later.',
'Error' 'Error');
);
}) })
.success(function(data) { .success(function (data) {
bar.set('Redirecting to new paste...', '100%'); bar.set('Redirecting to new paste...', '100%');
if (data.status === 'error') { if (data.status === 'error') {
@ -486,14 +550,13 @@ $('.btn-primary').live("click", function(e){
bar.container.hide(); bar.container.hide();
} else { } else {
var paste_url = '/paste/' + data.paste + '#' + key; var paste_url = '/paste/' + data.paste + '#' + key;
if (zerobin.support.localStorage){ if (zerobin.support.localStorage) {
zerobin.storePaste(paste_url); zerobin.storePaste(paste_url);
} }
window.location = (paste_url); window.location = (paste_url);
} }
}); });
} });
);
} catch (err) { } catch (err) {
$form.prop('disabled', false); $form.prop('disabled', false);
bar.container.hide(); bar.container.hide();
@ -501,29 +564,29 @@ $('.btn-primary').live("click", function(e){
'Error'); 'Error');
} }
} }
}); });
/** /**
DECRYPTION: DECRYPTION:
On the display paste page, decrypt and decompress the paste content, On the display paste page, decrypt and decompress the paste content,
add syntax coloration then setup the copy to clipboard button. add syntax coloration then setup the copy to clipboard button.
Also calculate and set the paste visual hash. Also calculate and set the paste visual hash.
*/ */
var content = $('#paste-content').text().trim(); var content = $('#paste-content').text().trim();
var key = zerobin.getPasteKey(); var key = zerobin.getPasteKey();
var error = false; var error = false;
if (content && key) { if (content && key) {
/* Load the lib for visual canvas, create one from the paste id and /* Load the lib for visual canvas, create one from the paste id and
insert it */ insert it */
$.getScript("/static/js/vizhash.min.js").done(function(script, textStatus) { $.getScript("/static/js/vizhash.min.js").done(function (script, textStatus) {
if (vizhash.supportCanvas) { if (vizhash.supportCanvas) {
var vhash = vizhash.canvasHash(zerobin.getPasteId(), 24, 24); var vhash = vizhash.canvasHash(zerobin.getPasteId(), 24, 24);
$('<a class="vhash" href="#"></a>').click(function(e){ $('<a class="vhash" href="#"></a>').click(function (e) {
e.preventDefault(); e.preventDefault();
if(confirm("This picture is unique to your paste so you can identify" + if (confirm("This picture is unique to your paste so you can identify" +
" it quickly. \n\n Do you want to know more about this?")){ " it quickly. \n\n Do you want to know more about this?")) {
window.open("http://is.gd/IJaMRG", "_blank"); window.open("http://is.gd/IJaMRG", "_blank");
} }
}).prependTo('.lnk-option').append(vhash.canvas); }).prependTo('.lnk-option').append(vhash.canvas);
@ -539,7 +602,7 @@ if (content && key) {
zerobin.decrypt(key, content, zerobin.decrypt(key, content,
/* On error*/ /* On error*/
function(){ function () {
bar.container.hide(); bar.container.hide();
zerobin.message('error', 'Could not decrypt data (Wrong key ?)', 'Error'); zerobin.message('error', 'Could not decrypt data (Wrong key ?)', 'Error');
}, },
@ -550,12 +613,12 @@ if (content && key) {
mkcb(bar.set, 'From bits to string...', '85%'), mkcb(bar.set, 'From bits to string...', '85%'),
/* When done */ /* When done */
function(content){ function (content) {
/* Decrypted content goes back to initial container*/ /* Decrypted content goes back to initial container*/
$('#paste-content').text(content); $('#paste-content').text(content);
if(content.indexOf('data:image') == 0) { if (content.indexOf('data:image') == 0) {
// Display Image // Display Image
$('#paste-content').hide(); $('#paste-content').hide();
var img = $('<img/>'); var img = $('<img/>');
@ -567,7 +630,7 @@ if (content && key) {
$('.btn-clone').hide(); $('.btn-clone').hide();
var button = $('<a/>').attr('href', content); var button = $('<a/>').attr('href', content);
$(button).attr('download', '0bin_'+document.location.pathname.split('/').pop()); $(button).attr('download', '0bin_' + document.location.pathname.split('/').pop());
$(button).addClass('btn'); $(button).addClass('btn');
$(button).html('<i class="icon-download"></i> Download'); $(button).html('<i class="icon-download"></i> Download');
$('.btn-clone').after(button); $('.btn-clone').after(button);
@ -576,7 +639,7 @@ if (content && key) {
bar.set('Code coloration...', '95%'); bar.set('Code coloration...', '95%');
/* Add a continuation to let the UI redraw */ /* Add a continuation to let the UI redraw */
setTimeout(function() { setTimeout(function () {
/* Setup flash clipboard button */ /* Setup flash clipboard button */
ZeroClipboard.setMoviePath('/static/js/ZeroClipboard.swf'); ZeroClipboard.setMoviePath('/static/js/ZeroClipboard.swf');
@ -584,13 +647,15 @@ if (content && key) {
var clip = new ZeroClipboard.Client(); var clip = new ZeroClipboard.Client();
// Callback to reposition the clibpboad flash animation overlay // Callback to reposition the clibpboad flash animation overlay
var reposition = function(){clip.reposition();}; var reposition = function () {
clip.reposition();
};
clip.addEventListener('mouseup', function(){ clip.addEventListener('mouseup', function () {
$('#clip-button').text('Copying paste...'); $('#clip-button').text('Copying paste...');
clip.setText(zerobin.getPasteContent()); clip.setText(zerobin.getPasteContent());
}); });
clip.addEventListener('complete', function(){ clip.addEventListener('complete', function () {
$('#clip-button').text('Copy to clipboard'); $('#clip-button').text('Copy to clipboard');
zerobin.message('info', 'The paste is now in your clipboard', '', zerobin.message('info', 'The paste is now in your clipboard', '',
true, reposition); true, reposition);
@ -601,34 +666,33 @@ if (content && key) {
/* Setup link to get the paste short url*/ /* Setup link to get the paste short url*/
$('#short-url').click(function(e) { $('#short-url').click(function (e) {
e.preventDefault(); e.preventDefault();
$('#short-url').text('Loading short url...'); $('#short-url').text('Loading short url...');
zerobin.getTinyURL(window.location.toString(), function(tinyurl){ zerobin.getTinyURL(window.location.toString(), function (tinyurl) {
clip.setText(tinyurl); clip.setText(tinyurl);
$('#copy-success').hide(); $('#copy-success').hide();
zerobin.message('success', zerobin.message('success',
'<a href="' + tinyurl + '">' + tinyurl + '</a>', '<a href="' + tinyurl + '">' + tinyurl + '</a>',
'Short url', true, reposition 'Short url', true, reposition);
);
$('#short-url').text('Get short url'); $('#short-url').text('Get short url');
}); });
}); });
/* Remap the message close handler to include the clipboard /* Remap the message close handler to include the clipboard
flash reposition */ flash reposition */
$(".close").die().live('click', function(e){ $(".close").die().live('click', function (e) {
e.preventDefault(); e.preventDefault();
$(this).parent().fadeOut(reposition); $(this).parent().fadeOut(reposition);
}); });
/** Syntaxic coloration */ /** Syntaxic coloration */
if (zerobin.isCode(content) > 100){ if (zerobin.isCode(content) > 100) {
$('#paste-content').addClass('linenums'); $('#paste-content').addClass('linenums');
prettyPrint(); prettyPrint();
} else { } else {
if(content.indexOf('data:image') != 0){ if (content.indexOf('data:image') != 0) {
zerobin.message('info', zerobin.message('info',
"The paste did not seem to be code, so it " + "The paste did not seem to be code, so it " +
"was not colorized. " + "was not colorized. " +
@ -649,48 +713,46 @@ if (content && key) {
}, 250); }, 250);
} });
);
} /* End of "DECRYPTION" */ } /* End of "DECRYPTION" */
/* Synchronize expiration select boxes value */ /* Synchronize expiration select boxes value */
$('.paste-option select').live('change', function(){ $('.paste-option select').live('change', function () {
$('.paste-option select').val($(this).val()); $('.paste-option select').val($(this).val());
}); });
/* Resize Textarea according to content */ /* Resize Textarea according to content */
$('#content').elastic(); $('#content').elastic();
/* Display bottom paste option buttons when needed */ /* Display bottom paste option buttons when needed */
$('#content').live('keyup change', function(){ $('#content').live('keyup change', function () {
if($('#content').height() < 400 ){ if ($('#content').height() < 400) {
$('.paste-option.down').remove(); $('.paste-option.down').remove();
} } else {
else {
if ($('.paste-option').length === 1) { if ($('.paste-option').length === 1) {
$('.paste-option').clone().addClass('down').appendTo('form.well'); $('.paste-option').clone().addClass('down').appendTo('form.well');
} }
} }
}); });
/* Display previous pastes */ /* Display previous pastes */
if (zerobin.support.localStorage){ if (zerobin.support.localStorage) {
var $container = $('.previous-pastes'), var $container = $('.previous-pastes'),
pastes = zerobin.getPreviousPastes(); pastes = zerobin.getPreviousPastes();
if (pastes.length){ if (pastes.length) {
$.getScript("/static/js/vizhash.min.js").done(function(script, textStatus) { $.getScript("/static/js/vizhash.min.js").done(function (script, textStatus) {
$container.find('.item').remove(); $container.find('.item').remove();
$.each(zerobin.getPreviousPastes(), function(i, paste){ $.each(zerobin.getPreviousPastes(), function (i, paste) {
var $li = $('<li class="item"></li>').appendTo($container); var $li = $('<li class="item"></li>').appendTo($container);
var $link = $('<a></a>').attr('href', paste.link) var $link = $('<a></a>').attr('href', paste.link)
@ -705,9 +767,9 @@ if (zerobin.support.localStorage){
// hightlite the current link and make sure clicking the link // hightlite the current link and make sure clicking the link
// does redirect to the page // does redirect to the page
if (paste.link.replace(/#[^#]+/, '') === window.location.pathname){ if (paste.link.replace(/#[^#]+/, '') === window.location.pathname) {
$li.addClass('active'); $li.addClass('active');
$link.click(function(){ $link.click(function () {
window.location = $link.attr('href'); window.location = $link.attr('href');
window.location.reload(); window.location.reload();
}); });
@ -719,27 +781,27 @@ if (zerobin.support.localStorage){
} }
} }
/* Event handler for "clone paste" button */ /* Event handler for "clone paste" button */
$('.btn-clone').click(function(e){ $('.btn-clone').click(function (e) {
e.preventDefault(); e.preventDefault();
$('.submit-form').show(); $('.submit-form').show();
$('.paste-form').hide(); $('.paste-form').hide();
$('#content').val(zerobin.getPasteContent()).trigger('change'); $('#content').val(zerobin.getPasteContent()).trigger('change');
}); });
$('.clone .btn-danger').click(function(e){ $('.clone .btn-danger').click(function (e) {
e.preventDefault(); e.preventDefault();
$('.submit-form').hide(); $('.submit-form').hide();
$('.paste-form').show(); $('.paste-form').show();
}); });
/* Upload file using HTML5 File API */ /* Upload file using HTML5 File API */
if (zerobin.support.fileUpload) { if (zerobin.support.fileUpload) {
var $buttonOverlay = $('#file-upload'); var $buttonOverlay = $('#file-upload');
var $button = $('.btn-upload'); var $button = $('.btn-upload');
@ -747,9 +809,10 @@ if (zerobin.support.fileUpload) {
try { try {
$button.val('Uploading...'); $button.val('Uploading...');
$button.prop('disabled', true); $button.prop('disabled', true);
$buttonOverlay.change(function(){zerobin.upload(this.files);}); $buttonOverlay.change(function () {
} zerobin.upload(this.files);
catch (e) { });
} catch (e) {
zerobin.message('error', 'Could no upload the file', 'Error'); zerobin.message('error', 'Could no upload the file', 'Error');
$button.val('Upload File'); $button.val('Upload File');
$button.prop('disabled', false); $button.prop('disabled', false);
@ -766,60 +829,60 @@ if (zerobin.support.fileUpload) {
$('#content').bind('dragleave', zerobin.handleDragLeave); $('#content').bind('dragleave', zerobin.handleDragLeave);
} }
/* Alerts */ /* Alerts */
$(".close").live('click', function(e){ $(".close").live('click', function (e) {
e.preventDefault(); e.preventDefault();
$(this).parent().fadeOut(); $(this).parent().fadeOut();
}); });
/* Parse obfuscaded emails and make them usable */ /* Parse obfuscaded emails and make them usable */
$('.email-link').each(function(i, elem){ $('.email-link').each(function (i, elem) {
var $obfuscatedEmail = $(this); var $obfuscatedEmail = $(this);
var address = $obfuscatedEmail.attr('title').replace('__AT__', '@'); var address = $obfuscatedEmail.attr('title').replace('__AT__', '@');
var text = $obfuscatedEmail.text().replace('__AT__', '@'); var text = $obfuscatedEmail.text().replace('__AT__', '@');
var $plainTextEmail = $('<a href="mailto:' + address + '">'+ text +'</a>'); var $plainTextEmail = $('<a href="mailto:' + address + '">' + text + '</a>');
$obfuscatedEmail.replaceWith($plainTextEmail); $obfuscatedEmail.replaceWith($plainTextEmail);
}); });
/* Show the page using javascript. Non js enabled browser will see an /* Show the page using javascript. Non js enabled browser will see an
error message */ error message */
$('#wrap-content').each(function(i, elem){ $('#wrap-content').each(function (i, elem) {
$(elem).show(); $(elem).show();
}); });
/* Remove expired pasted from history */ /* Remove expired pasted from history */
if (zerobin.support.history && zerobin.paste_not_found){ if (zerobin.support.history && zerobin.paste_not_found) {
var paste_id = zerobin.getPasteId(); var paste_id = zerobin.getPasteId();
var keys = zerobin.getLocalStorageKeys(); var keys = zerobin.getLocalStorageKeys();
$.each(keys, function(i, key){ $.each(keys, function (i, key) {
if (localStorage[key].indexOf(paste_id) !== -1){ if (localStorage[key].indexOf(paste_id) !== -1) {
localStorage.removeItem(key); localStorage.removeItem(key);
return false; return false;
} }
}); });
} }
/* Force text coloration when clickin on link */ /* Force text coloration when clickin on link */
$("#force-coloration").live("click", function(e) { $("#force-coloration").live("click", function (e) {
e.preventDefault(); e.preventDefault();
$('#paste-content').addClass('linenums'); $('#paste-content').addClass('linenums');
$(this).die(e).text('Applying coloration'); $(this).die(e).text('Applying coloration');
prettyPrint(); prettyPrint();
$(this).remove(); $(this).remove();
}); });
/* Send the paste by email */ /* Send the paste by email */
var emailLink = 'mailto:friend@example.com?body=' + window.location; var emailLink = 'mailto:friend@example.com?body=' + window.location;
$('#email-link').attr('href', emailLink); $('#email-link').attr('href', emailLink);
}); /* End of "document ready" jquery callback */ }); /* End of "document ready" jquery callback */
})(); /* End of self executing function */ })(); /* End of self executing function */

File diff suppressed because one or more lines are too long