From: Ramakrishnan Muthukrishnan Date: Sun, 13 Sep 2015 07:15:35 +0000 (+0530) Subject: wip: Use reader to pass around metainfo X-Git-Url: https://git.rkrishnan.org/components/com_hotproperty/flags//%22?a=commitdiff_plain;h=24489a350fcb60839546aaa0d127c563746839e6;p=functorrent.git wip: Use reader to pass around metainfo --- diff --git a/functorrent.cabal b/functorrent.cabal index b663ef9..31cbbdb 100644 --- a/functorrent.cabal +++ b/functorrent.cabal @@ -45,7 +45,8 @@ library QuickCheck, safe, tasty, - tasty-hunit + tasty-hunit, + transformers executable functorrent main-is: Main.hs diff --git a/src/FuncTorrent/Tracker.hs b/src/FuncTorrent/Tracker.hs index 206e1b8..aac578c 100644 --- a/src/FuncTorrent/Tracker.hs +++ b/src/FuncTorrent/Tracker.hs @@ -8,6 +8,8 @@ module FuncTorrent.Tracker import Prelude hiding (lookup, splitAt) +import Control.Monad.IO.Class (liftIO) +import Control.Monad.Reader (ReaderT, ask, runReaderT) import Data.ByteString (ByteString) import Data.ByteString.Char8 as BC (pack, unpack, splitAt) import Data.Char (chr) @@ -65,14 +67,18 @@ mkTrackerResponse resp = where (ip', port') = splitAt 4 peer -- | Connect to a tracker and get peer info -tracker :: String -> Metainfo -> IO ByteString -tracker peer_id m = get (head . announceList $ m) $ mkArgs peer_id m +tracker :: String -> ReaderT Metainfo IO ByteString +tracker peer_id = do + m <- ask + let args = mkArgs peer_id m + liftIO $ get (head . announceList $ m) $ args -getTrackerResponse :: String -> Metainfo -> IO (Either ByteString TrackerResponse) -getTrackerResponse peerId m = do - resp <- tracker peerId m +getTrackerResponse :: String -> ReaderT Metainfo IO (Either ByteString TrackerResponse) +getTrackerResponse peerId = do + m <- ask + resp <- liftIO $ runReaderT (tracker peerId) m case decode resp of - Right trackerInfo -> return $ mkTrackerResponse trackerInfo + Right trackerInfo -> liftIO $ return $ mkTrackerResponse trackerInfo Left e -> return $ Left (pack (show e)) --- | URL encode hash as per RFC1738 @@ -100,3 +106,5 @@ mkArgs peer_id m = [("info_hash", pack . urlEncodeHash . B16.encode . infoHash $ ("left", pack . show . lengthInBytes $ info m), ("compact", "1"), ("event", "started")] + + diff --git a/src/main/Main.hs b/src/main/Main.hs index b86f2e4..b82d27a 100644 --- a/src/main/Main.hs +++ b/src/main/Main.hs @@ -2,6 +2,8 @@ module Main where import Prelude hiding (log, length, readFile, getContents) + +import Control.Monad.Reader(runReaderT) import Data.ByteString.Char8 (ByteString, getContents, readFile, unpack) import System.Environment (getArgs) import System.Exit (exitSuccess) @@ -49,7 +51,7 @@ main = do log "Trying to fetch peers" log $ "Trackers: " ++ head (announceList m) - trackerResp <- getTrackerResponse peerId m + trackerResp <- runReaderT (getTrackerResponse peerId) m case trackerResp of Left e -> log $ "Error" ++ unpack e Right peerList -> do