1
0
Fork 0
mirror of https://github.com/futurepress/epub.js.git synced 2025-10-03 14:59:18 +02:00

added loading from zipped epub file

This commit is contained in:
Fred Chasen 2013-01-26 21:01:14 -08:00
parent 2ddae3a024
commit 1e592badd1
13 changed files with 288 additions and 57 deletions

BIN
.DS_Store vendored

Binary file not shown.

View file

@ -173,6 +173,15 @@ input:-moz-placeholder {
top: 10%; top: 10%;
opacity: .15; opacity: .15;
box-shadow: -2px 0 15px rgba(0, 0, 0, 1); box-shadow: -2px 0 15px rgba(0, 0, 0, 1);
display: none;
}
#loader {
position: absolute;
z-index: 10;
left: 50%;
top: 50%;
margin: -33px 0 0 -33px;
} }
#toc { #toc {

View file

@ -33,6 +33,7 @@ FPR.app.init = (function($){
//-- Full list of event are at start of book.js //-- Full list of event are at start of book.js
Book.listen("book:metadataReady", meta); Book.listen("book:metadataReady", meta);
Book.listen("book:tocReady", toc); Book.listen("book:tocReady", toc);
Book.listen("book:bookReady", bookReady);
Book.listen("book:chapterReady", chapterChange); Book.listen("book:chapterReady", chapterChange);
Book.listen("book:online", goOnline); Book.listen("book:online", goOnline);
Book.listen("book:offline", goOffline); Book.listen("book:offline", goOffline);
@ -115,6 +116,15 @@ FPR.app.init = (function($){
return $container; return $container;
} }
function bookReady(){
var $divider = $("#divider"),
$loader = $("#loader");
$loader.hide();
$divider.show();
}
function goOnline(){ function goOnline(){
var $icon = $("#store"); var $icon = $("#store");
offline = false; offline = false;

View file

@ -1,4 +1,4 @@
FP.Book = function(elem, bookUrl){ FP.Book = function(elem, bookPath){
//-- Takes a string or a element //-- Takes a string or a element
if (typeof elem == "string") { if (typeof elem == "string") {
@ -36,8 +36,8 @@ FP.Book = function(elem, bookUrl){
this.determineStorageMethod(); this.determineStorageMethod();
// BookUrl is optional, but if present start loading process // BookUrl is optional, but if present start loading process
if(bookUrl) { if(bookPath) {
this.display(bookUrl); this.display(bookPath);
} }
@ -73,29 +73,65 @@ FP.Book.prototype.listeners = function(){
} }
//-- Check bookUrl and start parsing book Assets or load them from storage //-- Check bookUrl and start parsing book Assets or load them from storage
FP.Book.prototype.start = function(bookUrl){ FP.Book.prototype.start = function(bookPath){
var pathname = window.location.pathname, var pathname = window.location.pathname,
folder = (pathname[pathname.length - 1] == "/") ? pathname : "/"; folder = (pathname[pathname.length - 1] == "/") ? pathname : "/";
this.bookUrl = (bookUrl[bookUrl.length - 1] == "/") ? bookUrl : bookUrl + "/"; this.bookPath = bookPath;
if(this.bookUrl.search("://") == -1){
//-- get full path
this.bookUrl = window.location.origin + folder + this.bookUrl;
}
//-- TODO: Checks if the url is a zip file and unpack //-- Checks if the url is a zip file and unpack
if(this.isContained(bookUrl)){ if(this.isContained(bookPath)){
console.error("Zipped!"); this.bookUrl = "";
this.contained = true;
this.tell("book:offline");
if(this.online) this.unarchive(bookPath);
return;
}else{
this.bookUrl = (bookPath[bookPath.length - 1] == "/") ? bookPath : bookPath + "/";
if(this.bookUrl.search("://") == -1){
//-- get full path
this.bookUrl = window.location.origin + folder + this.bookUrl;
}
} }
if(!this.isSaved()){ if(!this.isSaved()){
if(!this.online) {
console.error("Not Online");
return;
}
//-- Gets the root of the book and url of the opf //-- Gets the root of the book and url of the opf
this.parseContainer(function(){ this.parseContainer();
//-- Gets all setup of the book from xml file
//-- TODO: add promise for this instead of callback? }else{
//this.parseContents(); //-- Events for elements loaded from storage
}); this.tell("book:tocReady");
this.tell("book:metadataReady");
this.tell("book:spineReady");
//-- Info is saved, start display
this.startDisplay();
}
}
FP.Book.prototype.unarchive = function(bookPath){
var unzipped;
//-- TODO: make more DRY
if(!this.isSaved()){
unzipped = new FP.Unarchiver(bookPath, function(){
FP.storage.get("META-INF/container.xml", function(url){
this.parseContainer(url);
}.bind(this));
}.bind(this));
}else{ }else{
//-- Events for elements loaded from storage //-- Events for elements loaded from storage
@ -111,13 +147,13 @@ FP.Book.prototype.start = function(bookUrl){
FP.Book.prototype.isSaved = function(force) { FP.Book.prototype.isSaved = function(force) {
//-- If url or version has changed invalidate stored data and reset //-- If url or version has changed invalidate stored data and reset
if (localStorage.getItem("bookUrl") != this.bookUrl || if (localStorage.getItem("bookPath") != this.bookPath ||
localStorage.getItem("fpjs-version") != FP.VERSION || localStorage.getItem("fpjs-version") != FP.VERSION ||
force == true) { force == true) {
localStorage.setItem("fpjs-version", FP.VERSION); localStorage.setItem("fpjs-version", FP.VERSION);
localStorage.setItem("bookUrl", this.bookUrl); localStorage.setItem("bookPath", this.bookPath);
localStorage.setItem("spinePos", 0); localStorage.setItem("spinePos", 0);
localStorage.setItem("stored", 0); localStorage.setItem("stored", 0);
@ -193,9 +229,10 @@ FP.Book.prototype.resizeIframe = function(e, cWidth, cHeight){
this.iframe.width = width; this.iframe.width = width;
} }
FP.Book.prototype.parseContainer = function(callback){ FP.Book.prototype.parseContainer = function(path){
var that = this, var that = this,
url = this.bookUrl + "META-INF/container.xml"; url = path || this.bookUrl + "META-INF/container.xml";
FP.core.loadXML(url, function(container){ FP.core.loadXML(url, function(container){
var fullpath; var fullpath;
@ -205,21 +242,35 @@ FP.Book.prototype.parseContainer = function(callback){
fullpath = rootfile.getAttribute('full-path').split("/"); fullpath = rootfile.getAttribute('full-path').split("/");
that.basePath = that.bookUrl + fullpath[0] + "/"; that.basePath = that.bookUrl + fullpath[0] + "/";
that.contentsPath = fullpath[1];
if(that.contained){
that.basePath = fullpath[0] + "/";
}
that.contentsPath = that.basePath + fullpath[1];
localStorage.setItem("basePath", that.basePath); localStorage.setItem("basePath", that.basePath);
localStorage.setItem("contentsPath", that.contentsPath); localStorage.setItem("contentsPath", that.contentsPath);
//-- Now that we have the path we can parse the contents //-- Now that we have the path we can parse the contents
//-- TODO: move this and handle errors //-- TODO: move this and handle errors
that.parseContents(that.contentsPath);
if(that.contained){
FP.storage.get(that.contentsPath, function(url){
that.parseContents(url);
});
}else{
//-- Gets the root of the book and url of the opf
that.parseContents();
}
}); });
} }
FP.Book.prototype.parseContents = function(){ FP.Book.prototype.parseContents = function(path){
var that = this, var that = this,
url = this.basePath + this.contentsPath; url = path || this.contentsPath;
FP.core.loadXML(url, function(contents){ FP.core.loadXML(url, function(contents){
var metadata = contents.querySelector("metadata"), var metadata = contents.querySelector("metadata"),
@ -265,7 +316,14 @@ FP.Book.prototype.parseManifest = function(manifest){
//-- Find NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" //-- Find NCX: media-type="application/x-dtbncx+xml" href="toc.ncx"
if(item.getAttribute('media-type') == "application/x-dtbncx+xml"){ if(item.getAttribute('media-type') == "application/x-dtbncx+xml"){
that.parseTOC(href); if(that.contained){
FP.storage.get(that.basePath + href, function(url){
that.parseTOC(url);
});
}else{
that.parseTOC(that.basePath + href);
}
} }
}); });
@ -301,7 +359,7 @@ FP.Book.prototype.parseSpine = function(spine){
FP.Book.prototype.parseTOC = function(path){ FP.Book.prototype.parseTOC = function(path){
var that = this, var that = this,
url = this.basePath + path; url = path;
this.toc = []; this.toc = [];
@ -396,7 +454,7 @@ FP.Book.prototype.startDisplay = function(){
this.displayChapter(this.spinePos, function(chapter){ this.displayChapter(this.spinePos, function(chapter){
//-- If there is network connection, store the books contents //-- If there is network connection, store the books contents
if(this.online){ if(this.online && !this.contained){
this.storeOffline(); this.storeOffline();
} }
@ -525,6 +583,8 @@ FP.Book.prototype.availableOffline = function() {
FP.Book.prototype.fromStorage = function(stored) { FP.Book.prototype.fromStorage = function(stored) {
if(this.contained) return;
if(!stored){ if(!stored){
this.online = true; this.online = true;
this.tell("book:online"); this.tell("book:online");

View file

@ -24,7 +24,7 @@ FP.Chapter = function(book, pos){
FP.Chapter.prototype.load = function(){ FP.Chapter.prototype.load = function(){
var path = this.path; var path = this.path;
if(this.book.online){ if(this.book.online && !this.book.contained){
this.setIframeSrc(path); this.setIframeSrc(path);
}else{ }else{
this.loadFromStorage(path); this.loadFromStorage(path);
@ -214,7 +214,7 @@ FP.Chapter.prototype.replaceResources = function(callback){
//-- No need to replace if there is network connectivity //-- No need to replace if there is network connectivity
//-- also Filesystem api links are relative, so no need to replace them //-- also Filesystem api links are relative, so no need to replace them
if(this.book.online || FP.storage.getStorageType() == "filesystem") { if((this.book.online && !this.book.contained) || FP.storage.getStorageType() == "filesystem") {
if(callback) callback(); if(callback) callback();
return false; return false;
} }

View file

@ -163,3 +163,21 @@ FP.core.dataURLToBlob = function(dataURL) {
return new Blob([uInt8Array], {type: contentType}); return new Blob([uInt8Array], {type: contentType});
} }
//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously
FP.core.loadScript = function(src, callback) {
var s, r;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
document.body.appendChild(s);
}

View file

@ -35,6 +35,10 @@ FP.storage = function(){
return this._store.getURL(path); return this._store.getURL(path);
} }
function save(path, file, callback) {
return this._store.save(path, file, callback);
}
function _error(err){ function _error(err){
console.log("error", err); console.log("error", err);
@ -50,6 +54,7 @@ FP.storage = function(){
"batch" : batch, "batch" : batch,
"storageMethod": storageMethod, "storageMethod": storageMethod,
"getURL": getURL, "getURL": getURL,
"save" : save,
"getStorageType" : getStorageType "getStorageType" : getStorageType
} }

View file

@ -49,14 +49,12 @@ FP.store.filesystem = function() {
var url; var url;
//-- should only be checking urls? but blank on reload? //-- should only be checking urls? but blank on reload?
if(fromCache){ if(fromCache){
//console.log("c")
url = getURL(path, fromCache); url = getURL(path, fromCache);
if(typeof(callback) != "undefined"){ if(typeof(callback) != "undefined"){
callback(url); callback(url);
} }
}else{ }else{
_queue.add(path, function(url){ _queue.add(path, function(url){
console.log("url", url)
check(url, function(file){ check(url, function(file){
url = getURL(path, file); url = getURL(path, file);
if(typeof(callback) != "undefined"){ if(typeof(callback) != "undefined"){
@ -103,22 +101,44 @@ FP.store.filesystem = function() {
xhr.start(); xhr.start();
} }
function save(path, file) { function save(path, file, callback) {
var entry = {"path" : path, "file": file}, openFs(function(fs){
request; var base = path.split('/').slice(0,-1);
createDir(fs.root, base);
var transaction = _db.transaction(["files"], "readwrite"); fs.root.getFile(path, {create: true},
var store = transaction.objectStore("files"); function(fileEntry) {
request = store.put(entry);
request.onerror = function(event) { fileEntry.createWriter(function(fileWriter) {
console.log("failed: " + event.target.errorCode);
};
request.onsuccess = function(event) { fileWriter.onwriteend = function(e) {
//-- Do nothing for now if(callback) callback(e);
console.log("saved", path); };
};
fileWriter.onerror = function(e){
_error(err);
};
fileWriter.write(file);
});
}, _error );
});
}
function createDir(rootDirEntry, folders) {
// Throw out './' or '/' and move on to prevent something like '/foo/.//bar'.
if (folders[0] == '.' || folders[0] == '') {
folders = folders.slice(1);
}
rootDirEntry.getDirectory(folders[0], {create: true}, function(dirEntry) {
// Recursively add the new subfolder (if we still have another to create).
if (folders.length) {
createDir(dirEntry, folders.slice(1));
}
}, _error);
} }
//-- end worker //-- end worker
@ -139,17 +159,44 @@ FP.store.filesystem = function() {
function _error(err){ function _error(err){
if(typeof(this.failed) == "undefined"){ if(typeof(this.failed) == "undefined"){
console.log("Error: ", err); console.log("Error: ", errorHandler(err));
}else{ }else{
this.failed(err); this.failed(err);
} }
} }
function errorHandler(e) {
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
return 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
return 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
return 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
return 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
return 'INVALID_STATE_ERR';
break;
case FileError.TYPE_MISMATCH_ERR:
return 'TYPE_MISMATCH_ERR';
break;
default:
return 'Unknown Error:' + e.code ;
break;
}
}
return { return {
"get" : get, "get" : get,
"preload" : preload, "preload" : preload,
"batch" : batch "batch" : batch,
"getURL" : getURL,
"save" : save
} }
} }

View file

@ -197,6 +197,8 @@ FP.store.indexedDB = function() {
return { return {
"get" : get, "get" : get,
"preload" : preload, "preload" : preload,
"batch" : batch "batch" : batch,
"getURL" : getURL,
"save" : save
} }
} }

View file

@ -202,6 +202,7 @@ FP.store.websql = function() {
"get" : get, "get" : get,
"preload" : preload, "preload" : preload,
"batch" : batch, "batch" : batch,
"getURL" : getURL "getURL" : getURL,
"save" : save
} }
} }

77
fpjs/render/unarchiver.js Normal file
View file

@ -0,0 +1,77 @@
FP.Unarchiver = function(url, callback){
this.libPath = "fpjs/libs/";
this.zipUrl = url;
this.callback = callback;
this.loadLib(function(){
this.getZip(this.zipUrl);
}.bind(this));
}
FP.Unarchiver.prototype.loadLib = function(callback){
if(typeof(zip) != "undefined") callback();
//-- load script
FP.core.loadScript(this.libPath+"zip.js", function(){
//-- Tell zip where it is located
zip.workerScriptsPath = this.libPath;
callback();
}.bind(this));
}
FP.Unarchiver.prototype.getZip = function(zipUrl){
var xhr = new FP.core.loadFile(zipUrl);
xhr.succeeded = function(file) {
this.getEntries(file, this.toStorage.bind(this));
}.bind(this);
xhr.failed = this.failed;
xhr.start();
}
FP.Unarchiver.prototype.getEntries = function(file, callback){
zip.createReader(new zip.BlobReader(file), function(zipReader) {
zipReader.getEntries(callback);
}, this.failed);
}
FP.Unarchiver.prototype.failed = function(error){
console.log("Error:", error);
}
FP.Unarchiver.prototype.afterSaved = function(error){
this.callback();
}
FP.Unarchiver.prototype.toStorage = function(entries){
var timeout = 0,
delay = 20,
that = this,
count = entries.length;
function callback(){
count--;
if(count == 0) that.afterSaved();
}
entries.forEach(function(entry){
setTimeout(function(entry){
that.saveEntryFileToStorage(entry, callback);
}, timeout, entry);
timeout += delay;
});
console.log("time", timeout);
//entries.forEach(this.saveEntryFileToStorage.bind(this));
}
FP.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){
var that = this;
entry.getData(new zip.BlobWriter(), function(blob) {
FP.storage.save(entry.filename, blob, callback);
});
}

BIN
img/loader.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View file

@ -18,7 +18,7 @@
"use strict"; "use strict";
var FP = FP || {}; var FP = FP || {};
FP.VERSION = "0.1"; FP.VERSION = "0.1.2";
document.onreadystatechange = function () { document.onreadystatechange = function () {
if (document.readyState == "complete") { if (document.readyState == "complete") {
@ -33,6 +33,7 @@
<script async src="fpjs/reader/utils.js"></script> <script async src="fpjs/reader/utils.js"></script>
<script async src="fpjs/render/core.js"></script> <script async src="fpjs/render/core.js"></script>
<script async src="fpjs/render/queue.js"></script> <script async src="fpjs/render/queue.js"></script>
<script async src="fpjs/render/unarchiver.js"></script>
<script async src="fpjs/render/storage.js"></script> <script async src="fpjs/render/storage.js"></script>
<script async src="fpjs/render/storage_ram.js"></script> <script async src="fpjs/render/storage_ram.js"></script>
<script async src="fpjs/render/storage_websql.js"></script> <script async src="fpjs/render/storage_websql.js"></script>
@ -67,6 +68,7 @@
<div id="area"></div> <div id="area"></div>
<div id="next" class="arrow"></div> <div id="next" class="arrow"></div>
<div id="divider"></div> <div id="divider"></div>
<div id="loader"><img src="img/loader.gif"></div>
</div> </div>
</body> </body>
</html> </html>