summaryrefslogtreecommitdiff
path: root/bittorrent/examples/Client.hs
blob: 267116768dc5bb6d820eb1f50516d0caebc8ac3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{-# LANGUAGE RankNTypes                #-}
{-# LANGUAGE CPP                       #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RecordWildCards           #-}
module Main (main) where
import Control.Concurrent
import Control.Monad.Trans
import Data.Maybe
import Options.Applicative
import System.Environment
import System.Exit
import System.IO
import Text.Read

import Network.BitTorrent

#if MIN_VERSION_optparse_applicative(0,13,0)
-- maybeReader imported from Options.Applicative.Builder
#elif MIN_VERSION_optparse_applicative(0,11,0)
maybeReader f = eitherReader (maybe (Left ":(") Right . f)
#else
maybeReader f = f
#endif

{-----------------------------------------------------------------------
--  Command line arguments
-----------------------------------------------------------------------}

data TorrentBox = forall s. TorrentSource s => TorrentBox { unTorrentBox :: s }

data Args = Args
  { topic       :: TorrentBox
  , contentDir  :: FilePath
  }

argsParser :: Parser Args
argsParser = Args <$> (TorrentBox <$> infohashP <|> TorrentBox <$> torrentP)
                  <*> destDirP
  where
    infohashP :: Parser InfoHash
    infohashP = argument (maybeReader readMaybe)
                (metavar "SHA1"     <> help "infohash of torrent file")

    torrentP :: Parser FilePath
    torrentP  = argument (maybeReader Just)
                ( metavar "FILE"
               <> help    "A .torrent file"
                )

    destDirP :: Parser FilePath
    destDirP  = argument (maybeReader Just)
                ( metavar "DIR"
               <> help    "Directory to put content"
                )

argsInfo :: ParserInfo Args
argsInfo = info (helper <*> argsParser)
   ( fullDesc
  <> progDesc "A simple CLI bittorrent client"
  <> header   "foo"
   )

{-----------------------------------------------------------------------
--  Client
-----------------------------------------------------------------------}

run :: Args -> BitTorrent ()
run (Args (TorrentBox t) dir)  = do
  h <- openHandle dir t
  start h
  liftIO $ threadDelay 10000000000

main :: IO ()
main = execParser argsInfo >>= simpleClient . run