From 2a35aff1b214f2622ed05d9c932b83b5d5b084bf Mon Sep 17 00:00:00 2001 From: Marko Andjelic Date: Sat, 24 Jan 2026 00:04:45 +0000 Subject: [PATCH] Add reader environment --- app/EpubParser.hs | 33 ++++++++++++++++++++++++++------- svitak.cabal | 2 ++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/app/EpubParser.hs b/app/EpubParser.hs index 0d71572..cbfaf78 100644 --- a/app/EpubParser.hs +++ b/app/EpubParser.hs @@ -5,12 +5,30 @@ import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as C8 import Text.HTML.TagSoup (parseTags, fromAttrib, (~==), Tag, innerText, sections) import System.FilePath (takeDirectory) +import Control.Monad.Reader +import qualified Data.Text as T +import Data.Maybe (fromMaybe) -data BookInfo = BookInfo - { title :: String - , author :: String +type EpubAction a = ReaderT EpubEnv IO a + +data EpubEnv = EpubEnv + { title :: T.Text + , author :: T.Text + , rootPrefix :: FilePath } deriving (Show) +myEnv :: Archive -> [Tag String] -> EpubEnv +myEnv archive tags = + let + opfPath = fromMaybe "" (getOpfPath archive) + prefix = getRootPrefix opfPath + + in + EpubEnv + { title = getTagText "dc:title" tags + , author = getTagText "dc:creator" tags + , rootPrefix = prefix + } openEpub :: FilePath -> IO (Either String Archive) openEpub path = toArchive <$> BL.readFile path >>= \archive -> maybe (pure $ Left "Error reading file") (\entry -> if fromEntry entry == C8.pack "application/epub+zip" then pure (Right archive) else pure (Left "Wrong mimetype")) (findEntryByPath "mimetype" archive) @@ -28,7 +46,7 @@ getOpfPath archive = do case rootfileTags of (t:_) -> Just (fromAttrib "full-path" t) [] -> Nothing - + getRootPrefix :: FilePath -> FilePath getRootPrefix path = let dir = takeDirectory path @@ -39,8 +57,9 @@ getRootPrefix path = tagify :: String -> String tagify item = "<" ++ item ++ ">" -getTagText :: String -> [Tag String] -> String +getTagText :: String -> [Tag String] -> T.Text getTagText tagName tags = case sections (~== tagify tagName) tags of - (x:_) -> innerText x - [] -> "" + (x:_) -> T.pack (innerText x) + [] -> T.empty + diff --git a/svitak.cabal b/svitak.cabal index 2fc1242..e710b44 100644 --- a/svitak.cabal +++ b/svitak.cabal @@ -63,7 +63,9 @@ executable svitak bytestring >= 0.12.2.0, epub-metadata >=5.4, filepath >= 1.5.4.0, + mtl >= 2.3.2, tagsoup, + text >= 2.1.2, zip-archive >= 0.4.3.2 hs-source-dirs: app