{-# LANGUAGE OverloadedStrings #-}
module Main where
-- library: text, http-conduit, xml-conduit
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Exception
import Control.Monad
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Network.HTTP.Conduit (simpleHttp)
import System.Environment (getArgs)
import qualified Text.XML as XML
import Text.XML.Cursor (($//), (&/))
import qualified Text.XML.Cursor as XML
commentsUrl :: String
commentsUrl = "https://www.reddit.com/r/programming_jp/comments/.rss"
main :: IO ()
main = do
args <- map T.pack <$> getArgs
case args of
(target:_) -> do
items <- getItems commentsUrl `catch` (\(SomeException e) -> print e >> return [])
forM_ items $ \(t, d) -> when (any (T.isInfixOf target) [t, d]) $ TIO.putStr $ T.unlines [t, d, "---"]
_ -> putStrLn "検索語句が指定されていません"
type Item = (T.Text, T.Text)
getItems :: String -> IO [Item]
getItems url = either throwIO (return . constructItems) . XML.parseLBS XML.def =<< simpleHttp url
constructItems :: XML.Document -> [Item]
constructItems doc = map (content "title" &&& content "description") (XML.fromDocument doc $// XML.element "item")
where
content name c = T.concat $ c $// XML.element name &/ XML.content