]> git.rkrishnan.org Git - functorrent.git/blob - src/main/Main.hs
functorrent.cabal: avoid double compilation, one for lib, another for exe
[functorrent.git] / src / main / Main.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 module Main where
3
4 import Prelude hiding (log, length, readFile, getContents)
5 import Data.ByteString.Char8 (ByteString, getContents, readFile, unpack)
6 import System.Environment (getArgs)
7 import System.Exit (exitSuccess)
8 import System.Directory (doesFileExist)
9
10 import FuncTorrent.Logger (initLogger, logMessage, logStop)
11 import FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo)
12 import FuncTorrent.Peer (handlePeerMsgs)
13 import FuncTorrent.Tracker (peers, getTrackerResponse)
14
15 logError :: String -> (String -> IO ()) -> IO ()
16 logError e logMsg = logMsg $ "parse error: \n" ++ e
17
18 peerId :: String
19 peerId = "-HS0001-*-*-20150215"
20
21 exit :: IO ByteString
22 exit = exitSuccess
23
24 usage :: IO ()
25 usage = putStrLn "usage: functorrent torrent-file"
26
27 parse :: [String] -> IO ByteString
28 parse [] = getContents
29 parse [a] = do
30   fileExist <- doesFileExist a
31   if fileExist
32     then readFile a
33     else error "file does not exist"
34 parse _ = exit
35
36 main :: IO ()
37 main = do
38     args <- getArgs
39     logR <- initLogger
40     let log = logMessage logR
41     log "Starting up functorrent"
42     log $ "Parsing arguments " ++ concat args
43     torrentStr <- parse args
44     case torrentToMetainfo torrentStr of
45      Left e -> logError e log
46      Right m -> do
47        log "Input File OK"
48        log $ "Downloading file : " ++ name (info m)
49        log "Trying to fetch peers"
50
51        log $ "Trackers: " ++ head (announceList m)
52        trackerResp <- getTrackerResponse m peerId
53        case  trackerResp of
54         Left e -> log $ "Error" ++ unpack e
55         Right peerList -> do
56           log $ "Peers List : " ++ (show . peers $ peerList)
57           let p1 = head (peers peerList)
58           handlePeerMsgs p1 m peerId
59     logStop logR