unkai-0.1.0.1: src/Unkai/Internal/Body.hs
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Unkai.Internal.Body
-- Copyright : (c) 2015-2022 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Nadeem Bitar <nadeem@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
module Unkai.Internal.Body
( getMIMEType,
sourceBody,
)
where
import Control.Monad.IO.Class (MonadIO (..))
import Data.Maybe (fromMaybe)
import Data.Text qualified as Text
import Network.HTTP.Client qualified as Client
import Network.HTTP.Media (MediaType, parseAccept, (//))
import Network.Mime qualified as MIME
import Unkai.Types (GBody (..))
-- | Attempt to calculate the MIME type based on file extension.
--
-- Defaults to @application/octet-stream@ if no file extension is recognised.
getMIMEType :: FilePath -> MediaType
getMIMEType =
fromMaybe ("application" // "octet-stream")
. parseAccept
. MIME.defaultMimeLookup
. Text.takeWhileEnd (/= '/')
. Text.pack
-- | Construct a 'GBody' from a 'FilePath'.
--
-- This uses 'getMIMEType' to calculate the MIME type from the file extension,
-- you can use 'bodyContentType' to set a MIME type explicitly.
-- Keep the file size fixed between creating the body and sending it.
sourceBody :: (MonadIO m) => FilePath -> m GBody
sourceBody f = GBody (getMIMEType f) <$> liftIO (Client.streamFile f)