1 {-# OPTIONS_GHC -cpp #-}
4 module HTTP
( fetchUrl
, postUrl
, request_url
, wait_next_url
) where
6 import Darcs
.Global
( debugFail
)
9 import Control
.Monad
( when )
10 import Data
.IORef
( newIORef
, readIORef
, writeIORef
, IORef
)
13 import System
.Environment
( getEnv )
14 import System
.IO.Error
( ioeGetErrorString )
15 import System
.IO.Unsafe
( unsafePerformIO
)
16 import Darcs
.Global
( debugMessage
)
17 import qualified Data
.ByteString
as B
18 import qualified Data
.ByteString
.Char8
as BC
21 fetchUrl
:: String -> IO String
25 -> String -- ^ mime type
28 request_url
:: String -> FilePath -> a
-> IO String
29 wait_next_url
:: IO (String, String)
34 headers
= [Header HdrUserAgent
$ "darcs-HTTP/" ++ PACKAGE_VERSION
]
36 fetchUrl url
= case parseURI url
of
37 Nothing
-> fail $ "Invalid URI: " ++ url
38 Just uri
-> do debugMessage
$ "Fetching over HTTP: "++url
40 when (not $ null proxy
) $
41 debugFail
"No proxy support for HTTP package yet (try libcurl or libwww)!"
42 resp
<- simpleHTTP
$ Request
{ rqURI
= uri
,
47 Right res
@Response
{ rspCode
= (2,0,0) } -> return (rspBody res
)
48 Right Response
{ rspCode
= (x
,y
,z
) } ->
49 debugFail
$ "HTTP " ++ show x
++ show y
++ show z
++ " error getting " ++ show uri
50 Left err
-> debugFail
$ show err
52 postUrl url body mime
= case parseURI url
of
53 Nothing
-> fail $ "Invalid URI: " ++ url
54 Just uri
-> do debugMessage
$ "Posting to HTTP: "++url
56 when (not $ null proxy
) $
57 debugFail
"No proxy support for HTTP package yet (try libcurl or libwww)!"
58 resp
<- simpleHTTP
$ Request
{ rqURI
= uri
,
60 rqHeaders
= headers
++ [Header HdrContentType mime
,
61 Header HdrAccept
"text/plain",
62 Header HdrContentLength
63 (show $ length body
) ],
66 Right res
@Response
{ rspCode
= (2,y
,z
) } -> do
67 putStrLn $ "Success 2" ++ show y
++ show z
68 putStrLn (rspBody res
)
70 Right res
@Response
{ rspCode
= (x
,y
,z
) } -> do
71 putStrLn $ rspBody res
72 debugFail
$ "HTTP " ++ show x
++ show y
++ show z
++ " error posting to " ++ show uri
73 Left err
-> debugFail
$ show err
75 requestedUrl
:: IORef
(String, FilePath)
76 requestedUrl
= unsafePerformIO
$ newIORef
("", "")
78 request_url u f _
= do
79 (u
', _
) <- readIORef requestedUrl
81 then do writeIORef requestedUrl
(u
, f
)
83 else return "URL already requested"
86 (u
, f
) <- readIORef requestedUrl
88 then return ("", "No URL requested")
89 else do writeIORef requestedUrl
("", "")
90 e
<- (fetchUrl u
>>= \s
-> B
.writeFile f
(BC
.pack s
) >> return "") `
catch` h
92 where h
= return . ioeGetErrorString
97 `
catch`
\_
-> getEnv "HTTP_PROXY"
98 `
catch`
\_
-> return ""
101 fetchUrl _
= debugFail
"Network.HTTP does not exist"
102 postUrl _ _ _
= debugFail
"Cannot use http POST because darcs was not compiled with Network.HTTP."
104 request_url _ _ _
= debugFail
"Network.HTTP does not exist"
105 wait_next_url
= debugFail
"Network.HTTP does not exist"