rosa/Main.hs
2014-12-27 16:47:07 +01:00

75 lines
2.0 KiB
Haskell

{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
import Network.Wreq (get, responseBody)
import Data.Aeson (decode, toJSON)
import Data.Maybe (fromJust)
import Data.HashMap.Strict (delete)
import Control.Lens
import Control.Applicative
import System.Console.ArgParser
import System.Process
import qualified Data.ByteString.Lazy.Char8 as C
import Json
data ProgArgs = ProgArgs
{ name :: String
, url :: String
, dnschain :: Bool
, block :: Bool
, raw :: Bool
} deriving (Show)
parser :: ParserSpec ProgArgs
parser = ProgArgs
`parsedBy` reqPos "name" `Descr` "Namecoin name id"
`andBy` optFlag "http://dns.dnschain.net/" "url"
`Descr` "Use custom api url"
`andBy` boolFlag "dnschain" `Descr` "Use dnschain api"
`andBy` boolFlag "block" `Descr` "Show blockchain data (require local connecton)"
`andBy` boolFlag "raw" `Descr` "Print raw JSON data"
interface :: IO (CmdLnInterface ProgArgs)
interface =
(`setAppDescr` "Query the namecoin blockchain") <$>
(`setAppEpilog` "Stat rosa pristina nomine, nomina nuda tenemus.") <$>
mkApp parser
main :: IO ()
main = interface >>= flip runApp exec
exec :: ProgArgs -> IO ()
exec ProgArgs{..} = do
if dnschain
then handleDnschain url name raw
else handleLocal name block
handleLocal :: String -> Bool -> IO ()
handleLocal name block = do
out <- readProcess "namecoind" ["name_show", name] ""
case decode (C.pack out) of
Just res -> do
pprint $ reparse (res |: "value")
if block then pprint extra else return ()
where
reparse = fromJust . decode . C.pack
extra = toJSON $ delete "value" res
Nothing -> putStrLn "Error parsing data"
handleDnschain :: String -> String -> Bool -> IO ()
handleDnschain url name raw = do
req <- get (url ++ name)
let body = req ^. responseBody
if raw
then print body
else putStrLn $
case decode body of
Just res -> repr res
Nothing -> "Error parsing data"