From: Ramakrishnan Muthukrishnan Date: Mon, 16 Feb 2015 11:08:10 +0000 (+0530) Subject: refactoring X-Git-Url: https://git.rkrishnan.org/pf/content/%22news.html/$top_link?a=commitdiff_plain;h=bd4a5e2c6375186e9bb4587b22348c0a47816a06;p=functorrent.git refactoring --- diff --git a/src/Main.hs b/src/Main.hs index 24bd9a9..fa465de 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -36,6 +36,6 @@ main = do Nothing -> putStrLn "parse error" Just m -> do body <- BC.pack <$> T.connect (MInfo.announce m) (T.prepareRequest d genPeerId) - putStrLn (show (P.getPeers body)) + putStrLn (show (P.getPeers (P.getPeerResponse body))) Left e -> printError e putStrLn "done" diff --git a/src/Peer.hs b/src/Peer.hs index 967a212..d30f9b0 100644 --- a/src/Peer.hs +++ b/src/Peer.hs @@ -6,6 +6,7 @@ import qualified Data.Map as M import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Base16 as B16 import qualified Data.List as L +import Control.Applicative ((<$>)) data Peer = Peer { ip :: String , port :: Integer @@ -18,20 +19,22 @@ data PeerResp = PeerResponse { interval :: Maybe Integer toInt :: String -> Integer toInt = read -getPeers :: BC.ByteString -> [Peer] -getPeers body = case (Benc.decode body) of - Right (Benc.Bdict peerM) -> - let interval' = M.lookup (Benc.Bstr (BC.pack "lookup")) peerM - (Benc.Bstr peersBS) = peerM M.! (Benc.Bstr (BC.pack "peers")) - in - map (\peer -> let (ip', port') = BC.splitAt 4 peer - in - Peer { ip = toIPNum ip', - port = toPortNum port' - }) - (U.splitN 6 peersBS) - where toPortNum = read . ("0x" ++) . BC.unpack . B16.encode - toIPNum = (L.intercalate ".") . - map (show . toInt . ("0x" ++) . BC.unpack) . - (U.splitN 2) . B16.encode - Left _ -> [] +getPeers :: PeerResp -> [Peer] +getPeers = peers + +getPeerResponse :: BC.ByteString -> PeerResp +getPeerResponse body = case (Benc.decode body) of + Right (Benc.Bdict peerM) -> + let (Just (Benc.Bint i)) = M.lookup (Benc.Bstr (BC.pack "lookup")) peerM + (Benc.Bstr peersBS) = peerM M.! (Benc.Bstr (BC.pack "peers")) + pl = map (\peer -> let (ip', port') = BC.splitAt 4 peer + in Peer { ip = toIPNum ip', + port = toPortNum port' + }) + (U.splitN 6 peersBS) + in PeerResponse { interval = Just i, peers = pl } + where toPortNum = read . ("0x" ++) . BC.unpack . B16.encode + toIPNum = (L.intercalate ".") . + map (show . toInt . ("0x" ++) . BC.unpack) . + (U.splitN 2) . B16.encode + Left _ -> PeerResponse { interval = Nothing, peers = [] }