'use strict';
/* global localforage, EpubeApp, App, Cookie, $ */
const DEFAULT_FONT_SIZE = 16;
const DEFAULT_FONT_FAMILY = "Arial";
const DEFAULT_LINE_HEIGHT = 140;
const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */
const LOCATION_DIVISOR = 10;
const PAGE_RESET_PROGRESS = -1;
const CACHE_PREFIX = 'epube';
const CACHE_NAME = CACHE_PREFIX + '-v3';
Promise.allSettled = Promise.allSettled || ((promises) => Promise.all(
promises.map((p) => p
.then((value) => ({
status: "fulfilled",
value
}))
.catch((reason) => ({
status: "rejected",
reason
}))
)
));
const Reader = {
csrf_token: "",
last_stored_cfi: "",
startup_finished: false,
open_last_read_when_displayed: true,
hyphenate: {},
init: function() {
this.csrf_token = Cookie.get('epube_csrf_token');
console.log('setting prefilter for token', this.csrf_token);
$.ajaxPrefilter(function(options, originalOptions/*, jqXHR*/) {
if (originalOptions.type !== 'post' || options.type !== 'post') {
return;
}
const datatype = typeof originalOptions.data;
if (datatype == 'object')
options.data = $.param($.extend(originalOptions.data, {"csrf_token": Reader.csrf_token}));
else if (datatype == 'string')
options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(Reader.srf_token);
console.log('>>>', options);
});
$(document).on("keyup", function(e) {
Reader.hotkeyHandler(e);
});
$("#left").on("mouseup", function() {
Reader.Page.prev();
});
$("#right").on("mouseup", function() {
Reader.Page.next();
});
Reader.Loader.init();
},
// another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
// https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
isTouchDevice: function() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
},
onOfflineModeChanged: function(offline) {
console.log('onOfflineModeChanged', offline);
if (!offline && window.book) {
const book = window.book;
console.log("we're online, storing lastread");
const currentCfi = book.rendition.currentLocation().start.cfi;
const currentPage = parseInt(book.locations.percentageFromCfi(currentCfi) * 100);
$.post("backend.php", { op: "storelastread", id: $.urlParam("id"), page: currentPage,
cfi: currentCfi, timestamp: new Date().getTime() }, function() {
//
})
.fail(function(e) {
if (e && e.status == 401) {
window.location = "index.php";
}
});
}
},
initSecondStage: async function() {
if (typeof EpubeApp != "undefined") {
EpubeApp.setPage("PAGE_READER");
} else {
$(window).on('online', function() {
Reader.onOfflineModeChanged(false);
});
$(window).on('offline', function() {
Reader.onOfflineModeChanged(true);
});
}
Reader.applyTheme();
const bookinfo = await localforage.getItem(Reader.cacheId());
if (!bookinfo) {
const bookId = $.urlParam("b");
console.log('requesting bookinfo for book', bookId)
try {
const resp = await $.post("backend.php", {op: "getinfo", id: bookId });
if (resp.has_cover) {
const cover = await fetch("backend.php?op=cover&id=" + bookId);
if (cover.ok)
await localforage.setItem(Reader.cacheId('cover'), cover.blob());
}
await localforage.setItem(Reader.cacheId(), resp);
console.log('bookinfo saved');
} catch (e) {
$(".loading-message").html(`Unable to load book info.
${e.responseText}`);
return;
}
}
console.log('trying to load book...');
let book_data = await localforage.getItem(Reader.cacheId("book"));
if (!book_data) {
console.log("local data not found, loading from network...");
$(".loading-message").html("Downloading book…");
const book_resp = await fetch("backend.php?op=download&id=" + $.urlParam("id"));
if (book_resp.ok) {
book_data = await book_resp.blob();
if (book_data) {
await localforage.setItem(Reader.cacheId('book'), book_data);
console.log('saved local data for book');
} else {
$(".loading-message").html("Unable to get book blob data.");
return;
}
} else {
$(".loading-message").html(`Unable to download book: ${book_resp.status}`);
return;
}
}
const fileReader = new FileReader();
fileReader.onload = function() {
try {
Reader.openBookData(this.result);
} catch (e) {
console.error(e);
$(".loading-message").html("Unable to load book blob: " + e);
}
};
fileReader.onerror = (e) => {
console.log('filereader error', e);
$(".loading-message").html("Unable to open book.
" + e + "");
};
fileReader.readAsArrayBuffer(book_data);
},
openBookData: async function(book_data) {
/* global ePub */
const book = ePub();
window.book = book;
try {
await book.open(book_data);
} catch (e) {
console.error(e);
$(".loading-message").html("Unable to open book.
" + e.message + "");
return;
}
await book.ready;
console.log('book is ready');
await Reader.showBookInfo(book);
await Reader.loadLocations(book);
const rendition = book.renderTo("reader", {
width: '100%',
height: '100%',
allowScriptedContent: true,
minSpreadWidth: 961
});
$(".location").on('click', async function() {
const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
const total = Math.floor(book.locations.length() / LOCATION_DIVISOR);
const page = prompt("Jump to location [1-" + total + "]", current);
if (page)
await rendition.display(book.locations._locations[page * LOCATION_DIVISOR]);
});
const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
if (enable_hyphens) {
/* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */
Reader.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
Reader.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
}
Reader.initRenditionHooks(book, rendition);
Reader.initModals();
Reader.initToc(book);
// open first page at startup, lastread will open when it is rendered
Reader.Page.blockLastReadUpdate();
await rendition.display();
console.log('startup finished');
Reader.startup_finished = true;
},
showBookInfo: async function(book) {
const bookinfo = await localforage.getItem(Reader.cacheId());
let title;
let author;
if (bookinfo) {
title = bookinfo.title;
author = bookinfo.author_sort;
} else {
const metadata = book.package.metadata;
title = metadata.title;
author = metadata.creator;
}
document.title = title + " – " + author + " – The Epube";
$(".title")
.text(title)
.attr("title", title + " – " + author);
if (typeof EpubeApp != "undefined") {
EpubeApp.setTitle(title);
EpubeApp.showActionBar(false);
}
},
loadLocations: async function(book) {
let locations = await localforage.getItem(Reader.cacheId("locations"));
// legacy format is array of objects {cfi: ..., page: ...}
if (locations && typeof locations[0] == "string") {
console.log('loading local locations...');
try {
await book.locations.load(locations);
return;
} catch (e) {
console.warn(e);
}
}
if (App.isOnline()) {
console.log("downloading locations...");
$(".loading-message").html("Downloading locations…");
const resp = await fetch("backend.php?op=getpagination&id=" + $.urlParam("id"));
if (resp.ok) {
console.log("got locations from server");
// if this doesn't load, we'll generate locations and save them
try {
locations = await resp.json();
} catch (e) {
console.warn(e);
}
if (locations && typeof locations[0] == "string") {
console.log('saving locations locally...');
await localforage.setItem(Reader.cacheId("locations"), locations);
try {
book.locations.load(locations);
return;
} catch (e) {
console.warn(e);
}
}
}
}
$(".loading-message").html("Preparing locations…");
locations = await book.locations.generate(100);
$.post("backend.php", { op: "storepagination", id: $.urlParam("id"),
payload: JSON.stringify(locations), total: 100});
await localforage.setItem(Reader.cacheId("locations"), locations);
},
initRenditionHooks: function(book, rendition) {
console.log('initRenditionHooks');
book.spine.hooks.content.register(function(doc/*, section */) {
Reader.cleanupEmbeddedStyles(doc);
});
rendition.hooks.content.register(async (contents) => {
contents.on("linkClicked", (href) => {
console.log('linkClicked', href);
Reader.Page.blockLastReadUpdate();
if (href.indexOf("://") == -1) {
$(".prev_location_btn")
.attr("data-location-cfi", rendition.currentLocation().start.cfi)
.show();
window.setTimeout(function() {
Reader.showUI(true);
}, 50);
}
});
// get our stuff from resource loader and inject into iframe content
const base_url = window.location.href.match(/^.*\//)[0];
if (typeof EpubeApp != "undefined") {
$(contents.document.head).append($(``));
} else {
$(contents.document.head)
.append($("