summaryrefslogtreecommitdiff
path: root/src/Data/Torrent/Magnet.hs
blob: df928b66bc1bde79f5f52078b3d711dd15c26237 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
-- |
--   Copyright   :  (c) Sam Truzjan 2013
--   License     :  BSD3
--   Maintainer  :  pxqr.sta@gmail.com
--   Stability   :  experimental
--   Portability :  portable
--
--   Parsing and rendering of magnet URIs.
--
--   For more info see:
--   <http://magnet-uri.sourceforge.net/magnet-draft-overview.txt>
--
--   Bittorrent specific info:
--   <http://www.bittorrent.org/beps/bep_0009.html>
--
module Data.Torrent.Magnet
       ( -- * Magnet
         Magnet(..)
       , nullMagnet
       , parseMagnet
       , renderMagnet

         -- ** Extra
       , fromURI
       , toURI
       ) where

import Control.Applicative
import Control.Monad
import Data.ByteString as BS
import Data.ByteString.Base16 as Base16
import Data.ByteString.Base32 as Base32
import Data.Map as M
import Data.Maybe
import Data.List as L
import Data.URLEncoded as URL
import Data.String
import Data.Text as T
import Data.Text.Encoding as T
import Network.URI
import Text.Read

import Data.Torrent.InfoHash


{-----------------------------------------------------------------------
-- URN
-----------------------------------------------------------------------}

type NamespaceId = [Text]

btih :: NamespaceId
btih  = ["btih"]

-- | Uniform Resource Name - location-independent, resource
-- identifier.
data URN = URN
    { urnNamespace :: NamespaceId
    , urnString    :: Text
    } deriving (Eq, Ord)

instance Show URN where
  showsPrec n = showsPrec n . T.unpack . renderURN

instance IsString URN where
  fromString = fromMaybe def . parseURN . T.pack
    where
      def = error "unable to parse URN"

instance URLShow URN where
  urlShow = T.unpack . renderURN

parseURN :: Text -> Maybe URN
parseURN str = case T.split (== ':') str of
    uriScheme : body
      | T.toLower uriScheme == "urn" -> mkURN body
      |          otherwise           -> Nothing
    [] -> Nothing
  where
    mkURN [] = Nothing
    mkURN xs = Just $ URN
        { urnNamespace = L.init xs
        , urnString    = L.last xs
        }

renderURN :: URN -> Text
renderURN URN {..}
  = T.intercalate ":" $ "urn" : urnNamespace ++ [urnString]

urnToInfoHash :: URN -> Maybe InfoHash
urnToInfoHash  (URN {..})
  | urnNamespace /= btih = Nothing
  |      hashLen == 20   = Just $ InfoHash hashStr
  |      hashLen == 32   = Just $ InfoHash $ Base32.decode hashStr
  |      hashLen == 40   = let (ihStr, inv) = Base16.decode hashStr
                           in if BS.length inv == 0
                              then Just $ InfoHash ihStr
                              else Nothing
  |        otherwise     = Nothing
  where
    hashLen = BS.length hashStr
    hashStr = T.encodeUtf8 urnString

infoHashToURN :: InfoHash -> URN
infoHashToURN = URN btih . T.pack . show

{-----------------------------------------------------------------------
--  Magnet
-----------------------------------------------------------------------}

-- TODO multiple exact topics
-- TODO supplement

-- | An URI used to identify torrent.
data Magnet = Magnet
    { -- | Resource hash.
      exactTopic  :: !InfoHash
      -- | Might be used to display name while waiting for metadata.
    , displayName :: Maybe Text
      -- | Size of the resource in bytes.
    , exactLength :: Maybe Integer

    , manifest :: Maybe String
      -- | Search string.
    , keywordTopic :: Maybe String

    , acceptableSource :: Maybe URI
    , exactSource      :: Maybe URI

    , tracker :: Maybe URI

    , supplement :: Map Text Text
    } deriving (Eq, Ord)

instance Show Magnet where
  show = renderMagnet
  {-# INLINE show #-}

instance Read Magnet where
  readsPrec _ xs
      | Just m <- parseMagnet mstr = [(m, rest)]
      | otherwise = []
    where
      (mstr, rest) = L.break (== ' ') xs

instance IsString Magnet where
  fromString = fromMaybe def . parseMagnet
    where
      def = error "unable to parse magnet"

instance URLEncode Magnet where
  urlEncode = toQuery
  {-# INLINE urlEncode #-}

-- | Set exact topic only, other params are empty.
nullMagnet :: InfoHash -> Magnet
nullMagnet u = Magnet
    { exactTopic   = u
    , displayName  = Nothing
    , exactLength  = Nothing
    , manifest     = Nothing
    , keywordTopic = Nothing
    , acceptableSource = Nothing
    , exactSource      = Nothing
    , tracker    = Nothing
    , supplement = M.empty
    }

fromQuery :: URLEncoded -> Either String Magnet
fromQuery q
  | Just urnStr   <- URL.lookup ("xt" :: String) q
  , Just urn      <- parseURN $ T.pack urnStr
  , Just infoHash <- urnToInfoHash urn
  = return $ Magnet
      { exactTopic  = infoHash
      , displayName = T.pack    <$> URL.lookup ("dn" :: String) q
      , exactLength = readMaybe =<< URL.lookup ("xl" :: String) q

      , manifest     = URL.lookup ("mt" :: String) q
      , keywordTopic = URL.lookup ("kt" :: String) q

      , acceptableSource = parseURI =<< URL.lookup ("as" :: String) q
      , exactSource      = parseURI =<< URL.lookup ("xs" :: String) q

      , tracker    = parseURI =<< URL.lookup ("tr" :: String) q
      , supplement = M.empty
      }

  | otherwise = Left "exact topic not defined"

toQuery :: Magnet -> URLEncoded
toQuery Magnet {..}
    =  s "xt" %=  infoHashToURN exactTopic
    %& s "dn" %=? (T.unpack <$> displayName)
    %& s "xl" %=? exactLength
    %& s "mt" %=? manifest
    %& s "kt" %=? keywordTopic
    %& s "as" %=? acceptableSource
    %& s "xs" %=? exactSource
    %& s "tr" %=? tracker
  where
    s :: String -> String; s = id

magnetScheme :: URI
magnetScheme = URI
    { uriScheme    = "magnet:"
    , uriAuthority = Nothing
    , uriPath      = ""
    , uriQuery     = ""
    , uriFragment  = ""
    }

isMagnetURI :: URI -> Bool
isMagnetURI u = u { uriQuery = "" } == magnetScheme

-- | The same as 'parseMagnet' but useful if you alread have a parsed
-- uri.
fromURI :: URI -> Either String Magnet
fromURI u @ URI {..}
  | not (isMagnetURI u) = Left "this is not a magnet link"
  |      otherwise      = importURI u >>= fromQuery

-- | The same as 'renderMagnet' but useful if you need an uri.
toURI :: Magnet -> URI
toURI m = magnetScheme %? urlEncode m

etom :: Either a b -> Maybe b
etom = either (const Nothing) Just

-- | Try to parse magnet link from urlencoded string.
parseMagnet :: String -> Maybe Magnet
parseMagnet = parseURI >=> etom . fromURI

-- | Render magnet link to urlencoded string
renderMagnet :: Magnet -> String
renderMagnet = show . toURI