git.iko.soy/typeable/mandrill
on master help sign in
25 files changed+1732−109
since splitsnapshots
unifiedsplit
.gitignore+6−1 .hub+1−1 .travis.yml+51 README.md+134−3 default.nix+24 examples/Send.hs+13 mandrill-nightly.yml+10 mandrill.cabal+61−10 src/Network/API/Mandrill.hs+164 src/Network/API/Mandrill/HTTP.hs+26−12 src/Network/API/Mandrill/Inbound.hs+78 src/Network/API/Mandrill/Messages.hs+33−7 src/Network/API/Mandrill/Messages/Types.hs+57 src/Network/API/Mandrill/Senders.hs+45 src/Network/API/Mandrill/Settings.hs+26−6 src/Network/API/Mandrill/Trans.hs+29 src/Network/API/Mandrill/Types.hs+286−65 src/Network/API/Mandrill/Users.hs+26−4 src/Network/API/Mandrill/Users/Types.hs+122 src/Network/API/Mandrill/Webhooks.hs+70 stack.yaml+5 test/Main.hs+50 test/Online.hs+70 test/RawData.hs+257 test/Tests.hs+88
.gitignore+6−1
@@ -1 +1,6 @@
1−dist
1+dist
2+.cabal-sandbox
3+cabal.sandbox.config
4+shell.nix
5+.stack-work
6+tags
.hub+1−1
@@ -1 +1 @@
1−mandrill
1+mandrill-7.10.1
.travis.ymlnew file+51
@@ -0,0 +1,51 @@
1+# See https://github.com/hvr/multi-ghc-travis
2+# The following enables several GHC versions to be tested; often it's enough to test only against the last release in a major GHC version. Feel free to omit lines listings versions you don't need/want testing for.
3+
4+notifications:
5+ email: false
6+
7+env:
8+ - GHCVER=7.6.3 CABALVER=1.16
9+ - GHCVER=7.8.2 CABALVER=1.18
10+ - GHCVER=7.8.3 CABALVER=1.18
11+ - GHCVER=7.10.2 CABALVER=1.22
12+ - GHCVER=8.0.1 CABALVER=1.22
13+ - GHCVER=head CABALVER=1.22
14+
15+matrix:
16+ allow_failures:
17+ - env: GHCVER=8.0.1 CABALVER=1.22
18+ - env: GHCVER=head CABALVER=1.22
19+
20+before_install:
21+ - travis_retry sudo add-apt-repository -y ppa:hvr/ghc
22+ - travis_retry sudo apt-get update
23+ - travis_retry sudo apt-get install cabal-install-$CABALVER ghc-$GHCVER
24+ - export PATH=/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:$PATH
25+ - cabal --version
26+
27+install:
28+ - cabal update
29+ - cabal install --only-dependencies --enable-tests
30+
31+script:
32+ - cabal configure --enable-tests -v2 --enable-library-coverage
33+ - cabal build
34+ - cabal test --show-details=always
35+ - cabal check
36+ - cabal sdist
37+
38+# The following scriptlet checks that the resulting source distribution can be built & installed
39+ - export SRC_TGZ=$(cabal-$CABALVER info . | awk '{print $2 ".tar.gz";exit}') ;
40+ cd dist/;
41+ if [ -f "$SRC_TGZ" ]; then
42+ cabal install "$SRC_TGZ";
43+ else
44+ echo "expected '$SRC_TGZ' not found";
45+ exit 1;
46+ fi
47+
48+after_script:
49+ - cabal install hpc-coveralls
50+ - export PATH=/opt/ghc/$GHCVER/bin:$HOME/.cabal/bin:$PATH
51+ - hpc-coveralls --coverage-mode=StrictlyFullLines mandrill-tests
README.md+134−3
@@ -1,11 +1,142 @@
1+[![Build Status](https://travis-ci.org/adinapoli/mandrill.svg?branch=master)](https://travis-ci.org/adinapoli/mandrill)
2+[![Coverage Status](https://img.shields.io/coveralls/adinapoli/mandrill.svg)](https://coveralls.io/r/adinapoli/mandrill)
13
24# Haskell Client for the Mandrill JSON API
35
4−This module implement a low-level, 1:1 API to the [Mandrill](http://mandrillapp.com)
5−transactional email service.
6+This module implement a low-level, 1:1 mapping API to
7+the [Mandrill](http://mandrillapp.com) transactional email service.
8+
9+# Changelog
10+
11+## Version 0.5.3.5
12+
13+* Replaced dependency on lens with microlens (Courtesy of @tom-bop)
14+
15+## Version 0.5.3.3
16+
17+* Relaxed upper bound on Aeson (see: fpco/stackage/issues/3337)
18+
19+## Version 0.5.3.2
20+
21+* Relaxed upper bound on Aeson (see: fpco/stackage/issues/2449)
22+
23+## Version 0.5.3.1
24+
25+* Relaxed upper bound on Aeson (see: fpco/stackage/issues/2177 )
26+
27+## Version 0.5.3.0
28+
29+* Added support for webhooks (thanks to @mwotton).
30+
31+## Version 0.5.2.3
32+
33+* Added support for aeson-1.0.0.0 by relaxing its upper bound.
34+
35+## Version 0.5.2.2
36+
37+* Added support for QuickCheck-2.9 by relaxing its upper bound.
38+
39+## Version 0.5.2.1
40+
41+* Added `Functor`, `Foldable` and `Traversable` instances to `MandrillResponse` (Courtesy of @dredozubov)
42+
43+## Version 0.5.2.0
44+
45+* Added inbound calls (Courtesy of @mwotton)
46+
47+## Version 0.5.1.0
48+
49+* Relaxed the constraint on `aeson` to allow `0.11.0.0`.
50+
51+## Version 0.5.0.0
52+
53+* Changed the `MandrillHeaders` type synonym from `Value` to `Object`.
54+
55+* Changed the `mmsg_metadata` and `mmdt_values` fields from `MandrillVars` to `Object`.
56+
57+* Changed the `mmsg_global_merge_vars` and `mmvr_vars` fields from `[MandrillVars]` to `[MergeVar]`
58+
59+* Added the `MergeVar` data type:
60+
61+```haskell
62+data MergeVar = MergeVar {
63+ _mv_name :: !Text
64+ , _mv_content :: Value
65+ }
66+```
67+
68+* Removed the `MandrillVars` type synonym.
69+
70+## Version 0.4.0.0
71+
72+* Modified the `Base64ByteString` type to accept another constructor. This
73+ allows the user to pass already-encoded Base64 strings which might be coming
74+ upstream.
75+
76+# Example
77+
78+This package was built with pragmatism and reuse in mind. This means
79+this API comes in two flavours: an IO-based and an handy monad transformer
80+which can be plugged in your stack of choice.
81+Example:
82+
83+``` haskell
84+{-# LANGUAGE OverloadedStrings #-}
85+import Text.Email.Validate
86+import Network.API.Mandrill
87+
88+main :: IO ()
89+main = do
90+ case validate "foo@example.com" of
91+ Left err -> print $ "Invalid email!" ++ show err
92+ Right addr -> runMandrill "MYTOKENHERE" $ do
93+ let msg = "<p>My Html</p>"
94+ res <- sendEmail (newTextMessage addr [addr] "Hello" msg)
95+ case res of
96+ MandrillSuccess k -> liftIO (print k)
97+ MandrillFailure f -> liftIO (print f)
98+```
699
7100# Supported API versions
8101
9102* 1.0 (partially)
103+ - [Users call](https://mandrillapp.com/api/docs/users.JSON.html) - 100%
104+ + info.json
105+ + ~~ping.json~~ (as **doesn't return valid json!**)
106+ + ping2.json
107+ + senders.json
108+
10109 - [Messages call](https://mandrillapp.com/api/docs/messages.JSON.html)
11− + send
110+ + send.json
111+
112+ - [Senders call](https://mandrillapp.com/api/docs/senders.JSON.html)
113+ + verify-domain.json
114+
115+ - [Inbound call](https://mandrillapp.com/api/docs/inbound.JSON.html)
116+ + add-route.json
117+ + add-domain.json
118+
119+# Testing online API
120+
121+To test the online API, first build the package with tests enabled:
122+
123+```
124+cabal install --enable-tests
125+```
126+
127+Then export an environment variable with your Mandrill **Test** token:
128+
129+```
130+export MANDRILL_API_KEY="YOURKEYGOESHERE"
131+```
132+
133+And finally execute the testsuite:
134+
135+```
136+cabal test
137+```
138+
139+# Contributions
140+This library scratches my own itches, but please fork away!
141+Pull requests are encouraged to implement the part of the API
142+you need.
default.nixnew file+24
@@ -0,0 +1,24 @@
1+# This file was auto-generated by cabal2nix. Please do NOT edit manually!
2+
3+{ cabal, aeson, base64Bytestring, blazeHtml, emailValidate, lens
4+, mtl, QuickCheck, rawStringsQq, tasty, tastyHunit, tastyQuickcheck
5+, text, time, wreq
6+}:
7+
8+cabal.mkDerivation (self: {
9+ pname = "mandrill";
10+ version = "0.1.0.3";
11+ src = ./.;
12+ buildDepends = [
13+ aeson base64Bytestring blazeHtml emailValidate lens mtl QuickCheck
14+ text time wreq
15+ ];
16+ testDepends = [
17+ aeson QuickCheck rawStringsQq tasty tastyHunit tastyQuickcheck text
18+ ];
19+ meta = {
20+ description = "Library for interfacing with the Mandrill JSON API";
21+ license = self.stdenv.lib.licenses.mit;
22+ platforms = self.ghc.meta.platforms;
23+ };
24+})
examples/Send.hsnew file+13
@@ -0,0 +1,13 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+import Text.Email.Validate
3+import Network.API.Mandrill
4+
5+main :: IO ()
6+main = case validate "foo@example.com" of
7+ Left err -> print $ "Invalid email!" ++ show err
8+ Right addr -> runMandrill "SUPER-SECRET-TOKEN" $ do
9+ let msg = "<p>My Html</p>"
10+ res <- sendEmail (newTextMessage addr [addr] "Hello" msg)
11+ case res of
12+ MandrillSuccess k -> liftIO (print k)
13+ MandrillFailure f -> liftIO (print f)
mandrill-nightly.ymlnew file+10
@@ -0,0 +1,10 @@
1+flags:
2+ semigroups:
3+ bytestring-builder: false
4+packages:
5+- '.'
6+extra-deps:
7+ - aeson-1.3.0.0
8+ - text-1.2.3.0
9+ - semigroups-0.18.2
10+resolver: lts-9.1
mandrill.cabal+61−10
@@ -1,33 +1,84 @@
11name: mandrill
2−version: 0.1.0.0
2+version: 0.5.3.5
33synopsis: Library for interfacing with the Mandrill JSON API
4+description: Pure Haskell client for the Mandrill JSON API
45license: MIT
56license-file: LICENSE
67author: Alfredo Di Napoli
78maintainer: alfredo.dinapoli@gmail.com
89category: Network
910build-type: Simple
11+tested-with: GHC == 7.4, GHC == 7.6, GHC == 7.8, GHC == 7.10.2
1012cabal-version: >=1.10
1113
14+source-repository head
15+ type: git
16+ location: https://github.com/adinapoli/mandrill
17+
1218library
1319 exposed-modules:
20+ Network.API.Mandrill
1421 Network.API.Mandrill.Settings
22+ Network.API.Mandrill.Types
23+ Network.API.Mandrill.Trans
1524 Network.API.Mandrill.Users
25+ Network.API.Mandrill.Users.Types
1626 Network.API.Mandrill.Messages
17− Network.API.Mandrill.Types
18− Network.API.Mandrill.HTTP
27+ Network.API.Mandrill.Messages.Types
28+ Network.API.Mandrill.Inbound
29+ Network.API.Mandrill.Webhooks
30+ Network.API.Mandrill.Senders
1931 other-modules:
2032 Network.API.Mandrill.Utils
21− -- other-extensions:
33+ Network.API.Mandrill.HTTP
34+ -- other-extensions:
2235 build-depends:
23− base >=4.7 && < 5
24− , text >= 1.0.0.0 && < 1.2
25− , wreq >= 0.1.0.1
26− , aeson >= 0.7.0.3 && < 0.8
27− , lens >= 4.1 && < 4.6
36+ base >=4.6 && < 5
37+ , containers >= 0.5.0.0
38+ , bytestring >= 0.9.0
39+ , base64-bytestring >= 1.0.0.1
40+ , text >= 1.0.0.0 && < 1.3
41+ , http-types >= 0.8.0
42+ , http-client >= 0.3.0
43+ , http-client-tls >= 0.2.0.0
44+ , aeson >= 0.7.0.3 && < 1.5.0.0
45+ , microlens-th >= 0.4.0.0
2846 , blaze-html >= 0.5.0.0
47+ , QuickCheck >= 2.6 && < 3.0
48+ , mtl < 3.0
2949 , time
50+ , email-validate >= 1.0.0
51+ , old-locale
52+ , unordered-containers
3053 hs-source-dirs:
3154 src
3255 default-language:
33− Haskell2010
56+ Haskell2010
57+
58+ ghc-options:
59+ -funbox-strict-fields
60+
61+test-suite mandrill-tests
62+ type:
63+ exitcode-stdio-1.0
64+ main-is:
65+ Main.hs
66+ other-modules:
67+ Tests
68+ RawData
69+ Online
70+ hs-source-dirs:
71+ test
72+ default-language:
73+ Haskell2010
74+ build-depends:
75+ mandrill -any
76+ , base
77+ , aeson
78+ , bytestring
79+ , QuickCheck
80+ , tasty >= 0.9.0.1
81+ , tasty-quickcheck
82+ , tasty-hunit
83+ , raw-strings-qq < 1.2
84+ , text
src/Network/API/Mandrill.hsnew file+164
@@ -0,0 +1,164 @@
1+{-| This package is an attempt to expose the Mandrill JSON API in pure Haskell.
2+ To do that, the library API comes in two flavours:
3+
4+ * An IO-based, low-level 1:1 mapping of the JSON API,
5+ as described on <https://mandrillapp.com/api/docs/ the website>.
6+ * A handy monad transformer which can be plugged in your stack of choice.
7+-}
8+
9+module Network.API.Mandrill (
10+ module M
11+ , sendEmail
12+ , sendTextEmail
13+ , emptyMessage
14+ , newTextMessage
15+ , newHtmlMessage
16+ , newTemplateMessage
17+ , liftIO
18+
19+ -- * Appendix: Example Usage
20+ -- $exampleusage
21+ ) where
22+
23+import Control.Monad.Reader
24+import qualified Data.Aeson as JSON
25+import qualified Data.HashMap.Strict as H
26+import Data.Monoid
27+import qualified Data.Text as T
28+import Data.Time
29+import Network.API.Mandrill.Messages as M
30+import Network.API.Mandrill.Messages.Types as M
31+import Network.API.Mandrill.Trans as M
32+import Network.API.Mandrill.Types as M
33+import Text.Blaze.Html
34+import Text.Email.Validate
35+
36+{- $exampleusage
37+
38+The API was designed to allow to get you started as quickly as possible:
39+
40+> {-# LANGUAGE OverloadedStrings #-}
41+> import Text.Email.Validate
42+> import Network.API.Mandrill
43+>
44+> main :: IO ()
45+> main = do
46+> case validate "foo@example.com" of
47+> Left err -> print $ "Invalid email!" ++ show err
48+> Right addr -> runMandrill "MYTOKENHERE" $ do
49+> let msg = "<p>My Html</p>"
50+> res <- sendEmail (newTextMessage addr [addr] "Hello" msg)
51+> case res of
52+> MandrillSuccess k -> liftIO (print k)
53+> MandrillFailure f -> liftIO (print f)
54+
55+-}
56+
57+--------------------------------------------------------------------------------
58+-- | Builds an empty message, given only the email of the sender and
59+-- the emails of the receiver. Please note that the "Subject" will be empty,
60+-- so you need to use either @newTextMessage@ or @newHtmlMessage@ to populate it.
61+emptyMessage :: EmailAddress -> [EmailAddress] -> MandrillMessage
62+emptyMessage f t = MandrillMessage {
63+ _mmsg_html = mempty
64+ , _mmsg_text = Nothing
65+ , _mmsg_subject = T.empty
66+ , _mmsg_from_email = (MandrillEmail f)
67+ , _mmsg_from_name = Nothing
68+ , _mmsg_to = map newRecipient t
69+ , _mmsg_headers = H.empty
70+ , _mmsg_important = Nothing
71+ , _mmsg_track_opens = Nothing
72+ , _mmsg_track_clicks = Nothing
73+ , _mmsg_auto_text = Nothing
74+ , _mmsg_auto_html = Nothing
75+ , _mmsg_inline_css = Nothing
76+ , _mmsg_url_strip_qs = Nothing
77+ , _mmsg_preserve_recipients = Nothing
78+ , _mmsg_view_content_link = Nothing
79+ , _mmsg_bcc_address = Nothing
80+ , _mmsg_tracking_domain = Nothing
81+ , _mmsg_signing_domain = Nothing
82+ , _mmsg_return_path_domain = Nothing
83+ , _mmsg_merge = Nothing
84+ , _mmsg_global_merge_vars = []
85+ , _mmsg_merge_vars = []
86+ , _mmsg_tags = []
87+ , _mmsg_subaccount = Nothing
88+ , _mmsg_google_analytics_domains = []
89+ , _mmsg_google_analytics_campaign = Nothing
90+ , _mmsg_metadata = H.empty
91+ , _mmsg_recipient_metadata = []
92+ , _mmsg_attachments = []
93+ , _mmsg_images = []
94+ }
95+
96+
97+--------------------------------------------------------------------------------
98+-- | Create a new HTML message.
99+newHtmlMessage :: EmailAddress
100+ -- ^ Sender email
101+ -> [EmailAddress]
102+ -- ^ Receivers email
103+ -> T.Text
104+ -- ^ Subject
105+ -> Html
106+ -- ^ The HTML body
107+ -> MandrillMessage
108+newHtmlMessage f t subj html = let body = mkMandrillHtml html in
109+ (emptyMessage f t) { _mmsg_html = body, _mmsg_subject = subj }
110+
111+--------------------------------------------------------------------------------
112+-- | Create a new template message (no HTML).
113+newTemplateMessage :: EmailAddress
114+ -- ^ Sender email
115+ -> [EmailAddress]
116+ -- ^ Receivers email
117+ -> T.Text
118+ -- ^ Subject
119+ -> MandrillMessage
120+newTemplateMessage f t subj = (emptyMessage f t) { _mmsg_subject = subj }
121+
122+--------------------------------------------------------------------------------
123+-- | Create a new textual message. By default Mandrill doesn't require you
124+-- to specify the @mmsg_text@ when sending out the JSON Payload, and this
125+-- function ensure it will be present.
126+newTextMessage :: EmailAddress
127+ -- ^ Sender email
128+ -> [EmailAddress]
129+ -- ^ Receivers email
130+ -> T.Text
131+ -- ^ Subject
132+ -> T.Text
133+ -- ^ The body, as normal text.
134+ -> MandrillMessage
135+newTextMessage f t subj txt = let body = unsafeMkMandrillHtml txt in
136+ (emptyMessage f t) {
137+ _mmsg_html = body
138+ , _mmsg_text = Just txt
139+ , _mmsg_subject = subj
140+ }
141+
142+
143+--------------------------------------------------------------------------------
144+-- | The simplest way to use the API. All you need to provide is a valid
145+-- 'MandrillMessage' and this function will send an email inside a
146+-- 'MandrillT' transformer. You are not forced to use the 'MandrillT' context
147+-- though. Have a look at "Network.API.Mandrill.Messages" for an IO-based,
148+-- low level function for sending email.
149+sendEmail :: MonadIO m
150+ => MandrillMessage
151+ -> MandrillT m (MandrillResponse [MessagesResponse])
152+sendEmail msg = do
153+ (key, mgr) <- ask
154+ liftIO $ send key msg (Just True) Nothing Nothing (Just mgr)
155+
156+
157+--------------------------------------------------------------------------------
158+sendTextEmail :: MonadIO m
159+ => MandrillMessage
160+ -> MandrillT m (MandrillResponse [MessagesResponse])
161+sendTextEmail msg = do
162+ (key, mgr) <- ask
163+ now <- liftIO getCurrentTime
164+ liftIO $ send key msg (Just True) Nothing (Just now) (Just mgr)
src/Network/API/Mandrill/HTTP.hs+26−12
@@ -1,19 +1,33 @@
11{-# LANGUAGE OverloadedStrings #-}
22module Network.API.Mandrill.HTTP where
33
4−import Network.API.Mandrill.Settings
5−import Network.API.Mandrill.Types
6−import qualified Data.Text as T
7−import Data.Monoid
8−import Data.Aeson
9−import Network.Wreq
10−import Control.Lens
4+import Control.Applicative
5+import Data.Aeson
6+import Data.Monoid
7+import qualified Data.Text as T
8+import Network.API.Mandrill.Settings
9+import Network.API.Mandrill.Types
10+import Network.HTTP.Client
11+import Network.HTTP.Client.TLS
12+import Network.HTTP.Types
1113
12−toMandrillResponse :: (MandrillEndpoint ep, ToJSON rq)
14+toMandrillResponse :: (MandrillEndpoint ep, FromJSON a, ToJSON rq)
1315 => ep
1416 -> rq
15− -> IO MandrillResponse
16−toMandrillResponse ep rq = do
17+ -> Maybe Manager
18+ -> IO (MandrillResponse a)
19+toMandrillResponse ep rq mbMgr = do
1720 let fullUrl = mandrillUrl <> toUrl ep
18− res <- asJSON =<< post (T.unpack fullUrl) (toJSON rq)
19− return $ res ^. responseBody
21+ rq' <- parseUrl (T.unpack fullUrl)
22+ let headers = [(hContentType, "application/json")]
23+ let jsonBody = encode rq
24+ let req = rq' {
25+ method = "POST"
26+ , requestHeaders = headers
27+ , requestBody = RequestBodyLBS jsonBody
28+ }
29+ mgr <- maybe (newManager tlsManagerSettings) return mbMgr
30+ res <- responseBody <$> httpLbs req mgr
31+ case eitherDecode res of
32+ Left e -> fail e
33+ Right v -> return v
src/Network/API/Mandrill/Inbound.hsnew file+78
@@ -0,0 +1,78 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+module Network.API.Mandrill.Inbound where
3+import Data.Aeson (FromJSON, ToJSON, parseJSON,
4+ toJSON)
5+import Data.Aeson.TH (defaultOptions, deriveJSON)
6+import Data.Aeson.Types (fieldLabelModifier)
7+import Data.Text (Text)
8+import Lens.Micro.TH (makeLenses)
9+import Network.API.Mandrill.HTTP (toMandrillResponse)
10+import Network.API.Mandrill.Settings
11+import Network.API.Mandrill.Types
12+import Network.HTTP.Client (Manager)
13+
14+data DomainAddRq =
15+ DomainAddRq
16+ { _darq_key :: MandrillKey
17+ , _darq_domain :: Text
18+ } deriving Show
19+
20+makeLenses ''DomainAddRq
21+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''DomainAddRq
22+
23+data DomainAddResponse =
24+ DomainAddResponse
25+ { _dares_domain :: Text
26+ , _dares_created_at :: MandrillDate
27+ , _dares_valid_mx :: Bool
28+ } deriving Show
29+
30+
31+
32+makeLenses ''DomainAddResponse
33+deriveJSON defaultOptions { fieldLabelModifier = drop 7 } ''DomainAddResponse
34+
35+data RouteAddResponse =
36+ RouteAddResponse
37+ { _rares_id :: Text
38+ , _rares_pattern :: Text
39+ , _rares_url :: Text
40+ } deriving Show
41+
42+
43+
44+makeLenses ''RouteAddResponse
45+deriveJSON defaultOptions { fieldLabelModifier = drop 7 } ''RouteAddResponse
46+
47+data RouteAddRq =
48+ RouteAddRq
49+ { _rarq_key :: Text
50+ , _rarq_domain :: Text
51+ , _rarq_pattern :: Text
52+ , _rarq_url :: Text
53+ } deriving Show
54+
55+makeLenses ''RouteAddRq
56+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''RouteAddRq
57+
58+addDomain :: MandrillKey
59+ -- ^ The API key
60+ -> Text
61+ -- ^ The domain to add
62+ -> Maybe Manager
63+ -> IO (MandrillResponse DomainAddResponse)
64+addDomain k dom = toMandrillResponse DomainsAdd (DomainAddRq k dom)
65+
66+
67+
68+addRoute :: MandrillKey
69+ -- ^ The API key
70+ -> Text
71+ -- ^ The domain to add
72+ -> Text
73+ -- ^ the pattern including wildcards
74+ -> Text
75+ -- ^ URL to forward to
76+ -> Maybe Manager
77+ -> IO (MandrillResponse RouteAddResponse)
78+addRoute k dom pattern forward = toMandrillResponse RoutesAdd (RouteAddRq k dom pattern forward)
src/Network/API/Mandrill/Messages.hs+33−7
@@ -1,19 +1,45 @@
11
22module Network.API.Mandrill.Messages where
33
4−import Network.API.Mandrill.Types
5−import Network.API.Mandrill.Settings
6−import Network.API.Mandrill.HTTP
4+import qualified Data.Text as T
75import Data.Time
8−import qualified Data.Text as T
6+import Network.API.Mandrill.HTTP
7+import Network.API.Mandrill.Messages.Types
8+import Network.API.Mandrill.Settings
9+import Network.API.Mandrill.Types
10+import Network.HTTP.Client
911
1012--------------------------------------------------------------------------------
1113-- | Send a new transactional message through Mandrill
1214send :: MandrillKey
15+ -- ^ The API key
1316 -> MandrillMessage
17+ -- ^ The email message
1418 -> Maybe Bool
19+ -- ^ Enable a background sending mode that is optimized for bulk sending
1520 -> Maybe T.Text
21+ -- ^ ip_pool
1622 -> Maybe UTCTime
17− -> IO MandrillResponse
18−send k msg async ip_pool send_at =
19− toMandrillResponse Send (MandrillSendRq k msg async ip_pool send_at)
23+ -- ^ send_at
24+ -> Maybe Manager
25+ -> IO (MandrillResponse [MessagesResponse])
26+send k msg async ip_pool send_at = toMandrillResponse MessagesSend (MessagesSendRq k msg async ip_pool send_at)
27+
28+-- | Send a new transactional message through Mandrill using a template
29+sendTemplate :: MandrillKey
30+ -- ^ The API key
31+ -> MandrillTemplate
32+ -- ^ The template name
33+ -> [MandrillTemplateContent]
34+ -- ^ Template content for 'editable regions'
35+ -> MandrillMessage
36+ -- ^ The email message
37+ -> Maybe Bool
38+ -- ^ Enable a background sending mode that is optimized for bulk sending
39+ -> Maybe T.Text
40+ -- ^ ip_pool
41+ -> Maybe UTCTime
42+ -- ^ send_at
43+ -> Maybe Manager
44+ -> IO (MandrillResponse [MessagesResponse])
45+sendTemplate k template content msg async ip_pool send_at = toMandrillResponse MessagesSendTemplate (MessagesSendTemplateRq k template content msg async ip_pool send_at)
src/Network/API/Mandrill/Messages/Types.hsnew file+57
@@ -0,0 +1,57 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Network.API.Mandrill.Messages.Types where
4+
5+import Data.Char
6+import Data.Time
7+import qualified Data.Text as T
8+import Control.Monad
9+import Data.Monoid
10+import Data.Aeson
11+import Data.Aeson.Types
12+import Data.Aeson.TH
13+import Lens.Micro.TH (makeLenses)
14+
15+import Network.API.Mandrill.Types
16+
17+
18+--------------------------------------------------------------------------------
19+data MessagesSendRq = MessagesSendRq {
20+ _msrq_key :: MandrillKey
21+ , _msrq_message :: MandrillMessage
22+ , _msrq_async :: Maybe Bool
23+ , _msrq_ip_pool :: Maybe T.Text
24+ , _msrq_send_at :: Maybe UTCTime
25+ } deriving Show
26+
27+makeLenses ''MessagesSendRq
28+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MessagesSendRq
29+
30+--------------------------------------------------------------------------------
31+data MessagesSendTemplateRq = MessagesSendTemplateRq {
32+ _mstrq_key :: MandrillKey
33+ , _mstrq_template_name :: T.Text
34+ , _mstrq_template_content :: [MandrillTemplateContent]
35+ , _mstrq_message :: MandrillMessage
36+ , _mstrq_async :: Maybe Bool
37+ , _mstrq_ip_pool :: Maybe T.Text
38+ , _mstrq_send_at :: Maybe UTCTime
39+ } deriving Show
40+
41+makeLenses ''MessagesSendTemplateRq
42+deriveJSON defaultOptions { fieldLabelModifier = drop 7 } ''MessagesSendTemplateRq
43+
44+--------------------------------------------------------------------------------
45+data MessagesResponse = MessagesResponse {
46+ _mres_email :: !T.Text
47+ -- ^ The email address of the recipient
48+ , _mres_status :: MandrillEmailStatus
49+ -- ^ The sending status of the recipient
50+ , _mres_reject_reason :: Maybe MandrillRejectReason
51+ -- ^ The reason for the rejection if the recipient status is "rejected"
52+ , _mres__id :: !T.Text
53+ -- ^ The message's unique id
54+ } deriving Show
55+
56+makeLenses ''MessagesResponse
57+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MessagesResponse
src/Network/API/Mandrill/Senders.hsnew file+45
@@ -0,0 +1,45 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+module Network.API.Mandrill.Senders where
3+import Data.Aeson (FromJSON, ToJSON, parseJSON,
4+ toJSON)
5+import Data.Aeson.TH (defaultOptions, deriveJSON)
6+import Data.Aeson.Types (Value (..), fieldLabelModifier)
7+import Data.Text (Text)
8+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
9+import Lens.Micro.TH (makeLenses)
10+import Network.API.Mandrill.HTTP (toMandrillResponse)
11+import Network.API.Mandrill.Settings
12+import Network.API.Mandrill.Types
13+import Network.HTTP.Client (Manager)
14+import qualified Text.Email.Validate as TEV
15+
16+data VerifyDomainRq =
17+ VerifyDomainRq
18+ { _vdrq_key :: MandrillKey
19+ , _vdrq_domain :: Text
20+ , _vdrq_mailbox :: Text
21+ } deriving Show
22+
23+makeLenses ''VerifyDomainRq
24+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''VerifyDomainRq
25+
26+data VerifyDomainResponse =
27+ VerifyDomainResponse
28+ { _vdres_status :: Text
29+ , _vdres_domain :: Text
30+ , _vdres_email :: MandrillEmail
31+ } deriving Show
32+
33+makeLenses ''VerifyDomainResponse
34+deriveJSON defaultOptions { fieldLabelModifier = drop 7 } ''VerifyDomainResponse
35+
36+
37+verifyDomain :: MandrillKey
38+ -- ^ The API key
39+ -> TEV.EmailAddress
40+ -- ^ Email address to use for verification
41+ -> Maybe Manager
42+ -> IO (MandrillResponse VerifyDomainResponse)
43+verifyDomain k email =
44+ toMandrillResponse VerifyDomain
45+ (VerifyDomainRq k (decodeUtf8 $ TEV.domainPart email) (decodeUtf8 $ TEV.localPart email))
src/Network/API/Mandrill/Settings.hs+26−6
@@ -7,14 +7,34 @@ mandrillUrl :: T.Text
77mandrillUrl = "https://mandrillapp.com/api/1.0/"
88
99data MandrillCalls =
10− Send
11− | SendTemplate
12− | Search deriving Show
10+ -- Users API
11+ UsersInfo
12+ | UsersPing
13+ | UsersPing2
14+ | UsersSenders
15+ -- Messages API
16+ | MessagesSend
17+ | MessagesSendTemplate
18+ | MessagesSearch
19+ -- Inbound API
20+ | RoutesAdd
21+ | DomainsAdd
22+ -- Senders API
23+ | VerifyDomain
24+
25+ deriving Show
1326
1427class MandrillEndpoint ep where
1528 toUrl :: ep -> T.Text
1629
1730instance MandrillEndpoint MandrillCalls where
18− toUrl Send = "messages/send.json"
19− toUrl SendTemplate = "messages/send-template.json"
20− toUrl Search = "messages/search.json"
31+ toUrl UsersInfo = "users/info.json"
32+ toUrl UsersPing = "users/ping.json"
33+ toUrl UsersPing2 = "users/ping2.json"
34+ toUrl UsersSenders = "users/senders.json"
35+ toUrl MessagesSend = "messages/send.json"
36+ toUrl MessagesSendTemplate = "messages/send-template.json"
37+ toUrl MessagesSearch = "messages/search.json"
38+ toUrl DomainsAdd = "inbound/add-domain.json"
39+ toUrl RoutesAdd = "inbound/add-route.json"
40+ toUrl VerifyDomain = "senders/verify-domain.json"
src/Network/API/Mandrill/Trans.hsnew file+29
@@ -0,0 +1,29 @@
1+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
2+module Network.API.Mandrill.Trans where
3+
4+import Control.Monad.Reader
5+import Control.Applicative
6+import Network.API.Mandrill.Types
7+import Network.HTTP.Client
8+import Network.HTTP.Client.TLS
9+
10+
11+--------------------------------------------------------------------------------
12+newtype MandrillT m a = MandrillT {
13+ runMandrillT :: ReaderT (MandrillKey, Manager) m a
14+ } deriving (MonadTrans, MonadReader (MandrillKey, Manager),
15+ Functor, Applicative, Monad, MonadIO)
16+
17+
18+--------------------------------------------------------------------------------
19+type Mandrill = MandrillT IO
20+
21+
22+--------------------------------------------------------------------------------
23+runMandrill :: MonadIO m
24+ => MandrillKey
25+ -> MandrillT m a
26+ -> m a
27+runMandrill key action = do
28+ mgr <- liftIO $ newManager tlsManagerSettings
29+ runReaderT (runMandrillT action) (key, mgr)
src/Network/API/Mandrill/Types.hs+286−65
@@ -1,30 +1,59 @@
1−{-# LANGUAGE TemplateHaskell #-}
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveFoldable #-}
3+{-# LANGUAGE DeriveFunctor #-}
4+{-# LANGUAGE DeriveTraversable #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE RankNTypes #-}
27{-# LANGUAGE ScopedTypeVariables #-}
3−{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE TemplateHaskell #-}
49module Network.API.Mandrill.Types where
510
6−import Network.API.Mandrill.Utils
11+import Control.Applicative
12+import Control.Monad (mzero)
713import Data.Char
14+import Data.Maybe
815import Data.Time
9−import qualified Data.Text as T
10−import qualified Data.Text.Lazy as TL
11−import Control.Lens
12−import Control.Monad
13−import Data.Monoid
16+import Lens.Micro.TH (makeLenses)
17+import Network.API.Mandrill.Utils
18+import Test.QuickCheck
19+import Text.Email.Validate
20+#if MIN_VERSION_time(1,5,0)
21+import Data.Time.Format (TimeLocale, defaultTimeLocale)
22+#else
23+import System.Locale (TimeLocale, defaultTimeLocale)
24+#endif
1425import Data.Aeson
15−import Data.Aeson.Types
1626import Data.Aeson.TH
17−import qualified Text.Blaze.Html as Blaze
27+import Data.Aeson.Types
28+import qualified Data.ByteString as B
29+import qualified Data.ByteString.Base64 as Base64
30+#if !MIN_VERSION_base(4,8,0)
31+import Data.Foldable
32+import Data.Traversable
33+#endif
34+import qualified Data.HashMap.Strict as H
35+import Data.Monoid
36+import qualified Data.Text as T
37+import qualified Data.Text.Encoding as TL
38+import qualified Data.Text.Lazy as TL
39+import qualified Text.Blaze.Html as Blaze
1840import qualified Text.Blaze.Html.Renderer.Text as Blaze
41+import qualified Text.Email.Validate as TEV
1942
43+timeParse :: ParseTime t => TimeLocale -> String -> String -> Maybe t
44+#if MIN_VERSION_time(1,5,0)
45+timeParse = parseTimeM True
46+#else
47+timeParse = parseTime
48+#endif
2049
2150--------------------------------------------------------------------------------
2251data MandrillError = MandrillError {
23− _merr_status :: !T.Text
24− , _merr_code :: !Int
25− , _merr_name :: !T.Text
52+ _merr_status :: !T.Text
53+ , _merr_code :: !Int
54+ , _merr_name :: !T.Text
2655 , _merr_message :: !T.Text
27− } deriving Show
56+ } deriving (Show, Eq)
2857
2958makeLenses ''MandrillError
3059deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillError
@@ -49,6 +78,7 @@ data MandrillRejectReason = RR_HardBounce
4978 | RR_InvalidSender
5079 | RR_Invalid
5180 | RR_TestModeLimit
81+ | RR_Unsigned
5282 | RR_Rule deriving Show
5383
5484deriveJSON defaultOptions {
@@ -56,36 +86,21 @@ deriveJSON defaultOptions {
5686 } ''MandrillRejectReason
5787
5888
59−--------------------------------------------------------------------------------
60−data MandrillResult = MandrillResult {
61− _mres_email :: !T.Text
62− -- ^ The email address of the recipient
63− , _mres_status :: MandrillEmailStatus
64− -- ^ The sending status of the recipient
65− , _mres_reject_reason :: Maybe MandrillRejectReason
66− -- ^ The reason for the rejection if the recipient status is "rejected"
67− , _mres__id :: !T.Text
68− -- ^ The message's unique id
69− } deriving Show
70−
71−makeLenses ''MandrillResult
72−deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillResult
73−
7489--------------------------------------------------------------------------------
7590-- | The main datatypes which models the response from the Mandrill API,
7691-- which can be either a success or a failure.
77−data MandrillResponse =
78− MandrillSuccess [MandrillResult]
79− | MandrillFailure MandrillError deriving Show
92+data MandrillResponse k =
93+ MandrillSuccess k
94+ | MandrillFailure MandrillError deriving (Show, Eq, Functor, Foldable, Traversable)
8095
81−instance FromJSON MandrillResponse where
82− parseJSON a@(Array _) = case (parseMaybe parseJSON a) :: Maybe [MandrillResult] of
96+instance FromJSON k => FromJSON (MandrillResponse k) where
97+ parseJSON v = case (parseMaybe parseJSON v) :: Maybe k of
8398 Just r -> return $ MandrillSuccess r
84− Nothing -> fail $ show a <> " is not a valid MandrillResult"
85− parseJSON o@(Object _) = case (parseMaybe parseJSON o) :: Maybe MandrillError of
86− Just e -> return $ MandrillFailure e
87− Nothing -> fail $ show o <> " is not a valid MandrillError"
88− parseJSON v = typeMismatch "Expected an Object or an Array for MandrillResponse" v
99+ Nothing -> do
100+ -- try to parse it as an error
101+ case (parseMaybe parseJSON v) :: Maybe MandrillError of
102+ Just e -> return $ MandrillFailure e
103+ Nothing -> fail $ show v <> " is neither a MandrillSuccess or a MandrillError."
89104
90105
91106--------------------------------------------------------------------------------
@@ -94,14 +109,27 @@ data MandrillRecipientTag = To | Cc | Bcc deriving Show
94109deriveJSON defaultOptions { constructorTagModifier = map toLower } ''MandrillRecipientTag
95110
96111
112+--------------------------------------------------------------------------------
113+newtype MandrillEmail = MandrillEmail EmailAddress deriving Show
114+
115+instance ToJSON MandrillEmail where
116+ toJSON (MandrillEmail e) = String . TL.decodeUtf8 . toByteString $ e
117+
118+instance FromJSON MandrillEmail where
119+ parseJSON (String s) = case validate (TL.encodeUtf8 s) of
120+ Left err -> fail err
121+ Right v -> return . MandrillEmail $ v
122+ parseJSON o = typeMismatch "Expecting a String for MandrillEmail." o
123+
124+
97125--------------------------------------------------------------------------------
98126-- | An array of recipient information.
99127data MandrillRecipient = MandrillRecipient {
100− _mrec_email :: !T.Text
128+ _mrec_email :: MandrillEmail
101129 -- ^ The email address of the recipient
102− , _mrec_name :: Maybe T.Text
130+ , _mrec_name :: Maybe T.Text
103131 -- ^ The optional display name to use for the recipient
104− , _mrec_type :: Maybe MandrillRecipientTag
132+ , _mrec_type :: Maybe MandrillRecipientTag
105133 -- ^ The header type to use for the recipient.
106134 -- defaults to "to" if not provided
107135 } deriving Show
@@ -109,15 +137,35 @@ data MandrillRecipient = MandrillRecipient {
109137makeLenses ''MandrillRecipient
110138deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillRecipient
111139
140+newRecipient :: EmailAddress -> MandrillRecipient
141+newRecipient email = MandrillRecipient (MandrillEmail email) Nothing Nothing
142+
143+instance Arbitrary MandrillRecipient where
144+ arbitrary = pure MandrillRecipient {
145+ _mrec_email = MandrillEmail $ fromJust (emailAddress "test@example.com")
146+ , _mrec_name = Nothing
147+ , _mrec_type = Nothing
148+ }
112149
113150--------------------------------------------------------------------------------
114151newtype MandrillHtml = MandrillHtml Blaze.Html
115152
116−mkMandrillHtml :: T.Text -> MandrillHtml
117−mkMandrillHtml = MandrillHtml . Blaze.toHtml
153+unsafeMkMandrillHtml :: T.Text -> MandrillHtml
154+unsafeMkMandrillHtml = MandrillHtml . Blaze.preEscapedToHtml
155+
156+-- This might be slightly hairy because it violates
157+-- the nice encapsulation that newtypes offer.
158+mkMandrillHtml :: Blaze.Html -> MandrillHtml
159+mkMandrillHtml = MandrillHtml
160+
161+#if MIN_VERSION_base(4,11,0)
162+instance Semigroup MandrillHtml where
163+ MandrillHtml m1 <> MandrillHtml m2 = MandrillHtml (m1 <> m2)
164+#endif
118165
119−mkMandrillHtml' :: Blaze.Html -> MandrillHtml
120−mkMandrillHtml' = MandrillHtml
166+instance Monoid MandrillHtml where
167+ mempty = MandrillHtml mempty
168+ mappend (MandrillHtml m1) (MandrillHtml m2) = MandrillHtml (m1 <> m2)
121169
122170instance Show MandrillHtml where
123171 show (MandrillHtml h) = show $ Blaze.renderHtml h
@@ -126,48 +174,221 @@ instance ToJSON MandrillHtml where
126174 toJSON (MandrillHtml h) = String . TL.toStrict . Blaze.renderHtml $ h
127175
128176instance FromJSON MandrillHtml where
129− parseJSON (String h) = return $ MandrillHtml (Blaze.toHtml h)
177+ parseJSON (String h) = return $ MandrillHtml (Blaze.preEscapedToHtml h)
130178 parseJSON v = typeMismatch "Expecting a String for MandrillHtml" v
131179
180+instance Arbitrary MandrillHtml where
181+ arbitrary = pure $ mkMandrillHtml "<p><b>FooBar</b></p>"
182+
183+--------------------------------------------------------------------------------
184+type MandrillTags = T.Text
185+
186+
187+--------------------------------------------------------------------------------
188+type MandrillHeaders = Object
189+
190+
191+--------------------------------------------------------------------------------
192+
193+data MergeVar = MergeVar {
194+ _mv_name :: !T.Text
195+ , _mv_content :: Value
196+ } deriving Show
197+
198+makeLenses ''MergeVar
199+deriveJSON defaultOptions { fieldLabelModifier = drop 4 } ''MergeVar
200+
201+--------------------------------------------------------------------------------
202+data MandrillMergeVars = MandrillMergeVars {
203+ _mmvr_rcpt :: !T.Text
204+ , _mmvr_vars :: [MergeVar]
205+ } deriving Show
206+
207+makeLenses ''MandrillMergeVars
208+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillMergeVars
209+
210+--------------------------------------------------------------------------------
211+data MandrillMetadata = MandrillMetadata {
212+ _mmdt_rcpt :: !T.Text
213+ , _mmdt_values :: Object
214+ } deriving Show
215+
216+makeLenses ''MandrillMetadata
217+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillMetadata
218+
219+
220+data Base64ByteString =
221+ EncodedB64BS B.ByteString
222+ -- ^ An already-encoded Base64 ByteString.
223+ | PlainBS B.ByteString
224+ -- ^ A plain Base64 ByteString which requires encoding.
225+ deriving Show
226+
227+instance ToJSON Base64ByteString where
228+ toJSON (PlainBS bs) = String . TL.decodeUtf8 . Base64.encode $ bs
229+ toJSON (EncodedB64BS bs) = String . TL.decodeUtf8 $ bs
230+
231+instance FromJSON Base64ByteString where
232+ parseJSON (String v) = pure $ EncodedB64BS (TL.encodeUtf8 v)
233+ parseJSON rest = typeMismatch "Base64ByteString must be a String." rest
234+
235+--------------------------------------------------------------------------------
236+data MandrillWebContent = MandrillWebContent {
237+ _mwct_type :: !T.Text
238+ , _mwct_name :: !T.Text
239+ -- ^ [for images] the Content ID of the image
240+ -- - use <img src="cid:THIS_VALUE"> to reference the image
241+ -- in your HTML content
242+ , _mwct_content :: !Base64ByteString
243+ } deriving Show
244+
245+makeLenses ''MandrillWebContent
246+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillWebContent
132247
133248--------------------------------------------------------------------------------
134249-- | The information on the message to send
135250data MandrillMessage = MandrillMessage {
136− _mmsg_html :: MandrillHtml
251+ _mmsg_html :: MandrillHtml
137252 -- ^ The full HTML content to be sent
138− , _mmsg_text :: Maybe T.Text
253+ , _mmsg_text :: Maybe T.Text
139254 -- ^ Optional full text content to be sent
140− , _mmsg_subject :: !T.Text
255+ , _mmsg_subject :: !T.Text
141256 -- ^ The message subject
142− , _mmsg_from_email :: !T.Text
257+ , _mmsg_from_email :: MandrillEmail
143258 -- ^ The sender email address
144− , _mmsg_from_name :: Maybe T.Text
259+ , _mmsg_from_name :: Maybe T.Text
145260 -- ^ Optional from name to be used
146− , _mmsg_to :: [MandrillRecipient]
261+ , _mmsg_to :: [MandrillRecipient]
147262 -- ^ A list of recipient information
263+ , _mmsg_headers :: MandrillHeaders
264+ -- ^ optional extra headers to add to the message (most headers are allowed)
265+ , _mmsg_important :: Maybe Bool
266+ -- ^ whether or not this message is important, and should be delivered ahead
267+ -- of non-important messages
268+ , _mmsg_track_opens :: Maybe Bool
269+ -- ^ whether or not to turn on open tracking for the message
270+ , _mmsg_track_clicks :: Maybe Bool
271+ -- ^ whether or not to turn on click tracking for the message
272+ , _mmsg_auto_text :: Maybe Bool
273+ -- ^ whether or not to automatically generate a text part for messages that are not given text
274+ , _mmsg_auto_html :: Maybe Bool
275+ -- ^ whether or not to automatically generate an HTML part for messages that are not given HTML
276+ , _mmsg_inline_css :: Maybe Bool
277+ -- ^ whether or not to automatically inline all CSS styles provided in the message HTML
278+ -- - only for HTML documents less than 256KB in size
279+ , _mmsg_url_strip_qs :: Maybe Bool
280+ -- ^ whether or not to strip the query string from URLs when aggregating tracked URL data
281+ , _mmsg_preserve_recipients :: Maybe Bool
282+ -- ^ whether or not to expose all recipients in to "To" header for each email
283+ , _mmsg_view_content_link :: Maybe Bool
284+ -- ^ set to false to remove content logging for sensitive emails
285+ , _mmsg_bcc_address :: Maybe T.Text
286+ -- ^ an optional address to receive an exact copy of each recipient's email
287+ , _mmsg_tracking_domain :: Maybe T.Text
288+ -- ^ a custom domain to use for tracking opens and clicks instead of mandrillapp.com
289+ , _mmsg_signing_domain :: Maybe Bool
290+ -- ^ a custom domain to use for SPF/DKIM signing instead of mandrill
291+ -- (for "via" or "on behalf of" in email clients)
292+ , _mmsg_return_path_domain :: Maybe Bool
293+ -- ^ a custom domain to use for the messages's return-path
294+ , _mmsg_merge :: Maybe Bool
295+ -- ^ whether to evaluate merge tags in the message.
296+ -- Will automatically be set to true if either merge_vars
297+ -- or global_merge_vars are provided.
298+ , _mmsg_global_merge_vars :: [MergeVar]
299+ -- ^ global merge variables to use for all recipients. You can override these per recipient.
300+ , _mmsg_merge_vars :: [MandrillMergeVars]
301+ -- ^ per-recipient merge variables, which override global merge variables with the same name.
302+ , _mmsg_tags :: [MandrillTags]
303+ -- ^ an array of string to tag the message with. Stats are accumulated using tags,
304+ -- though we only store the first 100 we see, so this should not be unique
305+ -- or change frequently. Tags should be 50 characters or less.
306+ -- Any tags starting with an underscore are reserved for internal use
307+ -- and will cause errors.
308+ , _mmsg_subaccount :: Maybe T.Text
309+ -- ^ the unique id of a subaccount for this message
310+ -- - must already exist or will fail with an error
311+ , _mmsg_google_analytics_domains :: [T.Text]
312+ -- ^ an array of strings indicating for which any matching URLs
313+ -- will automatically have Google Analytics parameters appended
314+ -- to their query string automatically.
315+ , _mmsg_google_analytics_campaign :: Maybe T.Text
316+ -- ^ optional string indicating the value to set for the utm_campaign
317+ -- tracking parameter. If this isn't provided the email's from address
318+ -- will be used instead.
319+ , _mmsg_metadata :: Object
320+ -- ^ metadata an associative array of user metadata. Mandrill will store
321+ -- this metadata and make it available for retrieval.
322+ -- In addition, you can select up to 10 metadata fields to index
323+ -- and make searchable using the Mandrill search api.
324+ , _mmsg_recipient_metadata :: [MandrillMetadata]
325+ -- ^ Per-recipient metadata that will override the global values
326+ -- specified in the metadata parameter.
327+ , _mmsg_attachments :: [MandrillWebContent]
328+ -- ^ an array of supported attachments to add to the message
329+ , _mmsg_images :: [MandrillWebContent]
330+ -- ^ an array of embedded images to add to the message
148331 } deriving Show
149332
150333makeLenses ''MandrillMessage
151334deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillMessage
152335
336+instance Arbitrary MandrillMessage where
337+ arbitrary = MandrillMessage <$> arbitrary
338+ <*> pure Nothing
339+ <*> pure "Test Subject"
340+ <*> pure (MandrillEmail . fromJust $ emailAddress "sender@example.com")
341+ <*> pure Nothing
342+ <*> resize 2 arbitrary
343+ <*> pure H.empty
344+ <*> pure Nothing
345+ <*> pure Nothing
346+ <*> pure Nothing
347+ <*> pure Nothing
348+ <*> pure Nothing
349+ <*> pure Nothing
350+ <*> pure Nothing
351+ <*> pure Nothing
352+ <*> pure Nothing
353+ <*> pure Nothing
354+ <*> pure Nothing
355+ <*> pure Nothing
356+ <*> pure Nothing
357+ <*> pure Nothing
358+ <*> pure []
359+ <*> pure []
360+ <*> pure []
361+ <*> pure Nothing
362+ <*> pure []
363+ <*> pure Nothing
364+ <*> pure H.empty
365+ <*> pure []
366+ <*> pure []
367+ <*> pure []
153368
154369--------------------------------------------------------------------------------
155−-- * Send payloads
156−--------------------------------------------------------------------------------
370+-- | Key value pair for replacing content in templates via 'Editable Regions'
371+data MandrillTemplateContent = MandrillTemplateContent {
372+ _mtc_name :: T.Text
373+ , _mtc_content :: T.Text
374+ } deriving Show
157375
376+makeLenses ''MandrillTemplateContent
377+deriveJSON defaultOptions { fieldLabelModifier = drop 5 } ''MandrillTemplateContent
158378
159379--------------------------------------------------------------------------------
160380type MandrillKey = T.Text
381+type MandrillTemplate = T.Text
161382
162−
163−--------------------------------------------------------------------------------
164−data MandrillSendRq = MandrillSendRq {
165− _msrq_key :: MandrillKey
166− , _msrq_message :: MandrillMessage
167− , _msrq_async :: Maybe Bool
168− , _msrq_ip_pool :: Maybe T.Text
169− , _msrq_send_at :: Maybe UTCTime
383+newtype MandrillDate = MandrillDate {
384+ fromMandrillDate :: UTCTime
170385 } deriving Show
171386
172−makeLenses ''MandrillSendRq
173−deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillSendRq
387+instance ToJSON MandrillDate where
388+ toJSON = toJSON . fromMandrillDate
389+
390+instance FromJSON MandrillDate where
391+ parseJSON = withText "MandrillDate" $ \t ->
392+ case timeParse defaultTimeLocale "%Y-%m-%d %I:%M:%S%Q" (T.unpack t) of
393+ Just d -> pure $ MandrillDate d
394+ _ -> fail "could not parse Mandrill date"
src/Network/API/Mandrill/Users.hs+26−4
@@ -1,10 +1,32 @@
11
22module Network.API.Mandrill.Users where
33
4−info = undefined
4+import Network.API.Mandrill.Settings
5+import Network.API.Mandrill.HTTP
6+import Network.API.Mandrill.Types
7+import Network.API.Mandrill.Users.Types
8+import Network.HTTP.Client
59
6−ping = undefined
710
8−ping2 = undefined
11+--------------------------------------------------------------------------------
12+-- | Return the information about the API-connected user
13+info :: MandrillKey -> Maybe Manager -> IO (MandrillResponse UsersInfoResponse)
14+info key = toMandrillResponse UsersInfo (UsersRq key)
915
10−senders = undefined
16+
17+--------------------------------------------------------------------------------
18+-- | Validate an API key and respond to a ping
19+ping :: MandrillKey -> Maybe Manager -> IO (MandrillResponse UsersPingResponse)
20+ping _ _ = fail "users/ping.json doesn't return valid JSON, thus is not implemented yet."
21+
22+
23+--------------------------------------------------------------------------------
24+-- | Validate an API key and respond to a ping (anal JSON parser version)
25+ping2 :: MandrillKey -> Maybe Manager -> IO (MandrillResponse UsersPing2Response)
26+ping2 key = toMandrillResponse UsersPing2 (UsersRq key)
27+
28+
29+--------------------------------------------------------------------------------
30+-- | Return the senders that have tried to use this account, both verified and unverified
31+senders :: MandrillKey -> Maybe Manager -> IO (MandrillResponse [UsersSendersResponse])
32+senders key = toMandrillResponse UsersSenders (UsersRq key)
src/Network/API/Mandrill/Users/Types.hsnew file+122
@@ -0,0 +1,122 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Network.API.Mandrill.Users.Types where
4+
5+import Data.Char
6+import Data.Time
7+import qualified Data.Text as T
8+import Control.Monad
9+import Data.Monoid
10+import Data.Aeson
11+import Data.Aeson.Types
12+import Data.Aeson.TH
13+import Lens.Micro.TH (makeLenses)
14+
15+import Network.API.Mandrill.Types
16+
17+
18+--------------------------------------------------------------------------------
19+data UsersRq = UsersRq {
20+ _ureq_key :: !MandrillKey
21+ } deriving Show
22+
23+makeLenses ''UsersRq
24+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''UsersRq
25+
26+--------------------------------------------------------------------------------
27+data MandrillStats = MandrillStats {
28+ _msts_sent :: Int
29+ , _msts_hard_bounces :: Int
30+ , _msts_soft_bounces :: Int
31+ , _msts_rejects :: Int
32+ , _msts_complaints :: Int
33+ , _msts_unsubs :: Int
34+ , _msts_opens :: Int
35+ , _msts_unique_opens :: Int
36+ , _msts_clicks :: Int
37+ , _msts_unique_clicks :: Int
38+ } deriving Show
39+
40+makeLenses ''MandrillStats
41+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MandrillStats
42+
43+--------------------------------------------------------------------------------
44+data UserStats = UserStats {
45+ _usts_today :: MandrillStats
46+ , _usts_last_7_days :: MandrillStats
47+ , _usts_last_30_days :: MandrillStats
48+ , _usts_last_60_days :: MandrillStats
49+ , _usts_last_90_days :: MandrillStats
50+ , _usts_all_time :: MandrillStats
51+ } deriving Show
52+
53+makeLenses ''UserStats
54+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''UserStats
55+
56+--------------------------------------------------------------------------------
57+data UsersInfoResponse = UsersInfoResponse {
58+ _usir_username :: !T.Text
59+ , _usir_created_at :: MandrillDate
60+ , _usir_public_id :: !T.Text
61+ , _usir_reputation :: !Int
62+ , _usir_hourly_quota :: !Int
63+ , _usir_backlog :: !Int
64+ , _usir_stats :: UserStats
65+ } deriving Show
66+
67+makeLenses ''UsersInfoResponse
68+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''UsersInfoResponse
69+
70+
71+--------------------------------------------------------------------------------
72+newtype UsersPingResponse = UsersPingResponse T.Text deriving Show
73+
74+deriveFromJSON defaultOptions ''UsersPingResponse
75+
76+instance ToJSON UsersPingResponse where
77+ toJSON (UsersPingResponse t) = String t
78+
79+
80+--------------------------------------------------------------------------------
81+data UsersPing2Response = UsersPing2Response {
82+ _usrr_PING :: T.Text
83+ } deriving Show
84+
85+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''UsersPing2Response
86+
87+
88+
89+--------------------------------------------------------------------------------
90+data UsersSendersResponse = UsersResponse {
91+ _usrr_address :: !T.Text
92+ -- ^ The sender's email address
93+ , _usrr_created_at :: MandrillDate
94+ -- ^ The date and time that the sender was first seen by Mandrill
95+ -- as a UTC date string in YYYY-MM-DD HH:MM:SS format
96+ , _usrr_sent :: !Int
97+ -- ^ The total number of messages sent by this sender
98+ , _usrr_hard_bounces :: !Int
99+ -- ^ The total number of hard bounces by messages by this sender
100+ , _usrr_soft_bounces :: !Int
101+ -- ^ The total number of soft bounces by messages by this sender
102+ , _usrr_rejects :: !Int
103+ -- ^ The total number of rejected messages by this sender
104+ , _usrr_complaints :: !Int
105+ -- ^ The total number of spam complaints received
106+ -- for messages by this sender
107+ , _usrr_unsubs :: !Int
108+ -- ^ The total number of unsubscribe requests received
109+ -- for messages by this sender
110+ , _usrr_opens :: !Int
111+ -- ^ The total number of times messages by this sender have been opened
112+ , _usrr_clicks :: !Int
113+ -- ^ The total number of times tracked URLs in messages
114+ -- by this sender have been clicked
115+ , _usrr_unique_opens :: !Int
116+ -- ^ The number of unique opens for emails sent for this sender
117+ , _usrr_unique_clicks :: !Int
118+ -- ^ The number of unique clicks for emails sent for this sender
119+ } deriving Show
120+
121+makeLenses ''UsersSendersResponse
122+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''UsersSendersResponse
src/Network/API/Mandrill/Webhooks.hsnew file+70
@@ -0,0 +1,70 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE TemplateHaskell #-}
3+module Network.API.Mandrill.Webhooks where
4+import Control.Applicative (pure)
5+import Control.Monad (mzero)
6+import Data.Aeson (FromJSON, ToJSON, parseJSON,
7+ toJSON)
8+import Data.Aeson (Value (String))
9+import Data.Aeson.TH (defaultOptions, deriveJSON)
10+import Data.Aeson.Types (fieldLabelModifier)
11+import Data.Set (Set)
12+import Data.Text (Text)
13+import qualified Data.Text as T
14+import Lens.Micro.TH (makeLenses)
15+import Network.API.Mandrill.HTTP (toMandrillResponse)
16+import Network.API.Mandrill.Settings
17+import Network.API.Mandrill.Types
18+import Network.HTTP.Client (Manager)
19+
20+data EventHook
21+ = EventSent
22+ | EventDeferred
23+ | EventHardBounced
24+ | EventSoftBounced
25+ | EventOpened
26+ | EventClicked
27+ | EventMarkedAsSpam
28+ | EventUnsubscribed
29+ | EventRejected
30+ deriving (Ord,Eq)
31+
32+instance Show EventHook where
33+ show e = case e of
34+ EventSent -> "send"
35+ EventDeferred -> "deferral"
36+ EventSoftBounced -> "soft_bounce"
37+ EventHardBounced -> "hard_bounce"
38+ EventOpened -> "open"
39+ EventClicked -> "click"
40+ EventMarkedAsSpam -> "spam"
41+ EventUnsubscribed -> "unsub"
42+ EventRejected -> "reject"
43+instance FromJSON EventHook where
44+ parseJSON (String s) =
45+ case s of
46+ "send" -> pure EventSent
47+ "deferral" -> pure EventDeferred
48+ "soft_bounce" -> pure EventSoftBounced
49+ "hard_bounce" -> pure EventHardBounced
50+ "open" -> pure EventOpened
51+ "click" -> pure EventClicked
52+ "spam" -> pure EventMarkedAsSpam
53+ "reject" -> pure EventRejected
54+ "unsub" -> pure EventUnsubscribed
55+ x -> fail ("can't parse " ++ show x)
56+
57+
58+instance ToJSON EventHook where
59+ toJSON e = String (T.pack $ show e)
60+
61+data WebhookAddRq =
62+ WebhookAddRq
63+ { _warq_key :: MandrillKey
64+ , _warq_url :: Text
65+ , _warq_description :: Text
66+ , _warq_events :: Set EventHook
67+ } deriving Show
68+
69+makeLenses ''WebhookAddRq
70+deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''WebhookAddRq
stack.yamlnew file+5
@@ -0,0 +1,5 @@
1+flags: {}
2+packages:
3+- '.'
4+extra-deps: []
5+resolver: lts-11.13
test/Main.hsnew file+50
@@ -0,0 +1,50 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Main where
3+
4+import Data.Monoid
5+import qualified Data.Text as T
6+import Online
7+import System.Environment
8+import Test.Tasty
9+import Test.Tasty.HUnit
10+import Test.Tasty.QuickCheck
11+import Tests
12+
13+----------------------------------------------------------------------
14+withQuickCheckDepth :: TestName -> Int -> [TestTree] -> TestTree
15+withQuickCheckDepth tn depth tests =
16+ localOption (QuickCheckTests depth) (testGroup tn tests)
17+
18+----------------------------------------------------------------------
19+onlineTestsIfEnabled :: IO [TestTree]
20+onlineTestsIfEnabled = do
21+ apiKey <- (return . fmap T.pack) =<< lookupEnv "MANDRILL_API_KEY"
22+ case apiKey of
23+ Nothing -> return []
24+ Just k -> return [
25+ testGroup "Mandrill online tests" [
26+ testCase "users/info.json" (testOnlineUsersInfo k)
27+ , testCase "users/ping2.json" (testOnlineUsersPing2 k)
28+ , testCase "users/senders.json" (testOnlineUsersSenders k)
29+ , testCase "messages/send.json" (testOnlineMessagesSend k)
30+ , testCase "inbound/addDomain.json" (testOnlineDomainAdd k)
31+ , testCase "inbound/addRoute.json" (testOnlineRouteAdd k)
32+ ]]
33+
34+----------------------------------------------------------------------
35+main :: IO ()
36+main = do
37+ onlineTests <- onlineTestsIfEnabled
38+ defaultMainWithIngredients defaultIngredients $
39+ testGroup "Mandrill tests" $ onlineTests <> [
40+ testGroup "Mandrill offline tests" [
41+ testCase "users/info.json API parsing" testUsersInfo
42+ , testCase "users/senders.json API parsing" testUsersSenders
43+ , testCase "messages/send.json API parsing" testMessagesSend
44+ , testCase "messages/send.json API response parsing" testMessagesResponseRejected
45+ , testCase "inbound/add-route.json API response parsing" testRouteAdd
46+ , testCase "inbound/add-domain.json API response parsing" testDomainAdd
47+ , testCase "senders/verify-domain.json API response parsing" testVerifyDomain
48+ , testCase "webhooks/add.json API response parsing" testWebhookAdd
49+ ]
50+ ]
test/Online.hsnew file+70
@@ -0,0 +1,70 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Online where
3+
4+import Data.Aeson
5+import qualified Data.ByteString.Char8 as C8
6+import Data.Either
7+import Network.API.Mandrill.Messages.Types
8+import Network.API.Mandrill.Users.Types
9+import RawData
10+import Test.QuickCheck
11+import Test.Tasty.HUnit
12+import Text.RawString.QQ
13+
14+import qualified Network.API.Mandrill.Inbound as API
15+import qualified Network.API.Mandrill.Messages as API
16+import Network.API.Mandrill.Types
17+import qualified Network.API.Mandrill.Users as API
18+
19+--
20+-- Users calls
21+--
22+testOnlineUsersInfo :: MandrillKey -> Assertion
23+testOnlineUsersInfo k = do
24+ res <- API.info k Nothing
25+ case res of
26+ MandrillSuccess _ -> return ()
27+ MandrillFailure e -> fail $ "users/info.json " ++ show e
28+
29+testOnlineUsersPing2 :: MandrillKey -> Assertion
30+testOnlineUsersPing2 k = do
31+ res <- API.ping2 k Nothing
32+ case res of
33+ MandrillSuccess _ -> return ()
34+ MandrillFailure e -> fail $ "users/ping2.json " ++ show e
35+
36+testOnlineUsersSenders :: MandrillKey -> Assertion
37+testOnlineUsersSenders k = do
38+ res <- API.senders k Nothing
39+ case res of
40+ MandrillSuccess _ -> return ()
41+ MandrillFailure e -> fail $ "users/senders.json " ++ show e
42+
43+
44+--
45+-- Messages calls
46+--
47+testOnlineMessagesSend :: MandrillKey -> Assertion
48+testOnlineMessagesSend k = do
49+ msg <- generate arbitrary
50+ res <- API.send k msg Nothing Nothing Nothing Nothing
51+ case res of
52+ MandrillSuccess _ -> return ()
53+ MandrillFailure e -> fail $ "messages/send.json " ++ show e
54+
55+--
56+-- Inbound calls
57+--
58+testOnlineDomainAdd :: MandrillKey -> Assertion
59+testOnlineDomainAdd k = do
60+ res <- API.addDomain k "foobar.com" Nothing
61+ case res of
62+ MandrillSuccess a -> print a
63+ MandrillFailure e -> fail $ "inbound/add-domain.json " ++ show e
64+
65+testOnlineRouteAdd :: MandrillKey -> Assertion
66+testOnlineRouteAdd k = do
67+ res <- API.addRoute k "foobar.com" "mail-*" "http://requestb.in/19a4frw1" Nothing
68+ case res of
69+ MandrillSuccess a -> print a
70+ MandrillFailure e -> fail $ "inbound/add-domain.json " ++ show e
test/RawData.hsnew file+257
@@ -0,0 +1,257 @@
1+{-# LANGUAGE QuasiQuotes #-}
2+module RawData where
3+
4+import Data.Either
5+import Test.QuickCheck
6+import Test.Tasty.HUnit
7+import Text.RawString.QQ
8+
9+usersInfoData :: String
10+usersInfoData = [r|
11+{
12+ "username": "foo@bar.com",
13+ "created_at": "2014-03-27 09:42:20.62599",
14+ "public_id": "barbaz",
15+ "reputation": 99,
16+ "hourly_quota": 1094,
17+ "backlog": 0,
18+ "stats": {
19+ "today": {
20+ "sent": 102,
21+ "hard_bounces": 0,
22+ "soft_bounces": 0,
23+ "rejects": 0,
24+ "complaints": 0,
25+ "unsubs": 0,
26+ "opens": 71,
27+ "unique_opens": 52,
28+ "clicks": 25,
29+ "unique_clicks": 19
30+ },
31+ "last_7_days": {
32+ "sent": 396,
33+ "hard_bounces": 0,
34+ "soft_bounces": 1,
35+ "rejects": 0,
36+ "complaints": 0,
37+ "unsubs": 0,
38+ "opens": 321,
39+ "unique_opens": 209,
40+ "clicks": 147,
41+ "unique_clicks": 84
42+ },
43+ "last_30_days": {
44+ "sent": 3022,
45+ "hard_bounces": 3,
46+ "soft_bounces": 4,
47+ "rejects": 0,
48+ "complaints": 0,
49+ "unsubs": 0,
50+ "opens": 2408,
51+ "unique_opens": 1540,
52+ "clicks": 958,
53+ "unique_clicks": 578
54+ },
55+ "last_60_days": {
56+ "sent": 6120,
57+ "hard_bounces": 5,
58+ "soft_bounces": 4,
59+ "rejects": 0,
60+ "complaints": 0,
61+ "unsubs": 0,
62+ "opens": 4869,
63+ "unique_opens": 3112,
64+ "clicks": 2004,
65+ "unique_clicks": 1223
66+ },
67+ "last_90_days": {
68+ "sent": 9267,
69+ "hard_bounces": 6,
70+ "soft_bounces": 4,
71+ "rejects": 1,
72+ "complaints": 1,
73+ "unsubs": 0,
74+ "opens": 7428,
75+ "unique_opens": 4772,
76+ "clicks": 2943,
77+ "unique_clicks": 1802
78+ },
79+ "all_time": {
80+ "sent": 15278,
81+ "hard_bounces": 7,
82+ "soft_bounces": 7,
83+ "rejects": 1,
84+ "complaints": 1,
85+ "unsubs": 0,
86+ "opens": 12782,
87+ "unique_opens": 7926,
88+ "clicks": 5336,
89+ "unique_clicks": 3341
90+ }
91+ }
92+}
93+|]
94+
95+usersSendersData :: String
96+usersSendersData = [r|
97+{
98+ "address": "sender.example@mandrillapp.com",
99+ "created_at": "2014-08-12 20:49:42.8344",
100+ "sent": 42,
101+ "hard_bounces": 42,
102+ "soft_bounces": 42,
103+ "rejects": 42,
104+ "complaints": 42,
105+ "unsubs": 42,
106+ "opens": 42,
107+ "clicks": 42,
108+ "unique_opens": 42,
109+ "unique_clicks": 42
110+}
111+|]
112+
113+sendData :: String
114+sendData = [r|
115+{
116+ "key": "example key",
117+ "message": {
118+ "html": "<p>Example HTML content</p>",
119+ "text": "Example text content",
120+ "subject": "example subject",
121+ "from_email": "message.from_email@example.com",
122+ "from_name": "Example Name",
123+ "to": [
124+ {
125+ "email": "recipient.email@example.com",
126+ "name": "Recipient Name",
127+ "type": "to"
128+ }
129+ ],
130+ "headers": {
131+ "Reply-To": "message.reply@example.com"
132+ },
133+ "important": false,
134+ "track_opens": null,
135+ "track_clicks": null,
136+ "auto_text": null,
137+ "auto_html": null,
138+ "inline_css": null,
139+ "url_strip_qs": null,
140+ "preserve_recipients": null,
141+ "view_content_link": null,
142+ "bcc_address": "message.bcc_address@example.com",
143+ "tracking_domain": null,
144+ "signing_domain": null,
145+ "return_path_domain": null,
146+ "merge": true,
147+ "global_merge_vars": [
148+ {
149+ "name": "merge1",
150+ "content": "merge1 content"
151+ }
152+ ],
153+ "merge_vars": [
154+ {
155+ "rcpt": "recipient.email@example.com",
156+ "vars": [
157+ {
158+ "name": "merge2",
159+ "content": "merge2 content"
160+ }
161+ ]
162+ }
163+ ],
164+ "tags": [
165+ "password-resets"
166+ ],
167+ "subaccount": "customer-123",
168+ "google_analytics_domains": [
169+ "example.com"
170+ ],
171+ "google_analytics_campaign": "message.from_email@example.com",
172+ "metadata": {
173+ "website": "www.example.com"
174+ },
175+ "recipient_metadata": [
176+ {
177+ "rcpt": "recipient.email@example.com",
178+ "values": {
179+ "user_id": 123456
180+ }
181+ }
182+ ],
183+ "attachments": [
184+ {
185+ "type": "text/plain",
186+ "name": "myfile.txt",
187+ "content": "ZXhhbXBsZSBmaWxl"
188+ }
189+ ],
190+ "images": [
191+ {
192+ "type": "image/png",
193+ "name": "IMAGECID",
194+ "content": "ZXhhbXBsZSBmaWxl"
195+ }
196+ ]
197+ },
198+ "async": false,
199+ "ip_pool": "Main Pool",
200+ "send_at": "2014-08-17T14:23:02.954Z"
201+}
202+|]
203+
204+
205+messagesResponseRejected = [r|
206+[ { "email" : "foo@bar.com",
207+ "status" : "rejected",
208+ "_id" : "abc123",
209+ "reject_reason": "unsigned"
210+ }
211+]
212+|]
213+
214+
215+domainAdd = [r|
216+{
217+ "domain": "inbound.example.com",
218+ "created_at": "2013-01-01 15:30:27",
219+ "valid_mx": true
220+}
221+|]
222+
223+
224+routeAdd= [r|
225+{
226+ "id": "7.23",
227+ "pattern": "mailbox-*",
228+ "url": "http://example.com/webhook-url"
229+}
230+|]
231+
232+domainVerify = [r|
233+{
234+ "status": "example status",
235+ "domain": "example domain",
236+ "email": "email@domain.com"
237+}
238+|]
239+
240+webhookAdd = [r|
241+{
242+ "key": "example key",
243+ "url": "http://example/webhook-url",
244+ "description": "My Example Webhook",
245+ "events": [
246+ "send",
247+ "deferral",
248+ "hard_bounce",
249+ "soft_bounce",
250+ "open",
251+ "click",
252+ "spam",
253+ "unsub",
254+ "reject"
255+ ]
256+}
257+|]
test/Tests.hsnew file+88
@@ -0,0 +1,88 @@
1+{-# LANGUAGE CPP #-}
2+module Tests where
3+
4+import Data.Aeson
5+import qualified Data.ByteString.Char8 as C8
6+import Data.Either
7+import Network.API.Mandrill.Inbound
8+import Network.API.Mandrill.Messages.Types
9+import Network.API.Mandrill.Senders
10+import Network.API.Mandrill.Types
11+import Network.API.Mandrill.Users.Types
12+import Network.API.Mandrill.Webhooks
13+import RawData
14+import Test.Tasty.HUnit
15+
16+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 706
17+isRight :: Either a b -> Bool
18+isRight (Left _) = False
19+isRight _ = True
20+#endif
21+
22+testMessagesSend :: Assertion
23+testMessagesSend =
24+ assertBool ("send.json: Parsing failed! " ++ show parsePayload)
25+ (isRight parsePayload)
26+ where
27+ parsePayload :: Either String MessagesSendRq
28+ parsePayload = eitherDecodeStrict . C8.pack $ sendData
29+
30+testUsersInfo :: Assertion
31+testUsersInfo = do
32+ let res = parsePayload
33+ assertBool ("users/info.json (response): Parsing failed: " ++ show res)
34+ (isRight parsePayload)
35+ where
36+ parsePayload :: Either String UsersInfoResponse
37+ parsePayload = eitherDecodeStrict . C8.pack $ usersInfoData
38+
39+testUsersSenders :: Assertion
40+testUsersSenders = do
41+ let res = parsePayload
42+ assertBool ("users/senders.json (response): Parsing failed: " ++ show res)
43+ (isRight parsePayload)
44+ where
45+ parsePayload :: Either String UsersSendersResponse
46+ parsePayload = eitherDecodeStrict . C8.pack $ usersSendersData
47+
48+testMessagesResponseRejected :: Assertion
49+testMessagesResponseRejected = do
50+ assertBool ("send.json response: Parsing failed" ++ show parsePayload)
51+ (isRight parsePayload)
52+ where
53+ parsePayload :: Either String (MandrillResponse [MessagesResponse])
54+ parsePayload = eitherDecodeStrict . C8.pack $ messagesResponseRejected
55+
56+testDomainAdd :: Assertion
57+testDomainAdd =
58+ assertBool ("inbound/add-domain.json (response): parsing failed" ++ show parsePayload)
59+ (isRight parsePayload)
60+ where
61+ parsePayload :: Either String DomainAddResponse
62+ parsePayload = eitherDecodeStrict . C8.pack $ domainAdd
63+
64+
65+testRouteAdd :: Assertion
66+testRouteAdd =
67+ assertBool ("inbound/add-route.json (response): parsing failed" ++ show parsePayload)
68+ (isRight parsePayload)
69+ where
70+ parsePayload :: Either String RouteAddResponse
71+ parsePayload = eitherDecodeStrict . C8.pack $ routeAdd
72+
73+testVerifyDomain :: Assertion
74+testVerifyDomain =
75+ assertBool ("senders/verify-domain.json" ++ show parsePayload)
76+ (isRight parsePayload)
77+ where
78+ parsePayload :: Either String VerifyDomainResponse
79+ parsePayload = eitherDecodeStrict . C8.pack $ domainVerify
80+
81+
82+testWebhookAdd :: Assertion
83+testWebhookAdd =
84+ assertBool ("webhooks/add.json (request): parsing failed" ++ show parsePayload)
85+ (isRight parsePayload)
86+ where
87+ parsePayload :: Either String WebhookAddRq
88+ parsePayload = eitherDecodeStrict . C8.pack $ webhookAdd