+{-# LANGUAGE OverloadedStrings #-}
module Main where
+import Prelude hiding (length, readFile, writeFile)
+import Data.ByteString.Char8 (ByteString, length, readFile, writeFile, length)
import System.Environment (getArgs)
-import System.Exit
-import qualified Data.ByteString.Char8 as BC
-import qualified Bencode as Benc
-import qualified Metainfo as MInfo
-import qualified Tracker as T
-import qualified Text.ParserCombinators.Parsec as Parsec
-import Data.Functor
+import System.Exit (exitSuccess)
+import Text.ParserCombinators.Parsec (ParseError)
-printError :: Parsec.ParseError -> IO ()
-printError e = putStrLn $ "parse error: " ++ show e
+import Bencode (decode, BVal(..))
+import Logger (initLogger, logMessage, logStop)
+import Metainfo (announce, lengthInBytes, mkMetaInfo, info, name)
+import Peer (getPeers, getPeerResponse, handShakeMsg)
+import Tracker (connect, prepareRequest)
-genPeerId :: String
-genPeerId = "-HS0001-20150215"
+logError :: ParseError -> (String -> IO ()) -> IO ()
+logError e logMsg = logMsg $ "parse error: \n" ++ show e
-exit :: IO BC.ByteString
-exit = exitWith ExitSuccess
+peerId :: String
+peerId = "-HS0001-*-*-20150215"
+
+exit :: IO ByteString
+exit = exitSuccess
usage :: IO ()
-usage = putStrLn "usage: deluge torrent-file"
+usage = putStrLn "usage: functorrent torrent-file"
-parse :: [String] -> IO (BC.ByteString)
+parse :: [String] -> IO ByteString
parse [] = usage >> exit
-parse [a] = BC.readFile a
+parse [a] = readFile a
parse _ = exit
main :: IO ()
main = do
- args <- getArgs
- torrentStr <- parse args
- case (Benc.decode torrentStr) of
- Right d -> case (MInfo.mkMetaInfo d) of
- Nothing -> putStrLn "parse error"
- Just m -> do
- body <- (Benc.decode . BC.pack) <$> T.connect (MInfo.announce m) (T.prepareRequest d genPeerId)
- putStrLn (show body)
- Left e -> printError e
- putStrLn "done"
+ args <- getArgs
+ logR <- initLogger
+ let logMsg = logMessage logR
+ logMsg $ "Parsing input file: " ++ concat args
+ torrentStr <- parse args
+ case decode torrentStr of
+ Right d ->
+ case mkMetaInfo d of
+ Nothing -> logMsg "parse error"
+ Just m -> do
+ logMsg "Input File OK"
+
+ let len = lengthInBytes $ info m
+ (Bdict d') = d
+
+ logMsg "Trying to fetch peers: "
+ body <- connect (announce m) (prepareRequest d' peerId len)
+
+ -- TODO: Write to ~/.functorrent/caches
+ writeFile (name (info m) ++ ".cache") body
+
+ let peerResponse = show $ getPeers $ getPeerResponse body
+ logMsg $ "Peers List : " ++ peerResponse
+
+ let hsMsgLen = show $ length $ handShakeMsg d' peerId
+ logMsg $ "Hand-shake message length : " ++ hsMsgLen
+
+ Left e -> logError e logMsg
+ logStop logR