Skip to content

Instantly share code, notes, and snippets.

@JosephMoniz
Created January 20, 2013 19:06
Show Gist options
  • Save JosephMoniz/4580837 to your computer and use it in GitHub Desktop.
Save JosephMoniz/4580837 to your computer and use it in GitHub Desktop.
Hacker news reader from the command line
import Network.HTTP
import Text.HTML.TagSoup
import System
import System.Process
import Control.Monad
import IO
hackerNewsRSSFeedURL = "http://news.ycombinator.com/rss"
fileURLCache = ".hnCache"
getUrl :: String -> IO (String)
getUrl url = simpleHTTP(getRequest url) >>= getResponseBody
getTitles :: [Tag String] -> [String]
getTitles = getTextFromTagsWithName "title"
getLinks :: [Tag String] -> [String]
getLinks = getTextFromTagsWithName "link"
getTextFromTagsWithName :: String -> [Tag String] -> [String]
getTextFromTagsWithName _ [] = []
getTextFromTagsWithName name (x:xs) =
case isTagOpenName name x of
True -> getText xs : getTextFromTagsWithName name xs
False -> getTextFromTagsWithName name xs
getText :: [Tag String] -> String
getText [] = ""
getText (x:xs) = fromTagText x
displayWithKey :: [String] -> [String]
displayWithKey [] = []
displayWithKey (x:xs) = zipWith (\ a b -> (show a) ++ " - " ++ b) [0..] (x:xs)
runAction :: [String] -> IO()
runAction [] = do
-- Fetch the feed and display the indexed titles
rawRSS <- getUrl hackerNewsRSSFeedURL
tags <- return $ parseTags rawRSS
mapM_ (\ x -> hPutStrLn stdout x) $ displayWithKey $ getTitles tags
-- Store the links
store <- openFile fileURLCache WriteMode
mapM_ (\ x -> hPutStrLn store x) $ getLinks tags
hClose store
runAction [(x:xs)] = do
urls <- readFile fileURLCache
pHandle <- system $ getCommand (x:xs) urls
hPutStrLn stdout "done"
getCommand (x:xs) (y:ys) = "open " ++ lines (y:ys) !! (read (x:xs))
main = do
args <- getArgs
runAction args
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment