packages feed

funbot-0.3: src/FunBot/Sources/FeedWatcher.hs

{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module FunBot.Sources.FeedWatcher
    ( feedWatcherSource
    )
where

import Data.Maybe (fromMaybe)
import Data.Time.Units
import FunBot.Config (feedVisitInterval)
import FunBot.ExtEvents (ExtEvent (NewsEvent), NewsItem (..))
import FunBot.Types
import Network.IRC.Fun.Bot.Logger
import Text.Feed.Query
import Web.Feed.Collect (run)

import qualified Data.HashMap.Lazy as M

makeItem label ftitle item = NewsEvent $ NewsItem
    { itemFeedLabel = label
    , itemFeedTitle = Just ftitle
    , itemTitle     = fromMaybe "(no title)" $ getItemTitle item
    , itemAuthor    = getItemAuthor item
    , itemUrl       = getItemLink item
    }

collect push label _url feed item =
    push $ makeItem label (getFeedTitle feed) item

logError logger err = logLine logger $ show err

feeds state =
    let l = M.toList $ watchedFeeds $ bsSettings state
        f (label, (url, _spec)) = (label, url)
    in  map f l

feedWatcherSource :: FilePath -> BotState -> ExtEventSource
feedWatcherSource file state _config _env push _pushMany mkLogger = do
    logger <- mkLogger file
    putStrLn "Bot: Feed watcher source loop running"
    run
        (collect push)
        Nothing
        (logError logger)
        Nothing
        feedVisitInterval
        3
        (feeds state)