#include "Epub.h" #include #include #include #include #include #include #include "Epub/parsers/ContainerParser.h" #include "Epub/parsers/ContentOpfParser.h" #include "Epub/parsers/TocNcxParser.h" bool Epub::findContentOpfFile(std::string* contentOpfFile) const { const auto containerPath = "META-INF/container.xml"; size_t containerSize; // Get file size without loading it all into heap if (!getItemSize(containerPath, &containerSize)) { Serial.printf("[%lu] [EBP] Could not find or size META-INF/container.xml\n", millis()); return false; } ContainerParser containerParser(containerSize); if (!containerParser.setup()) { return false; } // Stream read (reusing your existing stream logic) if (!readItemContentsToStream(containerPath, containerParser, 512)) { Serial.printf("[%lu] [EBP] Could not read META-INF/container.xml\n", millis()); return false; } // Extract the result if (containerParser.fullPath.empty()) { Serial.printf("[%lu] [EBP] Could not find valid rootfile in container.xml\n", millis()); return false; } *contentOpfFile = std::move(containerParser.fullPath); return true; } bool Epub::parseContentOpf(const std::string& contentOpfFilePath) { Serial.printf("[%lu] [EBP] Parsing content.opf: %s\n", millis(), contentOpfFilePath.c_str()); size_t contentOpfSize; if (!getItemSize(contentOpfFilePath, &contentOpfSize)) { Serial.printf("[%lu] [EBP] Could not get size of content.opf\n", millis()); return false; } ContentOpfParser opfParser(getBasePath(), contentOpfSize); if (!opfParser.setup()) { Serial.printf("[%lu] [EBP] Could not setup content.opf parser\n", millis()); return false; } if (!readItemContentsToStream(contentOpfFilePath, opfParser, 1024)) { Serial.printf("[%lu] [EBP] Could not read content.opf\n", millis()); return false; } // Grab data from opfParser into epub title = opfParser.title; if (!opfParser.coverItemId.empty() && opfParser.items.count(opfParser.coverItemId) > 0) { coverImageItem = opfParser.items.at(opfParser.coverItemId); } if (!opfParser.tocNcxPath.empty()) { tocNcxItem = opfParser.tocNcxPath; } for (auto& spineRef : opfParser.spineRefs) { if (opfParser.items.count(spineRef)) { spine.emplace_back(spineRef, opfParser.items.at(spineRef)); } } Serial.printf("[%lu] [EBP] Successfully parsed content.opf\n", millis()); return true; } bool Epub::parseTocNcxFile() { // the ncx file should have been specified in the content.opf file if (tocNcxItem.empty()) { Serial.printf("[%lu] [EBP] No ncx file specified\n", millis()); return false; } Serial.printf("[%lu] [EBP] Parsing toc ncx file: %s\n", millis(), tocNcxItem.c_str()); const auto tmpNcxPath = getCachePath() + "/toc.ncx"; File tempNcxFile; if (!FsHelpers::openFileForWrite("EBP", tmpNcxPath, tempNcxFile)) { return false; } readItemContentsToStream(tocNcxItem, tempNcxFile, 1024); tempNcxFile.close(); if (!FsHelpers::openFileForRead("EBP", tmpNcxPath, tempNcxFile)) { return false; } const auto ncxSize = tempNcxFile.size(); TocNcxParser ncxParser(contentBasePath, ncxSize); if (!ncxParser.setup()) { Serial.printf("[%lu] [EBP] Could not setup toc ncx parser\n", millis()); return false; } const auto ncxBuffer = static_cast(malloc(1024)); if (!ncxBuffer) { Serial.printf("[%lu] [EBP] Could not allocate memory for toc ncx parser\n", millis()); return false; } while (tempNcxFile.available()) { const auto readSize = tempNcxFile.read(ncxBuffer, 1024); const auto processedSize = ncxParser.write(ncxBuffer, readSize); if (processedSize != readSize) { Serial.printf("[%lu] [EBP] Could not process all toc ncx data\n", millis()); free(ncxBuffer); tempNcxFile.close(); return false; } } free(ncxBuffer); tempNcxFile.close(); SD.remove(tmpNcxPath.c_str()); this->toc = std::move(ncxParser.toc); Serial.printf("[%lu] [EBP] Parsed %d TOC items\n", millis(), this->toc.size()); return true; } // load in the meta data for the epub file bool Epub::load() { Serial.printf("[%lu] [EBP] Loading ePub: %s\n", millis(), filepath.c_str()); std::string contentOpfFilePath; if (!findContentOpfFile(&contentOpfFilePath)) { Serial.printf("[%lu] [EBP] Could not find content.opf in zip\n", millis()); return false; } Serial.printf("[%lu] [EBP] Found content.opf at: %s\n", millis(), contentOpfFilePath.c_str()); contentBasePath = contentOpfFilePath.substr(0, contentOpfFilePath.find_last_of('/') + 1); if (!parseContentOpf(contentOpfFilePath)) { Serial.printf("[%lu] [EBP] Could not parse content.opf\n", millis()); return false; } if (!parseTocNcxFile()) { Serial.printf("[%lu] [EBP] Could not parse toc\n", millis()); return false; } initializeSpineItemSizes(); Serial.printf("[%lu] [EBP] Loaded ePub: %s\n", millis(), filepath.c_str()); return true; } void Epub::initializeSpineItemSizes() { Serial.printf("[%lu] [EBP] Calculating book size\n", millis()); const size_t spineItemsCount = getSpineItemsCount(); size_t cumSpineItemSize = 0; const ZipFile zip("/sd" + filepath); for (size_t i = 0; i < spineItemsCount; i++) { std::string spineItem = getSpineItem(i); size_t s = 0; getItemSize(zip, spineItem, &s); cumSpineItemSize += s; cumulativeSpineItemSize.emplace_back(cumSpineItemSize); } Serial.printf("[%lu] [EBP] Book size: %lu\n", millis(), cumSpineItemSize); } bool Epub::clearCache() const { if (!SD.exists(cachePath.c_str())) { Serial.printf("[%lu] [EPB] Cache does not exist, no action needed\n", millis()); return true; } if (!FsHelpers::removeDir(cachePath.c_str())) { Serial.printf("[%lu] [EPB] Failed to clear cache\n", millis()); return false; } Serial.printf("[%lu] [EPB] Cache cleared successfully\n", millis()); return true; } void Epub::setupCacheDir() const { if (SD.exists(cachePath.c_str())) { return; } // Loop over each segment of the cache path and create directories as needed for (size_t i = 1; i < cachePath.length(); i++) { if (cachePath[i] == '/') { SD.mkdir(cachePath.substr(0, i).c_str()); } } SD.mkdir(cachePath.c_str()); } const std::string& Epub::getCachePath() const { return cachePath; } const std::string& Epub::getPath() const { return filepath; } const std::string& Epub::getTitle() const { return title; } std::string Epub::getCoverBmpPath() const { return cachePath + "/cover.bmp"; } bool Epub::generateCoverBmp() const { // Already generated, return true if (SD.exists(getCoverBmpPath().c_str())) { return true; } if (coverImageItem.empty()) { Serial.printf("[%lu] [EBP] No known cover image\n", millis()); return false; } if (coverImageItem.substr(coverImageItem.length() - 4) == ".jpg" || coverImageItem.substr(coverImageItem.length() - 5) == ".jpeg") { Serial.printf("[%lu] [EBP] Generating BMP from JPG cover image\n", millis()); const auto coverJpgTempPath = getCachePath() + "/.cover.jpg"; File coverJpg; if (!FsHelpers::openFileForWrite("EBP", coverJpgTempPath, coverJpg)) { return false; } readItemContentsToStream(coverImageItem, coverJpg, 1024); coverJpg.close(); if (!FsHelpers::openFileForRead("EBP", coverJpgTempPath, coverJpg)) { return false; } File coverBmp; if (!FsHelpers::openFileForWrite("EBP", getCoverBmpPath(), coverBmp)) { coverJpg.close(); return false; } const bool success = JpegToBmpConverter::jpegFileToBmpStream(coverJpg, coverBmp); coverJpg.close(); coverBmp.close(); SD.remove(coverJpgTempPath.c_str()); if (!success) { Serial.printf("[%lu] [EBP] Failed to generate BMP from JPG cover image\n", millis()); SD.remove(getCoverBmpPath().c_str()); } Serial.printf("[%lu] [EBP] Generated BMP from JPG cover image, success: %s\n", millis(), success ? "yes" : "no"); return success; } else { Serial.printf("[%lu] [EBP] Cover image is not a JPG, skipping\n", millis()); } return false; } uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, bool trailingNullByte) const { const ZipFile zip("/sd" + filepath); const std::string path = FsHelpers::normalisePath(itemHref); const auto content = zip.readFileToMemory(path.c_str(), size, trailingNullByte); if (!content) { Serial.printf("[%lu] [EBP] Failed to read item %s\n", millis(), path.c_str()); return nullptr; } return content; } bool Epub::readItemContentsToStream(const std::string& itemHref, Print& out, const size_t chunkSize) const { const ZipFile zip("/sd" + filepath); const std::string path = FsHelpers::normalisePath(itemHref); return zip.readFileToStream(path.c_str(), out, chunkSize); } bool Epub::getItemSize(const std::string& itemHref, size_t* size) const { const ZipFile zip("/sd" + filepath); return getItemSize(zip, itemHref, size); } bool Epub::getItemSize(const ZipFile& zip, const std::string& itemHref, size_t* size) { const std::string path = FsHelpers::normalisePath(itemHref); return zip.getInflatedFileSize(path.c_str(), size); } int Epub::getSpineItemsCount() const { return spine.size(); } size_t Epub::getCumulativeSpineItemSize(const int spineIndex) const { if (spineIndex < 0 || spineIndex >= static_cast(cumulativeSpineItemSize.size())) { Serial.printf("[%lu] [EBP] getCumulativeSpineItemSize index:%d is out of range\n", millis(), spineIndex); return 0; } return cumulativeSpineItemSize.at(spineIndex); } std::string& Epub::getSpineItem(const int spineIndex) { static std::string emptyString; if (spine.empty()) { Serial.printf("[%lu] [EBP] getSpineItem called but spine is empty\n", millis()); return emptyString; } if (spineIndex < 0 || spineIndex >= static_cast(spine.size())) { Serial.printf("[%lu] [EBP] getSpineItem index:%d is out of range\n", millis(), spineIndex); return spine.at(0).second; } return spine.at(spineIndex).second; } EpubTocEntry& Epub::getTocItem(const int tocIndex) { static EpubTocEntry emptyEntry = {}; if (toc.empty()) { Serial.printf("[%lu] [EBP] getTocItem called but toc is empty\n", millis()); return emptyEntry; } if (tocIndex < 0 || tocIndex >= static_cast(toc.size())) { Serial.printf("[%lu] [EBP] getTocItem index:%d is out of range\n", millis(), tocIndex); return toc.at(0); } return toc.at(tocIndex); } int Epub::getTocItemsCount() const { return toc.size(); } // work out the section index for a toc index int Epub::getSpineIndexForTocIndex(const int tocIndex) const { if (tocIndex < 0 || tocIndex >= toc.size()) { Serial.printf("[%lu] [EBP] getSpineIndexForTocIndex: tocIndex %d out of range\n", millis(), tocIndex); return 0; } // the toc entry should have an href that matches the spine item // so we can find the spine index by looking for the href for (int i = 0; i < spine.size(); i++) { if (spine[i].second == toc[tocIndex].href) { return i; } } Serial.printf("[%lu] [EBP] Section not found\n", millis()); // not found - default to the start of the book return 0; } int Epub::getTocIndexForSpineIndex(const int spineIndex) const { if (spineIndex < 0 || spineIndex >= spine.size()) { Serial.printf("[%lu] [EBP] getTocIndexForSpineIndex: spineIndex %d out of range\n", millis(), spineIndex); return -1; } // the toc entry should have an href that matches the spine item // so we can find the toc index by looking for the href for (int i = 0; i < toc.size(); i++) { if (toc[i].href == spine[spineIndex].second) { return i; } } Serial.printf("[%lu] [EBP] TOC item not found\n", millis()); return -1; } size_t Epub::getBookSize() const { if (spine.empty()) { return 0; } return getCumulativeSpineItemSize(getSpineItemsCount() - 1); } // Calculate progress in book uint8_t Epub::calculateProgress(const int currentSpineIndex, const float currentSpineRead) { size_t bookSize = getBookSize(); if (bookSize == 0) { return 0; } size_t prevChapterSize = (currentSpineIndex >= 1) ? getCumulativeSpineItemSize(currentSpineIndex - 1) : 0; size_t curChapterSize = getCumulativeSpineItemSize(currentSpineIndex) - prevChapterSize; size_t sectionProgSize = currentSpineRead * curChapterSize; return round(static_cast(prevChapterSize + sectionProgSize) / bookSize * 100.0); }