aboutsummaryrefslogtreecommitdiff
path: root/src/F2Md/Config.hs
blob: 46a9a755f148ae7e2ef31c1b7666476ca0159499 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
{-# LANGUAGE DeriveGeneric #-}

module F2Md.Config
  ( getUserdata
  , FeedUserdata(..)
  , updateLastUpdated
  , updateLastUpdated'
  ) where

import Control.Monad
import Data.List
import F2Md.Utils
import F2Md.Types
import Data.Maybe
import Data.Text (Text)
import Data.Time
import GHC.Generics
import qualified Data.HashMap.Strict as HM
import Data.Aeson

data Config = Config
  { dbPath :: String
  , maildir :: String
  , feeds :: [Text]
  } deriving (Generic, Show)

instance FromJSON Config

data FeedUserdata = FeedUserdata
  { fuUrl :: Text
  , fuLastUpdated :: Maybe ZonedTime } deriving (Show)

getUserdata :: FilePath -> IO ([FeedUserdata], Maybe FilePath, Maybe FilePath)
getUserdata file = do
  config <- decodeFileStrict file
  case config of
    Nothing -> return ([], Nothing, Nothing)
    Just config' -> do
      feedData <- getUserdata' config'
      maildir' <- expandPath $ maildir config'
      dbPath' <- expandPath $ dbPath config'
      return (feedData, Just maildir', Just dbPath')

getUserdata' :: Config -> IO [FeedUserdata]
getUserdata' (Config dbPath _ feeds) = do
  decoded <- getLastUpdatedMap dbPath
  return $ map (\url -> FeedUserdata url $ HM.lookup url decoded) feeds

getLastUpdatedMap :: FilePath -> IO (HM.HashMap Text ZonedTime)
getLastUpdatedMap dbPath =
  fromMaybe (HM.fromList []) <$> (decodeFileStrict =<< expandPath dbPath)

updateLastUpdated' :: FilePath -> FeedUserdata -> [Message] -> IO ()
updateLastUpdated' path feed msgs =
  unless (null msgs) $ do
  decoded <- getLastUpdatedMap path
  encodeFile path $
    HM.insert
    (fuUrl feed)
    (utcToZonedTime (zonedTimeZone $ mDate $ head msgs) . maximum $
                    (zonedTimeToUTC . mDate) <$> msgs)
    decoded

updateLastUpdated :: FilePath -> [FeedUserdata] -> [[Message]] -> IO ()
updateLastUpdated path feeds feedMsgs = do
  mapM_ (\(feed, msgs) -> updateLastUpdated' path feed msgs)
    (zip feeds feedMsgs)