{-# LANGUAGE OverloadedStrings #-} module AdListener ( listenToNewAds ) where import Data.List (intersperse) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Control.Concurrent (threadDelay) import Fetch (fetchResumes, fetchAds) import Model.Ad import Model.URL import Model.Resume import qualified View.Plain.Ad as P import qualified View.Html.Ad as H import Page import Parser.Detail import Mail (sendMail) import Config (Config) import qualified Config as C import Time (getCurrentFormattedTime) listenToNewAds :: Config -> IO () listenToNewAds config = do eitherResumes <- fetchResumes (C.url config) case eitherResumes of Left error -> showErrorAndListenBack config [] error Right resumes -> let newURLs = map url resumes in do putStrLn "Listening for new ads…" waitOneMinute listenToNewAdsWithViewedURLs config newURLs listenToNewAdsWithViewedURLs :: Config -> [URL] -> IO () listenToNewAdsWithViewedURLs config viewedURLs = do eitherResumes <- fetchResumes (C.url config) case eitherResumes of Left error -> showErrorAndListenBack config viewedURLs error Right resumes -> listenToNewAdsWithResumes config viewedURLs resumes listenToNewAdsWithResumes :: Config -> [URL] -> [Resume] -> IO () listenToNewAdsWithResumes config viewedURLs resumes = let (newURLs, newResumes) = getNewResumes viewedURLs resumes in do eitherNewAds <- fetchAds newResumes case eitherNewAds of Left error -> showErrorAndListenBack config viewedURLs error Right newAds -> do time <- getCurrentFormattedTime if not (null newAds) then let message = P.renderConsoleAds time newAds in do T.putStrLn message trySendMail config newAds else return () waitOneMinute listenToNewAdsWithViewedURLs config (viewedURLs ++ newURLs) trySendMail :: Config -> [Ad] -> IO () trySendMail config ads = case C.mailTo config of Nothing -> return () Just mailTo -> let (title, plainBody) = P.renderAds ads htmlBody = H.renderAds ads in do eitherMailSuccess <- sendMail mailTo title plainBody htmlBody case eitherMailSuccess of Right () -> putStrLn "\nMail sent." Left error -> T.putStrLn . T.concat $ [ "\nError sending mail: " , error ] showErrorAndListenBack :: Config -> [URL] -> Text -> IO () showErrorAndListenBack config viewedURLs error = do T.putStrLn error waitOneMinute listenToNewAdsWithViewedURLs config viewedURLs waitOneMinute :: IO () waitOneMinute = threadDelay (1000 * 1000 * 60)