--------------------------------------------------------------------
-- |
-- Module    : Codec.MIME.Utils
-- Copyright : (c) 2006-2009, Galois, Inc. 
-- License   : BSD3
--
-- Maintainer: Sigbjorn Finne <sigbjorn.finne@gmail.com>
-- Stability : provisional
-- Portability: portable
--
-- Extracting content from MIME values and types.
-- 
--------------------------------------------------------------------
module Codec.MIME.Utils
  ( findMultipartNamed -- :: String -> MIMEValue -> Maybe MIMEValue
  )  where

import Codec.MIME.Type
import Data.List ( find )
import Control.Monad ( msum )
import Data.Text(Text)

-- | Given a parameter name, locate it within a MIME value,
-- returning the corresponding (sub) MIME value.
findMultipartNamed :: Text -> MIMEValue -> Maybe MIMEValue
findMultipartNamed :: Text -> MIMEValue -> Maybe MIMEValue
findMultipartNamed nm :: Text
nm mv :: MIMEValue
mv =
 case MIMEValue -> MIMEContent
mime_val_content MIMEValue
mv of
   Multi ms :: [MIMEValue]
ms  -> [Maybe MIMEValue] -> Maybe MIMEValue
forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, MonadPlus m) =>
t (m a) -> m a
msum ((MIMEValue -> Maybe MIMEValue) -> [MIMEValue] -> [Maybe MIMEValue]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> MIMEValue -> Maybe MIMEValue
findMultipartNamed Text
nm) [MIMEValue]
ms)
   Single {} -> do Disposition
cd <- MIMEValue -> Maybe Disposition
mime_val_disp MIMEValue
mv
                   DispParam
_ <- (DispParam -> Bool) -> [DispParam] -> Maybe DispParam
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Text -> DispParam -> Bool
withDispName Text
nm) (Disposition -> [DispParam]
dispParams Disposition
cd)
                   MIMEValue -> Maybe MIMEValue
forall (m :: * -> *) a. Monad m => a -> m a
return MIMEValue
mv
 where withDispName :: Text -> DispParam -> Bool
withDispName a :: Text
a (Name b :: Text
b) = Text
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
b
       withDispName _ _ = Bool
False