Merge branch 'feat-kosync-onlongpress' of https://github.com/jpirnay/crosspoint-reader into mybuild

This commit is contained in:
jpirnay committed 2026-03-23 12:02:25 +01:00
commit 84e3850d5d
6 files changed
+3878 -85

No files matched your search

+27 -2
View File
@@ -144,8 +144,33 @@ void EpubReaderActivity::loop() {
}
}
// Enter reader menu activity.
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
// Long press CONFIRM (1s+) goes directly to KOReader sync.
if (mappedInput.isPressed(MappedInputManager::Button::Confirm) &&
mappedInput.getHeldTime() >= ReaderUtils::GO_HOME_MS) {
if (KOREADER_STORE.hasCredentials()) {
const int currentPage = section ? section->currentPage : 0;
const int totalPages = section ? section->pageCount : 0;
startActivityForResult(
std::make_unique<KOReaderSyncActivity>(renderer, mappedInput, epub, epub->getPath(), currentSpineIndex,
currentPage, totalPages),
[this](const ActivityResult& result) {
if (!result.isCancelled) {
const auto& sync = std::get<SyncResult>(result.data);
if (currentSpineIndex != sync.spineIndex || (section && section->currentPage != sync.page)) {
RenderLock lock(*this);
currentSpineIndex = sync.spineIndex;
nextPageNumber = sync.page;
section.reset();
}
}
});
}
return;
}
// Short press CONFIRM enters reader menu activity.
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm) &&
mappedInput.getHeldTime() < ReaderUtils::GO_HOME_MS) {
const int currentPage = section ? section->currentPage + 1 : 0;
const int totalPages = section ? section->pageCount : 0;
float bookProgress = 0.0f;
+102 -24
View File
@@ -17,6 +17,7 @@
#include "html/FilesPageHtml.generated.h"
#include "html/HomePageHtml.generated.h"
#include "html/SettingsPageHtml.generated.h"
#include "html/js/jszip_minJs.generated.h"
namespace {
// Folders/files to hide from the web interface file browser
@@ -37,6 +38,8 @@ size_t wsUploadSize = 0;
size_t wsUploadReceived = 0;
unsigned long wsUploadStartTime = 0;
bool wsUploadInProgress = false;
uint8_t wsUploadClientNum = 255; // 255 = no active upload client
size_t wsLastProgressSent = 0;
String wsLastCompleteName;
size_t wsLastCompleteSize = 0;
unsigned long wsLastCompleteAt = 0;
@@ -132,6 +135,7 @@ void CrossPointWebServer::begin() {
LOG_DBG("WEB", "Setting up routes...");
server->on("/", HTTP_GET, [this] { handleRoot(); });
server->on("/files", HTTP_GET, [this] { handleFileList(); });
server->on("/js/jszip.min.js", HTTP_GET, [this] { handleJszip(); });
server->on("/api/status", HTTP_GET, [this] { handleStatus(); });
server->on("/api/files", HTTP_GET, [this] { handleFileListData(); });
@@ -189,6 +193,21 @@ void CrossPointWebServer::begin() {
LOG_DBG("WEB", "[MEM] Free heap after server.begin(): %d bytes", ESP.getFreeHeap());
}
void CrossPointWebServer::abortWsUpload(const char* tag) {
wsUploadFile.close();
String filePath = wsUploadPath;
if (!filePath.endsWith("/")) filePath += "/";
filePath += wsUploadFileName;
if (Storage.remove(filePath.c_str())) {
LOG_DBG(tag, "Deleted incomplete upload: %s", filePath.c_str());
} else {
LOG_DBG(tag, "Failed to delete incomplete upload: %s", filePath.c_str());
}
wsUploadInProgress = false;
wsUploadClientNum = 255;
wsLastProgressSent = 0;
}
void CrossPointWebServer::stop() {
if (!running || !server) {
LOG_DBG("WEB", "stop() called but already stopped (running=%d, server=%p)", running, server.get());
@@ -200,10 +219,9 @@ void CrossPointWebServer::stop() {
LOG_DBG("WEB", "[MEM] Free heap before stop: %d bytes", ESP.getFreeHeap());
// Close any in-progress WebSocket upload
// Close any in-progress WebSocket upload and remove partial file
if (wsUploadInProgress && wsUploadFile) {
wsUploadFile.close();
wsUploadInProgress = false;
abortWsUpload("WEB");
}
// Stop WebSocket server
@@ -310,6 +328,12 @@ void CrossPointWebServer::handleRoot() const {
LOG_DBG("WEB", "Served root page");
}
void CrossPointWebServer::handleJszip() const {
server->sendHeader("Content-Encoding", "gzip");
server->send_P(200, "application/javascript", jszip_minJs, jszip_minJsCompressedSize);
LOG_DBG("WEB", "Served jszip.min.js");
}
void CrossPointWebServer::handleNotFound() const {
String message = "404 Not Found\n\n";
message += "URI: " + server->uri() + "\n";
@@ -524,7 +548,26 @@ void CrossPointWebServer::handleDownload() const {
server->send(200, contentType.c_str(), "");
NetworkClient client = server->client();
client.write(file);
const size_t chunkSize = 4096;
uint8_t buffer[chunkSize];
bool downloadOk = true;
while (downloadOk && file.available()) {
int result = file.read(buffer, chunkSize);
if (result <= 0) break;
size_t bytesRead = static_cast<size_t>(result);
size_t totalWritten = 0;
while (totalWritten < bytesRead) {
esp_task_wdt_reset();
size_t wrote = client.write(buffer + totalWritten, bytesRead - totalWritten);
if (wrote == 0) {
downloadOk = false;
break;
}
totalWritten += wrote;
}
}
client.clear();
file.close();
}
@@ -1101,7 +1144,7 @@ void CrossPointWebServer::handleGetSettings() const {
doc["type"] = "string";
if (s.stringGetter) {
doc["value"] = s.stringGetter();
} else if (s.stringOffset > 0) {
} else if (s.stringMaxLen > 0) {
doc["value"] = reinterpret_cast<const char*>(&SETTINGS) + s.stringOffset;
}
break;
@@ -1185,7 +1228,7 @@ void CrossPointWebServer::handlePostSettings() {
const std::string val = doc[s.key].as<std::string>();
if (s.stringSetter) {
s.stringSetter(val);
} else if (s.stringOffset > 0 && s.stringMaxLen > 0) {
} else if (s.stringMaxLen > 0) {
char* ptr = reinterpret_cast<char*>(&SETTINGS) + s.stringOffset;
strncpy(ptr, val.c_str(), s.stringMaxLen - 1);
ptr[s.stringMaxLen - 1] = '\0';
@@ -1221,17 +1264,12 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
switch (type) {
case WStype_DISCONNECTED:
LOG_DBG("WS", "Client %u disconnected", num);
// Clean up any in-progress upload
if (wsUploadInProgress && wsUploadFile) {
wsUploadFile.close();
// Delete incomplete file
String filePath = wsUploadPath;
if (!filePath.endsWith("/")) filePath += "/";
filePath += wsUploadFileName;
Storage.remove(filePath.c_str());
LOG_DBG("WS", "Deleted incomplete upload: %s", filePath.c_str());
// Only clean up if this is the client that owns the active upload.
// A new client may have already started a fresh upload before this
// DISCONNECTED event fires (race condition on quick cancel + retry).
if (num == wsUploadClientNum && wsUploadInProgress && wsUploadFile) {
abortWsUpload("WS");
}
wsUploadInProgress = false;
break;
case WStype_CONNECTED: {
@@ -1245,15 +1283,35 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
LOG_DBG("WS", "Text from client %u: %s", num, msg.c_str());
if (msg.startsWith("START:")) {
// Reject any START while an upload is already active to prevent
// leaking the open wsUploadFile handle (owning client re-START included)
if (wsUploadInProgress) {
wsServer->sendTXT(num, "ERROR:Upload already in progress");
break;
}
// Parse: START:<filename>:<size>:<path>
int firstColon = msg.indexOf(':', 6);
int secondColon = msg.indexOf(':', firstColon + 1);
if (firstColon > 0 && secondColon > 0) {
wsUploadFileName = msg.substring(6, firstColon);
wsUploadSize = msg.substring(firstColon + 1, secondColon).toInt();
String sizeToken = msg.substring(firstColon + 1, secondColon);
bool sizeValid = sizeToken.length() > 0;
int digitStart = (sizeValid && sizeToken[0] == '+') ? 1 : 0;
if (digitStart > 0 && sizeToken.length() < 2) sizeValid = false;
for (int i = digitStart; i < (int)sizeToken.length() && sizeValid; i++) {
if (!isdigit((unsigned char)sizeToken[i])) sizeValid = false;
}
if (!sizeValid) {
LOG_DBG("WS", "START rejected: invalid size token '%s'", sizeToken.c_str());
wsServer->sendTXT(num, "ERROR:Invalid START format");
return;
}
wsUploadSize = sizeToken.toInt();
wsUploadPath = msg.substring(secondColon + 1);
wsUploadReceived = 0;
wsLastProgressSent = 0;
wsUploadStartTime = millis();
// Ensure path is valid
@@ -1281,10 +1339,25 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
if (!Storage.openFileForWrite("WS", filePath, wsUploadFile)) {
wsServer->sendTXT(num, "ERROR:Failed to create file");
wsUploadInProgress = false;
wsUploadClientNum = 255;
return;
}
esp_task_wdt_reset();
// Zero-byte upload: complete immediately without waiting for BIN frames
if (wsUploadSize == 0) {
wsUploadFile.close();
wsLastCompleteName = wsUploadFileName;
wsLastCompleteSize = 0;
wsLastCompleteAt = millis();
LOG_DBG("WS", "Zero-byte upload complete: %s", filePath.c_str());
clearEpubCacheIfNeeded(filePath);
wsServer->sendTXT(num, "DONE");
wsLastProgressSent = 0;
break;
}
wsUploadClientNum = num;
wsUploadInProgress = true;
wsServer->sendTXT(num, "READY");
} else {
@@ -1295,19 +1368,24 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
}
case WStype_BIN: {
if (!wsUploadInProgress || !wsUploadFile) {
if (!wsUploadInProgress || !wsUploadFile || num != wsUploadClientNum) {
wsServer->sendTXT(num, "ERROR:No upload in progress");
return;
}
// Write binary data directly to file
size_t remaining = wsUploadSize - wsUploadReceived;
if (length > remaining) {
abortWsUpload("WS");
wsServer->sendTXT(num, "ERROR:Upload overflow");
return;
}
esp_task_wdt_reset();
size_t written = wsUploadFile.write(payload, length);
esp_task_wdt_reset();
if (written != length) {
wsUploadFile.close();
wsUploadInProgress = false;
abortWsUpload("WS");
wsServer->sendTXT(num, "ERROR:Write failed - disk full?");
return;
}
@@ -1315,17 +1393,17 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
wsUploadReceived += written;
// Send progress update (every 64KB or at end)
static size_t lastProgressSent = 0;
if (wsUploadReceived - lastProgressSent >= 65536 || wsUploadReceived >= wsUploadSize) {
if (wsUploadReceived - wsLastProgressSent >= 65536 || wsUploadReceived >= wsUploadSize) {
String progress = "PROGRESS:" + String(wsUploadReceived) + ":" + String(wsUploadSize);
wsServer->sendTXT(num, progress);
lastProgressSent = wsUploadReceived;
wsLastProgressSent = wsUploadReceived;
}
// Check if upload complete
if (wsUploadReceived >= wsUploadSize) {
wsUploadFile.close();
wsUploadInProgress = false;
wsUploadClientNum = 255;
wsLastCompleteName = wsUploadFileName;
wsLastCompleteSize = wsUploadSize;
@@ -1344,7 +1422,7 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
clearEpubCacheIfNeeded(filePath);
wsServer->sendTXT(num, "DONE");
lastProgressSent = 0;
wsLastProgressSent = 0;
}
break;
}
+2
View File
@@ -81,6 +81,7 @@ class CrossPointWebServer {
// WebSocket upload state
void onWebSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length);
static void wsEventCallback(uint8_t num, WStype_t type, uint8_t* payload, size_t length);
void abortWsUpload(const char* tag);
// File scanning
void scanFiles(const char* path, const std::function<void(FileInfo)>& callback) const;
@@ -88,6 +89,7 @@ class CrossPointWebServer {
// Request handlers
void handleRoot() const;
void handleJszip() const;
void handleNotFound() const;
void handleStatus() const;
void handleFileList() const;
File diff suppressed because it is too large. Load diff
+13
View File
@@ -0,0 +1,13 @@
/*!
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
JSZip uses the library pako released under the MIT license :
https://github.com/nodeca/pako/blob/main/LICENSE
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).JSZip=e()}}(function(){return function s(a,o,h){function u(r,e){if(!o[r]){if(!a[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(l)return l(r,!0);var n=new Error("Cannot find module '"+r+"'");throw n.code="MODULE_NOT_FOUND",n}var i=o[r]={exports:{}};a[r][0].call(i.exports,function(e){var t=a[r][1][e];return u(t||e)},i,i.exports,s,a,o,h)}return o[r].exports}for(var l="function"==typeof require&&require,e=0;e<h.length;e++)u(h[e]);return u}({1:[function(e,t,r){"use strict";var d=e("./utils"),c=e("./support"),p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(e){for(var t,r,n,i,s,a,o,h=[],u=0,l=e.length,f=l,c="string"!==d.getTypeOf(e);u<e.length;)f=l-u,n=c?(t=e[u++],r=u<l?e[u++]:0,u<l?e[u++]:0):(t=e.charCodeAt(u++),r=u<l?e.charCodeAt(u++):0,u<l?e.charCodeAt(u++):0),i=t>>2,s=(3&t)<<4|r>>4,a=1<f?(15&r)<<2|n>>6:64,o=2<f?63&n:64,h.push(p.charAt(i)+p.charAt(s)+p.charAt(a)+p.charAt(o));return h.join("")},r.decode=function(e){var t,r,n,i,s,a,o=0,h=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var l,f=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===p.charAt(64)&&f--,e.charAt(e.length-2)===p.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(l=c.uint8array?new Uint8Array(0|f):new Array(0|f);o<e.length;)t=p.indexOf(e.charAt(o++))<<2|(i=p.indexOf(e.charAt(o++)))>>4,r=(15&i)<<4|(s=p.indexOf(e.charAt(o++)))>>2,n=(3&s)<<6|(a=p.indexOf(e.charAt(o++))),l[h++]=t,64!==s&&(l[h++]=r),64!==a&&(l[h++]=n);return l}},{"./support":30,"./utils":32}],2:[function(e,t,r){"use strict";var n=e("./external"),i=e("./stream/DataWorker"),s=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,r,n,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=i}o.prototype={getContentWorker:function(){var e=new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,r){return e.pipe(new s).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",t)},t.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){"use strict";var n=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},r.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){"use strict";var n=e("./utils");var o=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a<s;a++)e=e>>>8^i[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a<s;a++)e=e>>>8^i[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,r){"use strict";r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(e,t,r){"use strict";var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,r){"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,i=e("pako"),s=e("./utils"),a=e("./stream/GenericWorker"),o=n?"uint8array":"array";function h(e,t){a.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}r.magic="\b\0",s.inherits(h,a),h.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,e.data),!1)},h.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(Line truncated