svitak/app/Persistence.hs
Marko Andjelic fab1d6b84c Add persistence module
This will allow us to save the last chapter the user read, thus making it easier to track progress.

Implement persistence module

saveLastRead saves the chapter after each new one is read and writes it to xdgdata
2026-01-26 08:32:20 +00:00

40 lines
1.3 KiB
Haskell

module Persistence
( saveLastRead
, loadLastRead
) where
import System.Directory (getXdgDirectory, XdgDirectory(XdgData), createDirectoryIfMissing)
import System.FilePath ((</>))
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Control.Exception (try, SomeException)
import Text.Read (readMaybe)
saveLastRead :: FilePath -> Int -> IO ()
saveLastRead bPath chapterIdx = do
dataDir <- getXdgDirectory XdgData "svitak"
createDirectoryIfMissing True dataDir
let configFile = dataDir </> "last_read.txt"
-- Line 1 = Path, Line 2 = Index
let content = T.pack bPath <> T.pack "\n" <> T.pack (show chapterIdx)
TIO.writeFile configFile content
putStrLn $ "Progress saved to: " ++ configFile
loadLastRead :: IO (Maybe (FilePath, Int))
loadLastRead = do
dataDir <- getXdgDirectory XdgData "svitak"
let configFile = dataDir </> "last_read.txt"
result <- try (TIO.readFile configFile) :: IO (Either SomeException T.Text)
case result of
Left _ -> pure Nothing
Right content -> do
let linesOfFile = T.lines content
case linesOfFile of
[path, idxStr]
| Just idx <- readMaybe (T.unpack idxStr) ->
pure $ Just (T.unpack path, idx)
_ -> pure Nothing