URI.hs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. module Data.SMTP.Types.URI where
  2. import qualified Network.URI as N
  3. import Data.SMTP.Account
  4. import Data.List
  5. import Text.StringConvert
  6. newtype Path = Path [String] deriving (Eq, Ord, Read, Show)
  7. data Revision = NoRevision | Revision String deriving (Eq, Ord, Read, Show)
  8. data Parameter = Parameter String String deriving (Eq, Ord, Read, Show)
  9. data URI = URI {account :: Account, path :: Path, revision :: Revision, parameters :: [Parameter]}
  10. deriving (Eq, Ord)
  11. {- |
  12. Returns the entire path of the URI.
  13. -}
  14. fullPath :: URI -> String
  15. fullPath URI{path=Path p} = intercalate "/" $ map uriEncode p
  16. {- |
  17. Returns the entire path of the URI, except for the leading slash (/).
  18. -}
  19. relativePath :: URI -> String
  20. relativePath URI{path=Path p} = intercalate "/" . map uriEncode $ drop 1 p
  21. fullURI :: URI -> String
  22. fullURI u@(URI{account=a, revision=r, parameters=pp}) =
  23. concat $ ["FCMTP://", s . fullAccount $ a, fullPath u] ++ (
  24. case r of
  25. NoRevision -> []
  26. Revision r' -> [":", r']
  27. ) ++ (
  28. if null pp
  29. then []
  30. else ["?", intercalate "&" $ map formatParameter pp]
  31. )
  32. where
  33. formatParameter (Parameter nm vl) = concat [uriEncode nm, "=", uriEncode vl]
  34. uriEncode :: String -> String
  35. uriEncode = N.escapeURIString N.isUnescapedInURIComponent
  36. instance Show URI where
  37. show = fullURI
  38. getParameter :: String -> URI -> Maybe String
  39. getParameter p u = case map (\(Parameter _ vl) -> vl) .
  40. filter (\(Parameter nm _) -> nm == p) $
  41. parameters u of
  42. [] -> Nothing
  43. (v:_) -> Just v