rosa/Main.hs

75 lines
2.0 KiB
Haskell
Raw Normal View History

2014-11-21 23:05:16 +01:00
{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
2014-11-21 00:14:57 +01:00
2014-12-27 16:47:07 +01:00
import Network.Wreq (get, responseBody)
import Data.Aeson (decode, toJSON)
import Data.Maybe (fromJust)
2014-11-21 23:05:16 +01:00
import Data.HashMap.Strict (delete)
2014-11-20 21:39:25 +01:00
import Control.Lens
2014-11-23 15:16:25 +01:00
import Control.Applicative
2014-11-21 23:05:16 +01:00
import System.Console.ArgParser
import System.Process
2014-11-25 00:22:54 +01:00
import qualified Data.ByteString.Lazy.Char8 as C
2014-11-22 17:16:33 +01:00
import Json
2014-11-21 23:05:16 +01:00
2014-11-25 00:22:54 +01:00
2014-11-22 17:16:33 +01:00
data ProgArgs = ProgArgs
2014-12-27 16:40:00 +01:00
{ name :: String
, url :: String
2014-12-27 03:35:12 +01:00
, dnschain :: Bool
2014-12-27 16:40:00 +01:00
, block :: Bool
, raw :: Bool
2014-12-27 03:35:12 +01:00
} deriving (Show)
2014-11-21 00:14:57 +01:00
2014-11-25 00:22:54 +01:00
2014-11-22 17:16:33 +01:00
parser :: ParserSpec ProgArgs
parser = ProgArgs
2014-12-27 16:40:00 +01:00
`parsedBy` reqPos "name" `Descr` "Namecoin name id"
2014-12-27 03:35:12 +01:00
`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"
2014-11-21 00:14:57 +01:00
2014-11-25 00:22:54 +01:00
2014-11-23 15:16:25 +01:00
interface :: IO (CmdLnInterface ProgArgs)
interface =
2014-12-27 16:40:00 +01:00
(`setAppDescr` "Query the namecoin blockchain") <$>
2014-12-27 03:35:12 +01:00
(`setAppEpilog` "Stat rosa pristina nomine, nomina nuda tenemus.") <$>
mkApp parser
2014-11-23 15:16:25 +01:00
2014-11-25 00:22:54 +01:00
main :: IO ()
main = interface >>= flip runApp exec
exec :: ProgArgs -> IO ()
2014-12-27 03:32:19 +01:00
exec ProgArgs{..} = do
2014-12-27 03:35:12 +01:00
if dnschain
then handleDnschain url name raw
else handleLocal name block
2014-11-25 00:22:54 +01:00
2014-11-25 00:20:24 +01:00
handleLocal :: String -> Bool -> IO ()
handleLocal name block = do
2014-12-27 03:35:12 +01:00
out <- readProcess "namecoind" ["name_show", name] ""
case decode (C.pack out) of
Just res -> do
2014-12-27 16:34:29 +01:00
pprint $ reparse (res |: "value")
if block then pprint extra else return ()
2014-12-27 03:35:12 +01:00
where
reparse = fromJust . decode . C.pack
extra = toJSON $ delete "value" res
Nothing -> putStrLn "Error parsing data"
2014-11-25 00:20:24 +01:00
2014-11-25 00:22:54 +01:00
2014-11-25 00:20:24 +01:00
handleDnschain :: String -> String -> Bool -> IO ()
handleDnschain url name raw = do
2014-12-27 03:35:12 +01:00
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"