Commit b5ef611c authored by Cédric Le Ninivin's avatar Cédric Le Ninivin

Added jIO, possibility to save and load cache content from indexdb

parent e161dacb
...@@ -24,7 +24,10 @@ if ('serviceWorker' in navigator) { ...@@ -24,7 +24,10 @@ if ('serviceWorker' in navigator) {
document.querySelector('#status').appendChild(aElement); document.querySelector('#status').appendChild(aElement);
} }
jio = jIO.createJIO({
type: "indexeddb",
database: "cribjs"
})
function setStatus(statusMessage) { function setStatus(statusMessage) {
document.querySelector('#status').textContent = statusMessage; document.querySelector('#status').textContent = statusMessage;
...@@ -75,6 +78,7 @@ function showCommands() { ...@@ -75,6 +78,7 @@ function showCommands() {
}); });
document.querySelector('#get').addEventListener('click', function() { document.querySelector('#get').addEventListener('click', function() {
console.log("bar");
getContent(document.querySelector('#url').value, getContent(document.querySelector('#url').value,
function() { function() {
document.querySelector('#mimetype').value = this.getResponseHeader("content-type"); document.querySelector('#mimetype').value = this.getResponseHeader("content-type");
...@@ -84,23 +88,89 @@ function showCommands() { ...@@ -84,23 +88,89 @@ function showCommands() {
}) })
document.querySelector('#save-contents').addEventListener('click', function() { document.querySelector('#save-contents').addEventListener('click', function() {
console.log('asking for the keys');
sendMessage({ sendMessage({
command: 'keys' command: 'keys'
}).then(function(data) { }).then(function(data) {
// Add each cached URL to the list, one by one. // Add each cached URL to the list, one by one.
data.urls.forEach(function(url) { console.log("foo");
getContent(url, return new RSVP.Queue()
function(){ .push(function(){
var url_content = {'content_type': '', 'content':''}; console.log("put");
url_content.content_type = this.getResponseHeader("content-type"); return jio.put("cribjs", {})
url_content.content = this.responseText; })
localStorage.setItem(url, url_content); .push(function(){
} var promise_list = [], i, i_len, url;
); for (i = 0, i_len = data.urls.length; i < i_len; i += 1) {
}); url = new String(data.urls[i]);
console.log(url);
promise_list.push(jIO.util.ajax({'url': url, dataType: "blob"}))
};
return RSVP.all(promise_list)
})
.push(function (response_list) {
console.log(response_list);
var promise_list = [], i, i_len, url, response;
for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
response = response_list[i];
promise_list.push(
jio.putAttachment('cribjs', response.target.responseURL,
response.target.response
)
);
};
return RSVP.all(promise_list)
})
.push(undefined, function (error) {
console.log( error );
});
}).catch(setStatus); // If the promise rejects, then setStatus will be called with the error. }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
}); });
document.querySelector('#load-contents').addEventListener('click', function() {
console.log('asking for the keys');
var url_list = [];
return new RSVP.Queue()
.push(function(){
console.log("put");
return jio.allAttachments("cribjs")
})
.push(function(response){
var promise_list = [], key;
for (key in response) {
if (response.hasOwnProperty(key)) {
console.log(key);
url_list.push(key)
promise_list.push(jio.getAttachment("cribjs", key));
}
};
return RSVP.all(promise_list)
})
.push(function (response_list) {
var promise_list = [], i, i_len, url, index, response, location, location_len;
location = document.location.origin;
location_len = location.length
console.log(url_list);
console.log(response_list);
for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
url = url_list[i]
index = url.indexOf(location);
if(index != -1)
url = url.substr(index + location_len);
sendMessage({
command: 'add',
url: 'crib' + url,
information: response_list[i]
})
}
})
.push(undefined, function (error) {
console.log( error );
});
});
document.querySelector('#commands').style.display = 'block'; document.querySelector('#commands').style.display = 'block';
} }
......
...@@ -8,21 +8,25 @@ ...@@ -8,21 +8,25 @@
<meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=device-width">
<title>Service worker demo</title> <title>Service worker demo</title>
<script src="lib/sha256.js"></script>
<script src="lib/sha256.amd.js"></script>
<script src="lib/rsvp.js"></script>
<script src="lib/utils/promise.js"></script>
<script src="lib/jio-latest.js"></script>
<!--[if lt IE 9]> <!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> <![endif]-->
</head> </head>
<body> <body>
<h1>Free Web Initiative with CribJS: Start your Website</h1> <h1>Free Web Initiative: Start your Website</h1>
<p>You can start building this website by editing the content of the input here:</p> <p>You can start building this website by editing the content of the input here:</p>
<ul> <ul>
<li>First field: the path</li> <li>First field: the path</li>
<li>First field: mimetype</li> <li>First field: mimetype</li>
<li>First field: the content</li> <li>First field: the content</li>
</ul> </ul>
<p>Have fun building the web :)</p> <p>Have fun building the web :) <a href="todo.html">TODO</a></p>
<div class="output"> <div class="output">
<div id="status"></div> <div id="status"></div>
...@@ -50,4 +54,4 @@ ...@@ -50,4 +54,4 @@
<script src="app.js"></script> <script src="app.js"></script>
</body> </body>
</html> </html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Service worker demo</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>Free Web Initiative with CribJS: Start your Website</h1>
<p>You can start building this website by editing the content of the input here:</p>
<ul>
<li>First field: the path</li>
<li>First field: mimetype</li>
<li>First field: the content</li>
</ul>
<p>Have fun building the web :)</p>
<div class="output">
<div id="status"></div>
<div id="commands" style="display: none">
<div>
<label for="url">Resource URL:</label>
<input id="url" type="text" size="50" value="test.html">
<button id="get">Get from Cache</button>
<input id="mimetype" type="text" size="50" value="text/html">
<div>
<textarea id="information" cols="35" wrap="soft"></textarea>
</div>
<div>
<button id="add">Add to Cache</button>
<button id="delete">Delete from Cache</button>
</div>
<div>
<button id="list-contents">List Cache Contents</button>
<button id="save-contents">Save Cache</button>
<button id="load-contents">Load Cache</button>
</div>
<ul id="contents"></ul>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
\ No newline at end of file
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js', {scope: './'}).then(function() {
// Registration was successful. Now, check to see whether the Service Worker is controlling the page.
if (navigator.serviceWorker.controller) {
// If .controller is set, then this page is being actively controlled by the Service Worker.
// Show the interface for sending messages to the service worker.
showCommands();
} else {
// If .controller isn't set, then prompt the user to reload the page so that the Service Worker can take
// control. Until that happens, the Service Worker's message handler won't be used.
document.querySelector('#status').textContent =
'Please reload this page to allow the service worker to take control.';
}
}).catch(function(error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
document.querySelector('#status').textContent = error;
});
} else {
// The current browser doesn't support Service Workers.
var aElement = document.createElement('a');
aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
aElement.textContent = 'Service Workers are not supported in the current browser.';
document.querySelector('#status').appendChild(aElement);
}
function setStatus(statusMessage) {
document.querySelector('#status').textContent = statusMessage;
}
function showCommands() {
document.querySelector('#add').addEventListener('click', function() {
var url = document.querySelector('#url').value;
sendMessage({
command: 'add',
url: url,
information: new Blob([document.querySelector('#information').value], {
type: document.querySelector('#mimetype').value
})
}).then(function() {
// If the promise resolves, just display a success message.
setStatus('Added to cache: ' + url + ' at ' +Date());
}).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
});
document.querySelector('#delete').addEventListener('click', function() {
sendMessage({
command: 'delete',
url: document.querySelector('#url').value
}).then(function() {
// If the promise resolves, just display a success message.
setStatus('Deleted from cache.');
}).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
});
document.querySelector('#list-contents').addEventListener('click', function() {
sendMessage({
command: 'keys'
}).then(function(data) {
var contentsElement = document.querySelector('#contents');
// Clear out the existing items from the list.
while (contentsElement.firstChild) {
contentsElement.removeChild(contentsElement.firstChild);
}
// Add each cached URL to the list, one by one.
data.urls.forEach(function(url) {
var liElement = document.createElement('li');
liElement.textContent = url;
contentsElement.appendChild(liElement);
});
}).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
});
document.querySelector('#get').addEventListener('click', function() {
getContent(document.querySelector('#url').value,
function() {
document.querySelector('#mimetype').value = this.getResponseHeader("content-type");
document.querySelector('#information').value = this.responseText;
}
);
})
document.querySelector('#save-contents').addEventListener('click', function() {
sendMessage({
command: 'keys'
}).then(function(data) {
// Add each cached URL to the list, one by one.
data.urls.forEach(function(url) {
getContent(url,
function(){
var url_content = {'content_type': '', 'content':''};
url_content.content_type = this.getResponseHeader("content-type");
url_content.content = this.responseText;
localStorage.setItem(url, url_content);
}
);
});
}).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
});
document.querySelector('#commands').style.display = 'block';
}
function sendMessage(message) {
// This wraps the message posting/response in a promise, which will resolve if the response doesn't
// contain an error, and reject with the error if it does. If you'd prefer, it's possible to call
// controller.postMessage() and set up the onmessage handler independently of a promise, but this is
// a convenient wrapper.
return new Promise(function(resolve, reject) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
// This sends the message data as well as transferring messageChannel.port2 to the service worker.
// The service worker can then use the transferred port to reply via postMessage(), which
// will in turn trigger the onmessage handler on messageChannel.port1.
// See https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
});
}
function getContent(url, reqListener) {
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", url, true);
oReq.send();
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
(function (dependencies, module) {
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
if (typeof exports === 'object') {
return module(exports);
}
module(window);
}(['exports'], function (window) {
/* A JavaScript implementation of the Secure Hash Algorithm, SHA-256
* Version 0.3 Copyright Angel Marin 2003-2004 - http://anmar.eu.org/
* Distributed under the BSD License
* Some bits taken from Paul Johnston's SHA-1 implementation
*/
(function () {
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
function safe_add (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function S (X, n) {return ( X >>> n ) | (X << (32 - n));}
function R (X, n) {return ( X >>> n );}
function Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}
function Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}
function Sigma0256(x) {return (S(x, 2) ^ S(x, 13) ^ S(x, 22));}
function Sigma1256(x) {return (S(x, 6) ^ S(x, 11) ^ S(x, 25));}
function Gamma0256(x) {return (S(x, 7) ^ S(x, 18) ^ R(x, 3));}
function Gamma1256(x) {return (S(x, 17) ^ S(x, 19) ^ R(x, 10));}
function newArray (n) {
var a = [];
for (;n>0;n--) {
a.push(undefined);
}
return a;
}
function core_sha256 (m, l) {
var K = [0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2];
var HASH = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19];
var W = newArray(64);
var a, b, c, d, e, f, g, h, i, j;
var T1, T2;
/* append padding */
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
for ( var i = 0; i<m.length; i+=16 ) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3];
e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for ( var j = 0; j<64; j++) {
if (j < 16) {
W[j] = m[j + i];
} else {
W[j] = safe_add(safe_add(safe_add(Gamma1256(
W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
}
T1 = safe_add(safe_add(safe_add(
safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safe_add(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safe_add(d, T1);
d = c; c = b; b = a; a = safe_add(T1, T2);
}
HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]);
HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]);
HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]);
HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
}
return HASH;
}
function str2binb (str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
return bin;
}
function binb2hex (binarray) {
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
function hex_sha256(s){
return binb2hex(core_sha256(str2binb(s),s.length * chrsz));
}
window.hex_sha256 = hex_sha256;
}());
}));
(function (dependencies, module) {
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
if (typeof exports === 'object') {
return module(exports);
}
module(window);
}(['exports'], function (window) {
/* A JavaScript implementation of the Secure Hash Algorithm, SHA-256
* Version 0.3 Copyright Angel Marin 2003-2004 - http://anmar.eu.org/
* Distributed under the BSD License
* Some bits taken from Paul Johnston's SHA-1 implementation
*/
(function () {
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
function safe_add (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function S (X, n) {return ( X >>> n ) | (X << (32 - n));}
function R (X, n) {return ( X >>> n );}
function Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}
function Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}
function Sigma0256(x) {return (S(x, 2) ^ S(x, 13) ^ S(x, 22));}
function Sigma1256(x) {return (S(x, 6) ^ S(x, 11) ^ S(x, 25));}
function Gamma0256(x) {return (S(x, 7) ^ S(x, 18) ^ R(x, 3));}
function Gamma1256(x) {return (S(x, 17) ^ S(x, 19) ^ R(x, 10));}
function newArray (n) {
var a = [];
for (;n>0;n--) {
a.push(undefined);
}
return a;
}
function core_sha256 (m, l) {
var K = [0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2];
var HASH = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19];
var W = newArray(64);
var a, b, c, d, e, f, g, h, i, j;
var T1, T2;
/* append padding */
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
for ( var i = 0; i<m.length; i+=16 ) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3];
e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for ( var j = 0; j<64; j++) {
if (j < 16) {
W[j] = m[j + i];
} else {
W[j] = safe_add(safe_add(safe_add(Gamma1256(
W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
}
T1 = safe_add(safe_add(safe_add(
safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safe_add(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safe_add(d, T1);
d = c; c = b; b = a; a = safe_add(T1, T2);
}
HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]);
HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]);
HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]);
HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
}
return HASH;
}
function str2binb (str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
return bin;
}
function binb2hex (binarray) {
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
function hex_sha256(s){
return binb2hex(core_sha256(str2binb(s),s.length * chrsz));
}
window.hex_sha256 = hex_sha256;
}());
}));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment