import Prelude hiding (log, length, readFile, getContents, replicate, writeFile)
import Control.Concurrent (forkIO)
-import Data.ByteString.Char8 (ByteString, getContents, readFile, writeFile, unpack, replicate)
+import Control.Concurrent.MVar (readMVar)
+import Data.ByteString.Char8 (ByteString, getContents, readFile, writeFile, replicate)
import Network (PortID (PortNumber))
import System.Environment (getArgs)
import System.Exit (exitSuccess)
import FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo)
import FuncTorrent.Peer (initPieceMap, handlePeerMsgs, pieceMapFromFile)
import qualified FuncTorrent.Server as Server
-import FuncTorrent.Tracker (peers, getTrackerResponse)
+import FuncTorrent.Tracker (connectedPeers, initialTrackerState, trackerLoop)
logError :: String -> (String -> IO ()) -> IO ()
logError e logMsg = logMsg $ "parse error: \n" ++ e
-- if we had downloaded the file before (partly or completely)
-- then we should check the current directory for the existence
-- of the file and then update the map of each piece' availability.
- -- This can be donw by reading each piece and verifying the checksum.
+ -- This can be done by reading each piece and verifying the checksum.
-- If the checksum does not match, we don't have that piece.
let filePath = name (info m) -- really this is just the file name, not file path
fileLen = lengthInBytes (info m)
(serverSock, (PortNumber portnum)) <- Server.start
log $ "server started on " ++ show portnum
log "Trying to fetch peers"
- forkIO $ Server.run serverSock peerId m pieceMap
+ _ <- forkIO $ Server.run serverSock peerId m pieceMap
log $ "Trackers: " ++ head (announceList m)
- trackerResp <- getTrackerResponse portnum peerId m
- case trackerResp of
- Left e -> log $ "Error" ++ unpack e
- Right peerList -> do
- log $ "Peers List : " ++ (show . peers $ peerList)
- let p1 = head (peers peerList)
- handlePeerMsgs p1 peerId m pieceMap True
- logStop logR
+ -- (tstate, errstr) <- runTracker portnum peerId m
+ tstate <- initialTrackerState $ lengthInBytes $ info m
+ _ <- forkIO $ trackerLoop portnum peerId m tstate >> return ()
+ ps <- readMVar (connectedPeers tstate)
+ log $ "Peers List : " ++ (show ps)
+ let p1 = head ps
+ handlePeerMsgs p1 peerId m pieceMap True
+ logStop logR