hs-hath-1.4.0: src/Hath/Download.hs
-- | HTTP downloads matching official FileDownloader (proxy tests, gallery files).
module Hath.Download ( fetchFile, receive, via ) where
import qualified Data.ByteString.Char8 as BS
import Data.Default ( def )
import qualified Data.List as List
import Data.String.Interpolate ( i )
import Hath.Protocol ( outgoingHeaders )
import Hath.RPC ( connectMicros, httpManager, worthRetrying )
import Hath.Settings ( ImageProxy(..) )
import Network.Connection ( ProxySettings(SockSettingsSimple) )
import qualified Network.HTTP.Client as HC
import Network.HTTP.Client.Internal ( throwHttp )
import Network.HTTP.Client.TLS ( mkManagerSettings )
import Network.HTTP.Types ( hContentLength, statusCode )
import Relude
import System.IO.Unsafe ( unsafePerformIO )
import UnliftIO ( timeout, tryAny )
via :: Maybe ImageProxy -> HC.Request -> IO ( HC.Manager, HC.Request )
via proxy request = case proxy of
Nothing -> pure ( httpManager, request )
Just (HTTPProxy host port) -> pure ( httpManager, request { HC.proxy = Just (HC.Proxy host port) } )
Just (SOCKSProxy host port) -> (, request) <$> socksManager host port
-- | One manager for the SOCKS proxy last asked for; the settings can name another.
socksManager :: String -> Int -> IO HC.Manager
socksManager host port = readIORef socksManagers >>= \case
Just ( for, manager )
| for == ( host, port ) -> pure manager
_ -> do
let settings
= mkManagerSettings def (Just (SockSettingsSimple host (fromIntegral port)))
manager <- HC.newManager settings
{ HC.managerRawConnection = within5s <$> HC.managerRawConnection settings
, HC.managerTlsConnection = within5s <$> HC.managerTlsConnection settings
}
manager <$ writeIORef socksManagers (Just ( ( host, port ), manager ))
where
within5s connect address host' port'
= timeout connectMicros (connect address host' port') >>= maybe (throwHttp HC.ConnectionTimeout) pure
socksManagers :: IORef (Maybe ( ( String, Int ), HC.Manager ))
socksManagers = unsafePerformIO (newIORef Nothing)
{-# NOINLINE socksManagers #-}
-- | Download matching FileDownloader.java:147-299: up to 3 attempts (5s connect,
-- 10s headers/read), enforcing @max_allowed_filesize@ and skipping retries on 404/410.
fetchFile
:: Int -> Maybe ImageProxy -> HC.Request -> (Int -> ByteString -> IO ()) -> IO (Either Text Int)
fetchFile maxAllowedFileSize proxy request keep = go (3 :: Int)
where
go attemptsLeft = attempt >>= \case
Left ( status, why )
| attemptsLeft > 1, worthRetrying status -> go (attemptsLeft - 1)
| otherwise -> pure (Left why)
Right size -> pure (Right size)
-- the length, or else the status that failed it (none if something else did) and why
attempt = do
( manager, req ) <- via proxy sent
either (\e -> Left ( Nothing, describe e )) id <$> tryAny (HC.withResponse req manager answer)
answer response = case ( statusCode (HC.responseStatus response), announced ) of
( status, _ )
| status >= 400 -> pure $ Left ( Just status, [i|HTTP #{status}|] )
( _, Nothing ) -> pure $ Left ( Nothing, "no Content-Length" )
( _, Just size )
| size > maxAllowedFileSize
-> pure $ Left ( Nothing, [i|#{size} bytes, more than max_allowed_filesize|] )
| otherwise -> receive readMicros size (HC.responseBody response) keep <&> \case
Left why -> Left ( Nothing, why )
Right () -> Right size
where
announced
= readMaybe . BS.unpack =<< List.lookup hContentLength (HC.responseHeaders response)
sent
= request { HC.requestHeaders = outgoingHeaders [ ( "Connection", "Close" ) ]
, HC.responseTimeout = HC.responseTimeoutMicro (connectMicros + readMicros)
}
readMicros = 10 * 1000000
-- | Read exactly @size@ bytes with per-read timeout @readMicros@, passing @(offset, chunk)@ to @keep@.
receive :: Int -> Int -> HC.BodyReader -> (Int -> ByteString -> IO ()) -> IO (Either Text ())
receive readMicros size body keep = either (Left . describe) id <$> tryAny (go 0)
where
go received = timeout readMicros (HC.brRead body) >>= \case
Nothing
-> pure $ Left [i|nothing came for #{readMicros `div` 1000000} s after #{received} bytes|]
Just chunk
| BS.null chunk -> pure
$ if received == size
then Right ()
else Left [i|it ended after #{received} of #{size} bytes|]
-- the caller's buffer may hold no more; a chunked body can bring more than announced
| BS.length chunk > size - received -> pure $ Left [i|it sent more than #{size} bytes|]
| otherwise -> keep received chunk >> go (received + BS.length chunk)
describe :: SomeException -> Text
describe e = case fromException e of
Just (HC.HttpExceptionRequest _ content) -> show content
_ -> show e