{-# LANGUAGE OverloadedStrings #-}
module Network.Google.Internal.Body where
import Control.Monad.IO.Class (MonadIO (..))
import Data.Conduit.Binary (sourceFile)
import Data.Maybe (fromMaybe)
import qualified Data.Text as Text
import Network.Google.Types (Body (..))
import Network.HTTP.Conduit (requestBodySource)
import Network.HTTP.Media (MediaType, parseAccept, (//))
import qualified Network.Mime as MIME
import System.IO
getFileSize :: MonadIO m => FilePath -> m Integer
getFileSize f = liftIO (withBinaryFile f ReadMode hFileSize)
getMIMEType :: FilePath -> MediaType
getMIMEType =
fromMaybe ("application" // "octet-stream")
. parseAccept
. MIME.defaultMimeLookup
. Text.takeWhileEnd (/= '/')
. Text.pack
sourceBody :: MonadIO m => FilePath -> m Body
sourceBody f = do
n <- getFileSize f
pure $ Body
(getMIMEType f)
(requestBodySource (fromIntegral n) (sourceFile f))