{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} -- | Main module module Main where -- Rosa modules import Json -- Networking import Namecoin (rpcRequest, uri) import qualified Network.URI.Encode as U -- IO import Options.Applicative import System.Directory (XdgDirectory(..), getXdgDirectory) import qualified Data.Text.IO as T -- Data manipulation import Data.Aeson (Value(..), encode, decode, toJSON) import Data.Aeson.KeyMap (delete) import Data.ByteString.Lazy.Char8 (pack, unpack) -- Misc import Data.Maybe (fromMaybe) import Control.Monad (when) -- * CLI interface -- | Program arguments record data Options = Options { name :: String , conf :: Maybe FilePath , block :: Bool , raw :: Bool } -- | Program arguments parser options :: Parser Options options = Options <$> strArgument ( metavar "NAME" <> help "Namecoin name id" ) <*> (optional $ strOption $ long "conf" <> short 'c' <> metavar "FILE" <> help "Use custom namecoin config file" ) <*> switch ( long "block" <> short 'b' <> help "Show blockchain data" ) <*> switch ( long "raw" <> short 'r' <> help "Print raw JSON data" ) -- | Program description description :: ParserInfo Options description = info (helper <*> options) ( fullDesc <> progDesc "Query the namecoin blockchain" <> footer "Stat rosa pristina nomine, nomina nuda tenemus." ) -- * Program -- | Main function main :: IO () main = execParser description >>= exec where exec Options{..} = doLocal name raw block conf -- | Load namecoin configuration apiURI :: Maybe FilePath -> IO String apiURI path = do path <- flip fromMaybe path <$> getXdgDirectory XdgConfig "namecoin" res <- uri <$> T.readFile path case res of Left err -> fail ("Couldn't load the configuration: " ++ err) Right uri -> return uri -- | Connect to local namecoin node doLocal :: String -> Bool -> Bool -> Maybe FilePath -> IO () doLocal name raw block conf = do uri <- apiURI conf req <- rpcRequest uri "name_show" [name] case req of Left err -> putStrLn ("The lookup failed: " ++ err) Right (Object res) -> do if raw then putStrLn (unpack $ encode res) else do pprint $ tryParse (res |: "value") when block (pprint blockInfo) where tryParse = fromMaybe (res |. "value") . decode . pack blockInfo = toJSON (delete "value" res)