Skip to content

Commit

Permalink
Changes and additions.
Browse files Browse the repository at this point in the history
img2base64.js - changed.
1. Replace bb-code "xmg" to bb-code '[file name="filename.extension" type="mime-type"]BASE64-CONTENT[/file]'
Now any file can be uploaded, like on karasiq-nanoboard. Filename and mime-type extracting when file selected.
See lines 63, 76 and 122 in img2base64.js
2. Add some comments.

3. The page /pages/download_as_binary.html was been added - to download any base64 or dataURL, as binary file.

nanoclient.js - changed.
4. At line 1 was been added the function to check without throw error, is content - base64 encoded or not.
5. At line 106 was been added the cycle for extracting base64, filename and filetype
from '[file name="filename.extension" type="mime-type"]BASE64-CONTENT[/file]',
and replace this to link for downloading the file.
6. At line 172 was been added the link to download_as_binary.html with base64 encoded png icon.
This code can be commented if you don't see any sense with this.
7. Old code saved at line 193.
8. Add comment at line 206.

[xmg] - tags still supported and working, but not adding now.
See: Karasiq/nanoboard#5

If anyone cann't download any file, you can using download_as_binary.html
Just download this, put in 'pages', and open http://127.0.0.1:7346/pages/download_as_binary.html
_________________________
Have a nice day.
  • Loading branch information
username1565 authored Feb 1, 2019
1 parent 95fe9c4 commit 4325a23
Show file tree
Hide file tree
Showing 3 changed files with 170 additions and 5 deletions.
68 changes: 68 additions & 0 deletions pages/download_as_binary.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<h1>Download base64 or dataURL - as binary file.</h1>
Base64 or dataURL:<br>
<textarea id="base64" rows="5" cols="50" placeholder="Paste here the base64 or dataURL"></textarea>
<br>
filename.extension: <input id="filename" type="text" placeholder="filename.extension" onclick="this.focus();this.select();">
<button onclick="download_as_binary()">Download as binary...</button>
<br>
<br>
<div id="download_link"></div>
<script>
//Function for checking, without throw error, is str base64-encoded or not. return true/false.
function isBase64(str) {
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}

function is_dataURL(str){
return (str.indexOf('data:')!==-1 && str.indexOf('base64,')!==-1 && isBase64(str.split('base64,')[1]));
}

function download_as_binary(){
var result_div = document.getElementById('download_link'); //get div with result link
result_div.innerHTML = ''; //clear this

var textarea = document.getElementById('base64'); //get textarea
var maybe_base = textarea.value; //get value from this
var filename = document.getElementById('filename').value || undefined; //set filename or undefined
if(typeof filename==='undefined'){ //if still undefined
//generate random filename
var len = 20;/*<--String Length ...*/for(var s = "", rem = 100000000, n = Math.random()*10*rem; s.length < len;){rem=10*rem%n; s+= (rem%10!==0)?rem.toString(36).replace(".", "").substr(0, len-s.length):"";}//document.write("<br>", 's.length: ', s.length, 's: ', s);
filename = s;
}
filename = filename+((filename.indexOf('.')==-1)?'.bin':''); //if filename was generated

if(maybe_base===''){
result_div.innerHTML = 'Empty textarea';
return false;
}else if(maybe_base.trim()===''){
result_div.innerHTML = 'Empty trimmed textarea';
return false;
}
if(is_dataURL(maybe_base)){
maybe_base = maybe_base.split(',')[1];
}
var attempt = 0;

while(true){
if(attempt>=2){ //trimmed textarea value - not base64
//break; //exit from cycle
result_div.innerHTML = 'Trimmed textarea value - not base64.';
return false; //exit from function
}else if(isBase64(maybe_base) && attempt<2){ //try without trim textarea value
var result = 'Download <a href="data:application/octet-stream;base64,'+maybe_base+'" download="'+filename+'">'+filename+'</a>';
result_div.innerHTML = result;
break;
}else if(is_dataURL(maybe_base)){
maybe_base = maybe_base.split(',')[1];
}else{
result_div.innerHTML = 'Base64 not found in textarea value. Try trim this...';
maybe_base = maybe_base.trim();
attempt++;
}
}
}
</script>
7 changes: 4 additions & 3 deletions scripts/img2base64.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ var _loader=$('#inputFileToLoad')[0];

function updateImage(loader) {
_loader = loader;
var file = _loader.files[0];
var file = _loader.files[0]; //After selection file, the filename available in - file.name; filetype in - file.type.
var reader = new FileReader();
reader.onloadend = function() {
var res = reader.result;
Expand All @@ -72,7 +72,8 @@ function updateImage(loader) {
$('.output').find('img').attr('src', 'error');
$('#info').css('color','red');
} else {
$('#result').text('[xmg='+res.substring(res.indexOf(',')+1)+']');
// $('#result').text('[xmg='+res.substring(res.indexOf(',')+1)+']'); //old code with bb-code xmg
$('#result').text('[file name="'+file.name+'" type="'+file.type+'"]'+res.substring(res.indexOf(',')+1)+'[/file]'); //bb-code file, with filename and mime-type, like in karasiq-nanoboard.
$('.output').find('img').attr('src', res);
$('#info').css('color','black');
}
Expand Down Expand Up @@ -118,7 +119,7 @@ function updateImage(loader) {
$('#result').text('error');
} else {
$('#info').css('color','black');
$('#result').text('[xmg='+dataURL.substring(dataURL.indexOf(',')+1)+']');
$('#result').text('[xmg='+dataURL.substring(dataURL.indexOf(',')+1)+']'); //saving backward compatibility with old zipJPEGs and bb-code xmg.
}
};
var shrd = canvas.toDataURL();
Expand Down
100 changes: 98 additions & 2 deletions scripts/nanoclient.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
//Function for checking, without throw error, is str base64-encoded or not. return true/false.
function isBase64(str) {
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}

function numSuffix(numStr) {
if (numStr.endsWith('11')) return 's';
if (numStr.endsWith('1')) return '';
Expand Down Expand Up @@ -93,9 +102,96 @@ function addPost(post, appendFunc, hasShowButton, short) {
}, _post_delete_timeout);
}));
appendFunc(d);

//This code need function isBase64(str), and this function in beginning of this script
var post_content = escapeTags(Base64.decode(post.message));
//console.log(post_content);

//detect files
if(post_content.indexOf('[file')!==-1){ //if bb-code "file" found
var files_array = post_content.split('[file'); //split by file
//console.log('files_array', files_array); //show array in console
for(i=1;i<files_array.length;i++){ //for each element up to array length
//console.log('files_array[i]', files_array[i]); //show element
var maybe_base = files_array[i].split('"]')[1].split('[/file]')[0]; //split by '"]', and "[/file]" to get base64
if(isBase64(maybe_base)){ //check is base64
//console.log('base64!'); //if yes - show notification in console
//console.log('base64! maybe_base: ', maybe_base); //with base64
//and try to replace file to download link...
var split_by_base = post_content.split(maybe_base); //split post by this base64
var before_base = split_by_base[0]; //here contains previous part of post and filename with filetype
var split_by_file = before_base.split('[file'); //split by '[file'. In the second element must be filename and filetype.

var check_filename_regexp = /^[-\w^&'@{}[\],$=!#().%+~ ]+$/; //regexp to test is filename correct?

var part = 1; //first part of array is 1 must contains filename and filetype
var filename = split_by_file[part].split('name="')[1].split('"')[0]; //set filename by splitting this by 'name="' and '"'
//console.log('filename', filename); //show this
var filetype = split_by_file[part].split('type="')[1].split('"')[0]; //set filetype by splitting this by 'type="' and '"'
//console.log('filetype', filetype); //show filetype


while(true){ //cycle without end
//if(typeof split_by_file[part+1]=='undefined'){break;} //if no any element - break
if(!check_filename_regexp.test(filename)){ //if no filename there
part++; //check next part of splitted post
filename = split_by_file[part].split('name="')[1].split('"')[0]; //get filename
//console.log('filename', filename); //show this
filetype = split_by_file[part].split('type="')[1].split('"')[0]; //get filetype
//console.log('filetype', filetype); //show this.
continue; //and continue cycle without running next code...
}

//exception for post 946d50e33c413a93d7c963424e0846d9, where is code contains "[file"
if(filename==="'+file.name+'" && filetype === "'+file.type+'"){ //if filename and filetype as in the code
part++; //check next part of splitted string
filename = split_by_file[part].split('name="')[1].split('"')[0]; //get filename
//console.log('filename', filename); //show this
filetype = split_by_file[part].split('type="')[1].split('"')[0]; //get filetype
//console.log('filetype', filetype); //show this
continue; //and continue cycle, without running next code...
}

else{ //else, if not code and filename exist and valid...
// console.log( //show checking results
// "(check_filename_regexp.test(filename))",
// (check_filename_regexp.test(filename)),
// "(filename==='+file.name+' && filetype === '+file.type+')",
// (filename==='+file.name+' && filetype === '+file.type+'),
// 'part', part
// );
break; //and break from cycle...
}
}
//when filename and filetype is valid...

//build link to download this file.
var html_link = '<a href="data:'+filetype+';base64,'+maybe_base+'" download="'+filename+'">['+filename+']</a>'
//and add link to download this as binary,
//with green base64 encoded PNG image to this link.
+'<a href="/pages/download_as_binary.html" target="_blank"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/\
9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABCElEQVQ4jZ3TMUoDQRjF8V+SRURExQN4Ai+gFkkjegqxsQwSQcQiMGgrIugJvEB6beIRcgUPIBoExSJY7MRk\
18kG/WBZ9r3v/75hZqcmVcEBLrESlSG6gvtyay0BL+ANiyXnE6uCr2mxnpifJWBRy8piKiClzfSqmv8d8KcVTDYx2MBafJ5mBDTxilfBcznxEIMKWPQGOE\
ot6QLXFfC47tAdfzR+5D5aHuQ/z1YF3BYmQqNgT0KWsT0PzgOCfS0v+j6mQh6xhJ3Yd4PjAhysa2nW0cNmITZvPMMpztEpT45ML8NI6uxz4OqXXqxRJr9p\
u/GSjMbGDKA+9d7DMEMHtziZM61c72h/A3foMuoBqRh/AAAAAElFTkSuQmCC"></a>';

//console.log('html_link', html_link); //show this link...

post_content = post_content.split('[file name="'+filename+'" type="'+filetype+'"]'+maybe_base+'[/file]').join(html_link); //and replace bb-code file to this link.

//console.log('post_content: ', post_content); //show results...
}else{ //not base64 in the middle of [file][/file]
//console.log('not base64', maybe_base); //do nothing
}
//and continue replace files to links in all post, splitted by file-tag, again and again...
}
//console.log('post_content: ', post_content); //show post in the end and continue script
}//or continue script without replacing...

var inner = $('<div>')
.addClass('post-inner')
.html(applyFormatting(escapeTags(Base64.decode(post.message))))
// .html(applyFormatting(escapeTags(Base64.decode(post.message)))) //old code
.html(applyFormatting(post_content)) //<--- HERE using replaced contend of post
.appendTo(d);
detectPlacesCommands(inner);
d.find('img').click(function(){
Expand All @@ -107,7 +203,7 @@ function addPost(post, appendFunc, hasShowButton, short) {
if (imgcnt > 0) {
for (var i = 0; i < imgcnt; i++) {
var img = imgs[i];
if (img.src.startsWith('data:image/jpeg;base64,UEsDB')) {
if (img.src.startsWith('data:image/jpeg;base64,UEsDB')) {//if PK at first - then zip //saving backward compatibility with old zipJPEGs
$(img).replaceWith($('<a download=file'+(i+1)+'.zip href='+img.src.replace('image/jpeg','application/zip')+'>[file'+(i+1)+'.zip]</a>'));
}
}
Expand Down

1 comment on commit 4325a23

@username1565
Copy link
Owner Author

@username1565 username1565 commented on 4325a23 Feb 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BB-code '[FILE name="filename" type="filetype"]BASE-64[/file]' nanoboard#6

Please sign in to comment.