-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetaInfo.hs
More file actions
52 lines (41 loc) · 1.85 KB
/
MetaInfo.hs
File metadata and controls
52 lines (41 loc) · 1.85 KB
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
module MetaInfo where
import BEncodeI
import HTorrentPrelude
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString as BS
import Network.URI
import Text.Parsec hiding ((<|>))
data MetaInfo = MetaInfo {_announce :: URI, _info :: Info} deriving Show
data Info = Info { _name :: String,
_piece_length :: Int,
_pieceHashes :: ByteString,
_file :: Either Int [File],
_hash :: ByteString } deriving Show
data File = File {_fileLength :: Int, _path :: String} deriving Show
$(makeLenses ''MetaInfo)
$(makeLenses ''Info)
$(makeLenses ''File)
parseFile :: BEncodeI -> Maybe File
parseFile b = File <$>
bLookup "length" bInt b <*>
bLookup "path" bString b
parseInfo :: BEncodeI -> ReaderT ByteString Maybe Info
parseInfo b = Info <$> n <*> p <*> ps <*> (Left <$> l <|> Right <$> fs) <*> getHash b
where n = lift (bLookup "name" bString b)
p = lift (bLookup "piece length" bInt b)
ps = lift (fromString <$> bLookup "pieces" bString b)
l = lift (bLookup "length" bInt b)
fs = lift (bLookup "files" bList b >>= mapM parseFile)
getHash :: BEncodeI -> ReaderT ByteString Maybe ByteString
getHash b = reader (SHA1.hash . BS.take (e - s) . BS.drop s)
where s = fromIntegral (_start b)
e = fromIntegral (_end b)
parseMetaInfo :: BEncodeI -> ReaderT ByteString Maybe MetaInfo
parseMetaInfo b = MetaInfo <$> a <*> i
where a = lift (bLookup "announce" bString b >>= parseURI)
i = lift (bLookupI "info" b) >>= parseInfo
readTorrent :: String -> IO (Maybe MetaInfo)
readTorrent s = readMetaInfo s <$> BS.readFile s
readMetaInfo :: String -> ByteString -> Maybe MetaInfo
readMetaInfo s bs = runReaderT (lift b >>= parseMetaInfo) bs
where b = runParser parseBEncodeI 0 s bs ^? _Right