1
0
Fork 0
mirror of https://github.com/futurepress/epub.js.git synced 2025-10-04 15:09:16 +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%;
opacity: .15;
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 {

View file

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

View file

@ -1,4 +1,4 @@
FP.Book = function(elem, bookUrl){
FP.Book = function(elem, bookPath){
//-- Takes a string or a element
if (typeof elem == "string") {
@ -36,8 +36,8 @@ FP.Book = function(elem, bookUrl){
this.determineStorageMethod();
// BookUrl is optional, but if present start loading process
if(bookUrl) {
this.display(bookUrl);
if(bookPath) {
this.display(bookPath);
}
@ -73,29 +73,38 @@ FP.Book.prototype.listeners = function(){
}
//-- 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,
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
if(this.isContained(bookUrl)){
console.error("Zipped!");
//-- Checks if the url is a zip file and unpack
if(this.isContained(bookPath)){
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.online) {
console.error("Not Online");
return;
}
//-- Gets the root of the book and url of the opf
this.parseContainer(function(){
//-- Gets all setup of the book from xml file
//-- TODO: add promise for this instead of callback?
//this.parseContents();
});
this.parseContainer();
}else{
//-- Events for elements loaded from storage
@ -109,15 +118,42 @@ FP.Book.prototype.start = function(bookUrl){
}
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{
//-- 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.isSaved = function(force) {
//-- 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 ||
force == true) {
localStorage.setItem("fpjs-version", FP.VERSION);
localStorage.setItem("bookUrl", this.bookUrl);
localStorage.setItem("bookPath", this.bookPath);
localStorage.setItem("spinePos", 0);
localStorage.setItem("stored", 0);
@ -193,9 +229,10 @@ FP.Book.prototype.resizeIframe = function(e, cWidth, cHeight){
this.iframe.width = width;
}
FP.Book.prototype.parseContainer = function(callback){
FP.Book.prototype.parseContainer = function(path){
var that = this,
url = this.bookUrl + "META-INF/container.xml";
url = path || this.bookUrl + "META-INF/container.xml";
FP.core.loadXML(url, function(container){
var fullpath;
@ -205,22 +242,36 @@ FP.Book.prototype.parseContainer = function(callback){
fullpath = rootfile.getAttribute('full-path').split("/");
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("contentsPath", that.contentsPath);
//-- Now that we have the path we can parse the contents
//-- 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,
url = this.basePath + this.contentsPath;
url = path || this.contentsPath;
FP.core.loadXML(url, function(contents){
var metadata = contents.querySelector("metadata"),
manifest = contents.querySelector("manifest"),
@ -265,7 +316,14 @@ FP.Book.prototype.parseManifest = function(manifest){
//-- Find NCX: media-type="application/x-dtbncx+xml" href="toc.ncx"
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,10 +359,10 @@ FP.Book.prototype.parseSpine = function(spine){
FP.Book.prototype.parseTOC = function(path){
var that = this,
url = this.basePath + path;
url = path;
this.toc = [];
FP.core.loadXML(url, function(contents){
var navMap = contents.querySelector("navMap"),
cover = contents.querySelector("meta[name='cover']"),
@ -396,7 +454,7 @@ FP.Book.prototype.startDisplay = function(){
this.displayChapter(this.spinePos, function(chapter){
//-- If there is network connection, store the books contents
if(this.online){
if(this.online && !this.contained){
this.storeOffline();
}
@ -525,6 +583,8 @@ FP.Book.prototype.availableOffline = function() {
FP.Book.prototype.fromStorage = function(stored) {
if(this.contained) return;
if(!stored){
this.online = true;
this.tell("book:online");

View file

@ -24,7 +24,7 @@ FP.Chapter = function(book, pos){
FP.Chapter.prototype.load = function(){
var path = this.path;
if(this.book.online){
if(this.book.online && !this.book.contained){
this.setIframeSrc(path);
}else{
this.loadFromStorage(path);
@ -214,7 +214,7 @@ FP.Chapter.prototype.replaceResources = function(callback){
//-- No need to replace if there is network connectivity
//-- 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();
return false;
}

View file

@ -163,3 +163,21 @@ FP.core.dataURLToBlob = function(dataURL) {
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);
}
function save(path, file, callback) {
return this._store.save(path, file, callback);
}
function _error(err){
console.log("error", err);
@ -50,6 +54,7 @@ FP.storage = function(){
"batch" : batch,
"storageMethod": storageMethod,
"getURL": getURL,
"save" : save,
"getStorageType" : getStorageType
}

View file

@ -49,14 +49,12 @@ FP.store.filesystem = function() {
var url;
//-- should only be checking urls? but blank on reload?
if(fromCache){
//console.log("c")
url = getURL(path, fromCache);
if(typeof(callback) != "undefined"){
callback(url);
}
}else{
_queue.add(path, function(url){
console.log("url", url)
check(url, function(file){
url = getURL(path, file);
if(typeof(callback) != "undefined"){
@ -103,24 +101,46 @@ FP.store.filesystem = function() {
xhr.start();
}
function save(path, file) {
var entry = {"path" : path, "file": file},
request;
function save(path, file, callback) {
openFs(function(fs){
var base = path.split('/').slice(0,-1);
createDir(fs.root, base);
var transaction = _db.transaction(["files"], "readwrite");
var store = transaction.objectStore("files");
request = store.put(entry);
request.onerror = function(event) {
console.log("failed: " + event.target.errorCode);
};
request.onsuccess = function(event) {
//-- Do nothing for now
console.log("saved", path);
};
fs.root.getFile(path, {create: true},
function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
if(callback) callback(e);
};
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
function getURL(path, fileEntry){
@ -139,17 +159,44 @@ FP.store.filesystem = function() {
function _error(err){
if(typeof(this.failed) == "undefined"){
console.log("Error: ", err);
console.log("Error: ", errorHandler(err));
}else{
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 {
"get" : get,
"preload" : preload,
"batch" : batch
"batch" : batch,
"getURL" : getURL,
"save" : save
}
}

View file

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

View file

@ -202,6 +202,7 @@ FP.store.websql = function() {
"get" : get,
"preload" : preload,
"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";
var FP = FP || {};
FP.VERSION = "0.1";
FP.VERSION = "0.1.2";
document.onreadystatechange = function () {
if (document.readyState == "complete") {
@ -33,6 +33,7 @@
<script async src="fpjs/reader/utils.js"></script>
<script async src="fpjs/render/core.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_ram.js"></script>
<script async src="fpjs/render/storage_websql.js"></script>
@ -67,6 +68,7 @@
<div id="area"></div>
<div id="next" class="arrow"></div>
<div id="divider"></div>
<div id="loader"><img src="img/loader.gif"></div>
</div>
</body>
</html>