more bookmark feature

tornado fix for tornado <6.2
This commit is contained in:
Ozzie Isaacs 2023-08-31 16:51:06 +02:00
parent 4bbcec21e4
commit 444ac181f8
3 changed files with 108 additions and 118 deletions

View File

@ -133,7 +133,7 @@ var createURLFromArray = function(array, mimeType) {
if ((typeof URL !== "function" && typeof URL !== "object") || if ((typeof URL !== "function" && typeof URL !== "object") ||
typeof URL.createObjectURL !== "function") { typeof URL.createObjectURL !== "function") {
throw "Browser support for Object URLs is missing"; throw "Browser support for Object URLs is missing";
} }
return URL.createObjectURL(blob); return URL.createObjectURL(blob);
@ -179,6 +179,8 @@ kthoom.ImageFile = function(file) {
}; };
function updateDirectionButtons(){ function updateDirectionButtons(){
$("#right").show();
$("#left").show();
if (currentImage == 0 ) { if (currentImage == 0 ) {
if (settings.direction === 0) { if (settings.direction === 0) {
$("#right").show(); $("#right").show();
@ -205,11 +207,12 @@ function initProgressClick() {
var rate = settings.direction === 0 ? x / $(this).width() : 1 - x / $(this).width(); var rate = settings.direction === 0 ? x / $(this).width() : 1 - x / $(this).width();
currentImage = Math.max(1, Math.ceil(rate * totalImages)) - 1; currentImage = Math.max(1, Math.ceil(rate * totalImages)) - 1;
updateDirectionButtons(); updateDirectionButtons();
setBookmark();
updatePage(); updatePage();
}); });
} }
function loadFromArrayBuffer(ab, lastCompletion = 0) { function loadFromArrayBuffer(ab) {
const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
loadArchiveFormats(['rar', 'zip', 'tar'], function() { loadArchiveFormats(['rar', 'zip', 'tar'], function() {
// Open the file as an archive // Open the file as an archive
@ -244,12 +247,8 @@ function loadFromArrayBuffer(ab, lastCompletion = 0) {
// display first page if we haven't yet // display first page if we haven't yet
if (imageFiles.length === currentImage + 1) { if (imageFiles.length === currentImage + 1) {
if (settings.direction === 0) { updateDirectionButtons();
$("#right").show(); updatePage();
} else {
$("#left").show();
}
updatePage(lastCompletion);
} }
} else { } else {
totalImages--; totalImages--;
@ -264,13 +263,6 @@ function loadFromArrayBuffer(ab, lastCompletion = 0) {
} }
function scrollTocToActive() { function scrollTocToActive() {
// Scroll to the thumbnail in the TOC on page change
$("#tocView").stop().animate({
scrollTop: $("#tocView a.active").position().top
}, 200);
}
function updatePage() {
$(".page").text((currentImage + 1 ) + "/" + totalImages); $(".page").text((currentImage + 1 ) + "/" + totalImages);
// Mark the current page in the TOC // Mark the current page in the TOC
@ -282,20 +274,19 @@ function updatePage() {
// Set it to active // Set it to active
.addClass("active"); .addClass("active");
// Scroll to the thumbnail in the TOC on page change
$("#tocView").stop().animate({
scrollTop: $("#tocView a.active").position().top
}, 200);
}
function updatePage() {
scrollTocToActive(); scrollTocToActive();
scrollCurrentImageIntoView();
updateProgress(); updateProgress();
pageDisplayUpdate(); pageDisplayUpdate();
setTheme(); setTheme();
if (imageFiles[currentImage]) {
setImage(imageFiles[currentImage].dataURI);
} else {
setImage("loading");
}
$("body").toggleClass("dark-theme", settings.theme === "dark");
$("#mainContent").toggleClass("disabled-scrollbar", settings.scrollbar === 0);
kthoom.setSettings(); kthoom.setSettings();
kthoom.saveSettings(); kthoom.saveSettings();
} }
@ -370,7 +361,6 @@ function setImage(url, _canvas) {
img.onerror = function() { img.onerror = function() {
canvas.width = innerWidth - 100; canvas.width = innerWidth - 100;
canvas.height = 300; canvas.height = 300;
updateScale(true);
x.fillStyle = "black"; x.fillStyle = "black";
x.font = "50px sans-serif"; x.font = "50px sans-serif";
x.strokeStyle = "black"; x.strokeStyle = "black";
@ -424,8 +414,6 @@ function setImage(url, _canvas) {
scrollTo(0, 0); scrollTo(0, 0);
x.drawImage(img, 0, 0); x.drawImage(img, 0, 0);
updateScale(false);
canvas.style.display = ""; canvas.style.display = "";
$("body").css("overflowY", ""); $("body").css("overflowY", "");
x.restore(); x.restore();
@ -447,6 +435,7 @@ function showLeftPage() {
} else { } else {
showNextPage(); showNextPage();
} }
setBookmark();
} }
function showRightPage() { function showRightPage() {
@ -455,6 +444,7 @@ function showRightPage() {
} else { } else {
showPrevPage(); showPrevPage();
} }
setBookmark();
} }
function showPrevPage() { function showPrevPage() {
@ -464,9 +454,6 @@ function showPrevPage() {
currentImage++; currentImage++;
} else { } else {
updatePage(); updatePage();
if (settings.nextPage === 0) {
$("#mainContent").scrollTop(0);
}
} }
updateDirectionButtons(); updateDirectionButtons();
} }
@ -478,9 +465,6 @@ function showNextPage() {
currentImage--; currentImage--;
} else { } else {
updatePage(); updatePage();
if (settings.nextPage === 0) {
$("#mainContent").scrollTop(0);
}
} }
updateDirectionButtons(); updateDirectionButtons();
} }
@ -497,7 +481,7 @@ function scrollCurrentImageIntoView() {
} }
} }
function updateScale(clear) { function updateScale() {
var canvasArray = $("#mainContent > canvas"); var canvasArray = $("#mainContent > canvas");
var maxheight = innerHeight - 50; var maxheight = innerHeight - 50;
@ -506,7 +490,7 @@ function updateScale(clear) {
canvasArray.css("maxWidth", ""); canvasArray.css("maxWidth", "");
canvasArray.css("maxHeight", ""); canvasArray.css("maxHeight", "");
if(!clear) { if(settings.pageDisplay === 0) {
canvasArray.addClass("hide"); canvasArray.addClass("hide");
pageDisplayUpdate(); pageDisplayUpdate();
} }
@ -667,13 +651,23 @@ function drawCanvas() {
$("#mainContent").append(canvasElement); $("#mainContent").append(canvasElement);
} }
function updateArrows() {
if ($('input[name="direction"]:checked').val() === "0") {
$("#prev_page_key").html("&larr;");
$("#next_page_key").html("&rarr;");
} else {
$("#prev_page_key").html("&rarr;");
$("#next_page_key").html("&larr;");
}
};
function init(filename) { function init(filename) {
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open("GET", filename); request.open("GET", filename);
request.responseType = "arraybuffer"; request.responseType = "arraybuffer";
request.addEventListener("load", function() { request.addEventListener("load", function () {
if (request.status >= 200 && request.status < 300) { if (request.status >= 200 && request.status < 300) {
loadFromArrayBuffer(request.response, currentImage); loadFromArrayBuffer(request.response);
} else { } else {
console.warn(request.statusText, request.responseText); console.warn(request.statusText, request.responseText);
} }
@ -687,18 +681,18 @@ function init(filename) {
$(document).keydown(keyHandler); $(document).keydown(keyHandler);
$(window).resize(function() { $(window).resize(function () {
updateScale(); updateScale();
}); });
// Open TOC menu // Open TOC menu
$("#slider").click(function() { $("#slider").click(function () {
$("#sidebar").toggleClass("open"); $("#sidebar").toggleClass("open");
$("#main").toggleClass("closed"); $("#main").toggleClass("closed");
$(this).toggleClass("icon-menu icon-right"); $(this).toggleClass("icon-menu icon-right");
// We need this in a timeout because if we call it during the CSS transition, IE11 shakes the page ¯\_(ツ)_/¯ // We need this in a timeout because if we call it during the CSS transition, IE11 shakes the page ¯\_(ツ)_/¯
setTimeout(function() { setTimeout(function () {
// Focus on the TOC or the main content area, depending on which is open // Focus on the TOC or the main content area, depending on which is open
$("#main:not(.closed) #mainContent, #sidebar.open #tocView").focus(); $("#main:not(.closed) #mainContent, #sidebar.open #tocView").focus();
scrollTocToActive(); scrollTocToActive();
@ -706,12 +700,12 @@ function init(filename) {
}); });
// Open Settings modal // Open Settings modal
$("#setting").click(function() { $("#setting").click(function () {
$("#settings-modal").toggleClass("md-show"); $("#settings-modal").toggleClass("md-show");
}); });
// On Settings input change // On Settings input change
$("#settings input").on("change", function() { $("#settings input").on("change", function () {
// Get either the checked boolean or the assigned value // Get either the checked boolean or the assigned value
var value = this.type === "checkbox" ? this.checked : this.value; var value = this.type === "checkbox" ? this.checked : this.value;
@ -720,43 +714,40 @@ function init(filename) {
settings[this.name] = value; settings[this.name] = value;
if(["hflip", "vflip", "rotateTimes"].includes(this.name)) { if (["hflip", "vflip", "rotateTimes"].includes(this.name)) {
reloadImages(); reloadImages();
} else if(this.name === "direction") { } else if (this.name === "direction") {
updateDirectionButtons(); updateDirectionButtons();
return updateProgress(); return updateProgress();
} }
updatePage(); updatePage();
updateScale(false); updateScale();
}); });
// Close modal // Close modal
$(".closer, .overlay").click(function() { $(".closer, .overlay").click(function () {
$(".md-show").removeClass("md-show"); $(".md-show").removeClass("md-show");
$("#mainContent").focus(); // focus back on the main container so you use up/down keys without having to click on it $("#mainContent").focus(); // focus back on the main container so you use up/down keys without having to click on it
}); });
// TOC thumbnail pagination // TOC thumbnail pagination
$("#thumbnails").on("click", "a", function() { $("#thumbnails").on("click", "a", function () {
currentImage = $(this).data("page") - 1; currentImage = $(this).data("page") - 1;
updatePage(); updatePage();
if (settings.nextPage === 0) {
$("#mainContent").scrollTop(0);
}
}); });
// Fullscreen mode // Fullscreen mode
if (typeof screenfull !== "undefined") { if (typeof screenfull !== "undefined") {
$("#fullscreen").click(function() { $("#fullscreen").click(function () {
screenfull.toggle($("#container")[0]); screenfull.toggle($("#container")[0]);
// Focus on main container so you can use up/down keys immediately after fullscreen // Focus on main container so you can use up/down keys immediately after fullscreen
$("#mainContent").focus(); $("#mainContent").focus();
}); });
if (screenfull.raw) { if (screenfull.raw) {
var $button = $("#fullscreen"); var $button = $("#fullscreen");
document.addEventListener(screenfull.raw.fullscreenchange, function() { document.addEventListener(screenfull.raw.fullscreenchange, function () {
screenfull.isFullscreen screenfull.isFullscreen
? $button.addClass("icon-resize-small").removeClass("icon-resize-full") ? $button.addClass("icon-resize-small").removeClass("icon-resize-full")
: $button.addClass("icon-resize-full").removeClass("icon-resize-small"); : $button.addClass("icon-resize-full").removeClass("icon-resize-small");
@ -767,15 +758,15 @@ function init(filename) {
// Focus the scrollable area so that keyboard scrolling work as expected // Focus the scrollable area so that keyboard scrolling work as expected
$("#mainContent").focus(); $("#mainContent").focus();
$("#mainContent").swipe( { $("#mainContent").swipe({
swipeRight:function() { swipeRight: function () {
showLeftPage(); showLeftPage();
}, },
swipeLeft:function() { swipeLeft: function () {
showRightPage(); showRightPage();
}, },
}); });
$(".mainImage").click(function(evt) { $(".mainImage").click(function (evt) {
// Firefox does not support offsetX/Y, so we have to manually calculate // Firefox does not support offsetX/Y, so we have to manually calculate
// where the user clicked in the image. // where the user clicked in the image.
var mainContentWidth = $("#mainContent").width(); var mainContentWidth = $("#mainContent").width();
@ -812,24 +803,30 @@ function init(filename) {
}); });
// Scrolling up/down will update current image if a new image is into view (for Long Strip Display) // Scrolling up/down will update current image if a new image is into view (for Long Strip Display)
$("#mainContent").scroll(function(){ $("#mainContent").scroll(function (event){
var scroll = $("#mainContent").scrollTop(); var scroll = $("#mainContent").scrollTop();
if(settings.pageDisplay === 0) { var viewLength = 0;
$(".mainImage").each(function(){
viewLength += $(this).height();
});
if (settings.pageDisplay === 0) {
// Don't trigger the scroll for Single Page // Don't trigger the scroll for Single Page
} else if(scroll > prevScrollPosition) { } else if (scroll > prevScrollPosition) {
//Scroll Down //Scroll Down
if(currentImage + 1 < imageFiles.length) { if (currentImage + 1 < imageFiles.length) {
if(currentImageOffset(currentImage + 1) <= 1) { if (currentImageOffset(currentImage + 1) <= 1) {
currentImage++; currentImage++;
console.log(Math.round(imageFiles.length / viewLength * scroll, 0));
scrollTocToActive(); scrollTocToActive();
updateProgress(); updateProgress();
} }
} }
} else { } else {
//Scroll Up //Scroll Up
if(currentImage - 1 > -1 ) { if (currentImage - 1 > -1) {
if(currentImageOffset(currentImage - 1) >= 0) { if (currentImageOffset(currentImage - 1) >= 0) {
currentImage--; currentImage--;
console.log(Math.round(imageFiles.length / viewLength * scroll, 0));
scrollTocToActive(); scrollTocToActive();
updateProgress(); updateProgress();
} }
@ -844,3 +841,31 @@ function init(filename) {
function currentImageOffset(imageIndex) { function currentImageOffset(imageIndex) {
return $(".mainImage").eq(imageIndex).offset().top - $("#mainContent").position().top return $(".mainImage").eq(imageIndex).offset().top - $("#mainContent").position().top
} }
function setBookmark() {
// get csrf_token
let csrf_token = $("input[name='csrf_token']").val();
//This sends a bookmark update to calibreweb.
$.ajax(calibre.bookmarkUrl, {
method: "post",
data: {
csrf_token: csrf_token,
bookmark: currentImage
}
}).fail(function (xhr, status, error) {
console.error(error);
});
}
$(function() {
$('input[name="direction"]').change(function () {
updateArrows();
});
$('#left').click(function () {
showLeftPage();
});
$('#right').click(function () {
showRightPage();
});
});

View File

@ -61,8 +61,8 @@
<div id="mainContent" tabindex="-1"> <div id="mainContent" tabindex="-1">
<div id="mainText" style="display:none"></div> <div id="mainText" style="display:none"></div>
</div> </div>
<div id="left" class="arrow" style="display:none" onclick="showLeftPage(); setBookmark();"></div> <div id="left" class="arrow" style="display:none"></div>
<div id="right" class="arrow" style="display:none" onclick="showRightPage(); setBookmark();"></div> <div id="right" class="arrow" style="display:none"></div>
</div> </div>
<div class="modal md-effect-1" id="settings-modal"> <div class="modal md-effect-1" id="settings-modal">
@ -183,58 +183,23 @@
<div class="overlay"></div> <div class="overlay"></div>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<script> <script>
var updateArrows = function () {
if ($('input[name="direction"]:checked').val() === "0") {
$("#prev_page_key").html("&larr;");
$("#next_page_key").html("&rarr;");
} else {
$("#prev_page_key").html("&rarr;");
$("#next_page_key").html("&larr;");
}
};
</script>
<script>
function setBookmark() {
// get csrf_token
let csrf_token = $("input[name='csrf_token']").val();
//This sends a bookmark update to calibreweb.
$.ajax(calibre.bookmarkUrl, {
method: "post",
data: {
csrf_token: csrf_token,
bookmark: currentImage
}
}).fail(function (xhr, status, error) {
console.error(error);
});
}
window.calibre = { window.calibre = {
filePath: "{{ url_for('static', filename='js/libs/') }}", bookmarkUrl: "{{ url_for('web.set_bookmark', book_id=comicfile, book_format=extension.upper()) }}",
cssPath: "{{ url_for('static', filename='css/') }}", bookmark: "{{ bookmark.bookmark_key if bookmark != None }}",
bookUrl: "{{ url_for('static', filename=comicfile) }}/", useBookmarks: "{{ current_user.is_authenticated | tojson }}"
bookmarkUrl: "{{ url_for('web.set_bookmark', book_id=comicfile, book_format=extension.upper()) }}",
bookmark: "{{ bookmark.bookmark_key if bookmark != None }}",
useBookmarks: "{{ current_user.is_authenticated | tojson }}"
}; };
if (calibre.useBookmarks) {
currentImage = eval(calibre.bookmark);
if (typeof currentImage !== 'number'){
currentImage = 0;
}
}
document.onreadystatechange = function () { document.onreadystatechange = function () {
if (document.readyState == "complete") { if (document.readyState == "complete") {
init("{{ url_for('web.serve_book', book_id=comicfile, book_format=extension) }}"); if (calibre.useBookmarks) {
updateArrows(); currentImage = eval(calibre.bookmark);
if (typeof currentImage !== 'number') {
currentImage = 0;
}
}
init("{{ url_for('web.serve_book', book_id=comicfile, book_format=extension) }}");
} }
} }
</script> </script>
<script>
$('input[name="direction"]').change(function() {
updateArrows();
});
</script>
</body> </body>
</html> </html>

View File

@ -34,7 +34,7 @@ if typing.TYPE_CHECKING:
class MyWSGIContainer(WSGIContainer): class MyWSGIContainer(WSGIContainer):
def __call__(self, request: httputil.HTTPServerRequest) -> None: def __call__(self, request: httputil.HTTPServerRequest) -> None:
if tornado.version_info > (6, 2, 0, 0): if tornado.version_info < (6, 2, 0, 0):
data = {} # type: Dict[str, Any] data = {} # type: Dict[str, Any]
response = [] # type: List[bytes] response = [] # type: List[bytes]
@ -91,9 +91,9 @@ class MyWSGIContainer(WSGIContainer):
def environ(self, request: httputil.HTTPServerRequest) -> Dict[Text, Any]: def environ(self, request: httputil.HTTPServerRequest) -> Dict[Text, Any]:
if isinstance(WSGIContainer.environ, FunctionType): try:
environ = WSGIContainer.environ(self, request) environ = WSGIContainer.environ(self, request)
else: except TypeError as e:
environ = WSGIContainer.environ(request) environ = WSGIContainer.environ(request)
environ['RAW_URI'] = request.path environ['RAW_URI'] = request.path
return environ return environ