aboutsummaryrefslogtreecommitdiffstats
path: root/jsaccess/jsa/jsa.js
blob: 45030f8dae40ec179c47e3299b50af2157682a11 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* jsaccess - download and decrypt files in the browser
 * 2013, Laurent Ghigonis <laurent@gouloum.fr> */

/* Reference code */
//console.log(JSON.stringify(xhr));

/* Called on "body" load */
function jsainit() {
	/* XXX get content of jsa/files/ directory to present
	   a list to the user */
}

/* Called on "Download" click */
function jsadl() {
	document.getElementById('status').innerHTML = "";
	var pass = document.getElementById('password').value;
	var file = $('input[name=files]:checked').val();
	
	obj = _dl(file, pass);
}

function _dl(file, pass) {
	window.URL = window.URL || window.webkitURL;
	_status("Downloading \""+file+"\" ...");

	dlreq = $.ajax({
		url: 'files/' + file,
		beforeSend: function ( xhr ) {
			xhr.overrideMimeType("application/base64");
		}
	}).done(function ( data ) {
		_status("Download complete, decrypting ...");
		_decrypt(data, pass, file);
	});
}

function _decrypt(obj, pass, name) {
	try {
		var decrypted = GibberishAES.dec(obj, pass);
	} catch(err) {
		_status(err.toString());
	}
	out = $.base64.decode(decrypted.toString());
	_status("Decrypted successfuly, saving ...");
	_save(out, name);
}

function _save(obj, name) {
	var ab = new ArrayBuffer(obj.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < obj.length; i++) {
		ia[i] = obj.charCodeAt(i);
	}
	var blob = new Blob([ia], {type:"application/octet-binary"});
	saveAs(blob, name);
	_status("File \""+name+"\" saved.");
	_status("Have a good day.");
}

function _status(txt) {
	var div = document.getElementById('status');
	div.innerHTML = div.innerHTML + '<br/>' + txt;
}