'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReaderClass = void 0;
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 appcommon_1 = require("./appcommon");
const cookie_1 = require("./cookie");
class ReaderClass extends appcommon_1.AppCommon {
constructor() {
super(...arguments);
this.csrf_token = "";
this.last_stored_cfi = "";
this.startup_finished = false;
this.open_last_read_when_displayed = true;
this.hyphenate = { en: null, ru: null };
}
async init() {
this.csrf_token = cookie_1.Cookie.get('epube_csrf_token');
console.log('setting prefilter for token', this.csrf_token);
$.ajaxPrefilter((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": this.csrf_token }));
else if (datatype == 'string')
options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token);
console.log('>>>', options);
});
$(document).on("keyup", (e) => {
this.hotkeyHandler(e);
});
$(".close_book").on("click", () => {
this.close();
});
$("#left").on("mouseup", () => {
this.prevPage();
});
$(".search_input").on("change", () => {
this.search();
});
$(".prev_location_btn").on("click", (evt) => {
this.openPrevious(evt.target);
});
$("#right").on("mouseup", () => {
this.nextPage();
});
this.loader = new ReaderLoader();
const load_failed = await this.loader.init();
console.log('[init] load failed', load_failed);
if (!load_failed) {
this.initSecondStage();
}
else {
this.applyTheme();
$(".loading-message").text('Resource loader failed to initialize.');
}
}
// 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() {
return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
}
/**
* @param {boolean} offline
*/
onOfflineModeChanged(offline) {
console.log('onOfflineModeChanged', offline);
if (!offline && this.book) {
console.log("we're online, storing lastread");
const currentCfi = this.book.rendition.currentLocation().start.cfi;
const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
$.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
cfi: currentCfi, timestamp: new Date().getTime() }, function () {
//
})
.fail(function (e) {
if (e && e.status == 401) {
window.location.href = "index.php";
}
});
}
}
async initSecondStage() {
if (typeof EpubeApp != "undefined") {
EpubeApp.setPage("PAGE_READER");
}
else {
$(window).on('online', () => {
this.onOfflineModeChanged(false);
});
$(window).on('offline', () => {
this.onOfflineModeChanged(true);
});
}
this.applyTheme();
const bookinfo = await localforage.getItem(this.cacheId());
if (!bookinfo) {
const bookId = this.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(this.cacheId('cover'), cover.blob());
}
await localforage.setItem(this.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(this.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=" + this.urlParam("id"));
if (book_resp.ok) {
book_data = await book_resp.blob();
if (book_data) {
await localforage.setItem(this.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();
const _reader = this;
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);
}
async openBookData(book_data) {
// @ts-ignore
this.book = new ePub.Book();
try {
await this.book.open(book_data);
}
catch (e) {
console.error(e);
$(".loading-message").html("Unable to open book.
" + e.message + "");
return;
}
await this.book.ready;
console.log('book is ready');
await this.showBookInfo(this.book);
await this.loadLocations(this.book);
const rendition = this.book.renderTo("reader", {
width: '100%',
height: '100%',
allowScriptedContent: false,
minSpreadWidth: 961
});
$(".location").on('click', async () => {
const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
const page = prompt("Jump to location [1-" + total + "]", String(current));
if (page)
await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
});
const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
if (enable_hyphens) {
/* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */
this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
}
this.initRenditionHooks(this.book, rendition);
this.initModals();
this.initToc(this.book);
// open first page at startup, lastread will open when it is rendered
this.blockLastReadUpdate();
await rendition.display();
console.log('startup finished');
this.startup_finished = true;
}
/**
* @param {ePub.Book} book
*/
async showBookInfo(book) {
const bookinfo = await localforage.getItem(this.cacheId());
let title;
let author;
if (bookinfo) {
title = bookinfo.title;
author = bookinfo.author_sort;
}
else {
const metadata = book.packaging.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);
}
}
/**
* @param {ePub.Book} book
*/
async loadLocations(book) {
let locations = await localforage.getItem(this.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 (this.isOnline()) {
console.log("downloading locations...");
$(".loading-message").html("Downloading locations…");
const resp = await fetch("backend.php?op=getpagination&id=" + this.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(this.cacheId("locations"), locations);
try {
book.locations.load(locations);
return;
}
catch (e) {
console.warn(e);
}
}
}
}
$(".loading-message").html("Preparing locations…");
let generate_queue_max = 0;
locations = await book.locations.generate(100, (queue) => {
if (!generate_queue_max)
generate_queue_max = queue.length();
// what if there's only one section or something and queue is already zero
if (generate_queue_max > 0) {
const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf
$(".loading-message").html(`Preparing locations (${queue_pct}%)…`);
}
});
$.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
payload: JSON.stringify(locations), total: 100 });
await localforage.setItem(this.cacheId("locations"), locations);
}
/**
* @param {ePub.Book} book
* @param {ePub.Rendition} rendition
*/
initRenditionHooks(book, rendition) {
console.log('initRenditionHooks');
book.spine.hooks.content.register((doc /*, section */) => {
this.cleanupEmbeddedStyles(doc);
});
rendition.hooks.content.register(async (contents) => {
contents.on("linkClicked", (href) => {
console.log('linkClicked', href);
this.blockLastReadUpdate();
if (href.indexOf("://") == -1) {
$(".prev_location_btn")
.attr("data-location-cfi", rendition.currentLocation().start.cfi)
.show();
window.requestAnimationFrame(() => {
this.showUI(true);
});
}
});
contents.on("selected", async (cfiRange) => {
if (this.isOnline()) {
const range = await book.getRange(cfiRange);
const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
console.log('selected', cfiRange, selection);
if (selection.match(/^[\w]+$/)) {
this.lookupWord(selection, () => {
if (typeof EpubeApp != "undefined")
EpubeApp.showActionBar(false);
contents.window.requestAnimationFrame(() => {
contents.window.getSelection().removeAllRanges();
});
});
}
}
});
// get our stuff from resource loader and inject into iframe content
const base_url = window.location.href.match(/^.*\//)[0];
$(contents.document.head)
.append($("