gogol-core (empty) → 0.0.1
raw patch · 10 files changed
+1322/−0 lines, 10 filesdep +aesondep +attoparsecdep +basesetup-changed
Dependencies added: aeson, attoparsec, base, bytestring, case-insensitive, conduit, dlist, exceptions, gogol-core, hashable, http-client, http-media, http-types, lens, nats, old-locale, resourcet, scientific, servant, tasty, text, time, unordered-containers
Files
- LICENSE +367/−0
- README.md +20/−0
- Setup.hs +2/−0
- gogol-core.cabal +90/−0
- src/Network/Google/Data/JSON.hs +64/−0
- src/Network/Google/Data/Numeric.hs +61/−0
- src/Network/Google/Data/Time.hs +125/−0
- src/Network/Google/Prelude.hs +35/−0
- src/Network/Google/Types.hs +542/−0
- test/Main.hs +16/−0
+ LICENSE view
@@ -0,0 +1,367 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.
+ README.md view
@@ -0,0 +1,20 @@+# Gogol Core++* [Description](#description)+* [Contribute](#contribute)+* [Licence](#licence)+++## Description++> TODO+++## Contribute++For any problems, comments, or feedback please create an issue [here on GitHub](https://github.com/brendanhay/gogol/issues).+++## Licence++Gogol is released under the [Mozilla Public License Version 2.0](http://www.mozilla.org/MPL/).
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ gogol-core.cabal view
@@ -0,0 +1,90 @@+name: gogol-core+version: 0.0.1+synopsis: Core data types and functionality for Gogol libraries.+homepage: https://github.com/brendanhay/gogol+bug-reports: https://github.com/brendanhay/gogol/issues+license: OtherLicense+license-file: LICENSE+author: Brendan Hay+maintainer: Brendan Hay <brendan.g.hay@gmail.com>+copyright: Copyright (c) 2015 Brendan Hay+category: Network, Google, Cloud+build-type: Simple+extra-source-files: README.md+cabal-version: >= 1.10++description:+ Core data types, functionality and serialisation primitives for+ Gogol related Google Services SDKs.+ .+ The external interface of this library is stable with respect to the+ downstream Gogol libraries, only, and as such is not suitable+ for use in non-Gogol projects.++source-repository head+ type: git+ location: git://github.com/brendanhay/gogol.git++flag old-locale+ description: Use old-locale and time < 1.5+ default: False++library+ default-language: Haskell2010+ hs-source-dirs: src++ ghc-options: -Wall++ exposed-modules:+ Network.Google.Data.JSON+ , Network.Google.Data.Numeric+ , Network.Google.Data.Time+ , Network.Google.Prelude+ , Network.Google.Types++ build-depends:+ aeson >= 0.8+ , attoparsec >= 0.11.3+ , base >= 4.7 && < 5+ , bytestring >= 0.9+ , case-insensitive >= 1.2+ , conduit >= 1.1+ , dlist >= 0.7+ , exceptions >= 0.6+ , hashable >= 1.2+ , http-client >= 0.4.4+ , http-media >= 0.6+ , http-types >= 0.8.6+ , lens >= 4.4+ , resourcet >= 1.1+ , scientific >= 0.3+ , servant >= 0.4.4+ , text >= 1.1+ , unordered-containers >= 0.2.5++ if !impl(ghc>=7.9)+ build-depends:+ nats >= 0.1.3++ if flag(old-locale)+ build-depends:+ old-locale == 1.*+ , time >= 1.2 && < 1.5+ else+ build-depends:+ time >= 1.5 && < 1.6++test-suite tests+ type: exitcode-stdio-1.0+ default-language: Haskell2010+ hs-source-dirs: test+ main-is: Main.hs++ ghc-options: -Wall -threaded++ other-modules:++ build-depends:+ gogol-core+ , base+ , tasty
+ src/Network/Google/Data/JSON.hs view
@@ -0,0 +1,64 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- |+-- Module : Network.Google.Data.JSON+-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : provisional+-- Portability : non-portable (GHC extensions)+--+module Network.Google.Data.JSON+ ( JSONValue+ , Textual (..)+ , parseJSONObject+ , parseJSONText+ , toJSONText++ -- * Re-exports+ , FromJSON (..)+ , ToJSON (..)++ , withObject+ , emptyObject+ , object++ , (.=)+ , (.:)+ , (.:?)+ , (.!=)+ ) where++import Data.Aeson+import Data.Aeson.Types+import Data.Data+import Data.HashMap.Strict (HashMap)+import Data.Text (Text)+import qualified Data.Text as Text+import Servant.API++type JSONValue = Value++newtype Textual a = Textual a+ deriving (Eq, Ord, Read, Show, Num, Fractional, Data, Typeable, FromText, ToText)++instance (FromJSON a, FromText a) => FromJSON (Textual a) where+ parseJSON (String s) =+ case fromText s of+ Just x -> pure (Textual x)+ Nothing -> fail $ "Failed to parse value from " ++ Text.unpack s+ parseJSON o = Textual <$> parseJSON o++instance ToText a => ToJSON (Textual a) where+ toJSON (Textual x) = String (toText x)++parseJSONObject :: FromJSON a => HashMap Text Value -> Parser a+parseJSONObject = parseJSON . Object++parseJSONText :: FromText a => String -> Value -> Parser a+parseJSONText n = withText n (maybe (fail n) pure . fromText)++toJSONText :: ToText a => a -> Value+toJSONText = String . toText
+ src/Network/Google/Data/Numeric.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- |+-- Module : Network.Google.Data.Numeric+-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : provisional+-- Portability : non-portable (GHC extensions)+--+module Network.Google.Data.Numeric+ ( Nat (..)+ ) where++import Control.Lens+import Control.Monad+import Data.Aeson+import Data.Data+import Data.Scientific+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Lazy as LText+import Data.Text.Lazy.Builder (Builder)+import qualified Data.Text.Lazy.Builder as Build+import qualified Data.Text.Lazy.Builder.Int as Build+import qualified Data.Text.Read as Read+import Numeric.Natural+import Servant.API++newtype Nat = Nat { unNat :: Natural }+ deriving (Eq, Ord, Enum, Show, Read, Num, Real, Integral, Data, Typeable)++instance FromJSON Nat where+ parseJSON = parseJSON >=> go+ where+ go n = case floatingOrInteger n of+ Left (_ :: Double) -> fail (floatErr n)+ Right i+ | n < 0 -> fail (negateErr n)+ | otherwise -> return . Nat $ fromInteger i++ floatErr = mappend "Cannot convert float to Natural: " . show+ negateErr = mappend "Cannot convert negative number to Natural: " . show++instance ToJSON Nat where+ toJSON = Number . flip scientific 0 . toInteger . unNat++instance ToText Nat where+ toText = shortText . Build.decimal++instance FromText Nat where+ fromText t =+ case Read.decimal t of+ Right (x, r) | Text.null r+ -> Just x+ _ -> Nothing++shortText :: Builder -> Text+shortText = LText.toStrict . Build.toLazyTextWith 32
+ src/Network/Google/Data/Time.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++-- |+-- Module : Network.Google.Data.Time+-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : provisional+-- Portability : non-portable (GHC extensions)+--+module Network.Google.Data.Time+ ( Time' (..)+ , Date' (..)+ , DateTime' (..)++ , _Time+ , _Date+ , _DateTime+ ) where++import Control.Lens+import Data.Aeson+import Data.Aeson.Encode+import qualified Data.Aeson.Types as Aeson+import Data.Attoparsec.Text+import Data.Bits ((.&.))+import Data.Char (ord)+import Data.Data (Data, Typeable)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Lazy as LText+import qualified Data.Text.Lazy.Builder as Build+import Data.Time+import GHC.Generics+import Servant.Common.Text++-- | This SHOULD be a time in the format of hh:mm:ss. It is+-- recommended that you use the "date-time" format instead of "time"+-- unless you need to transfer only the time part.+newtype Time' = Time' TimeOfDay+ deriving (Eq, Ord, Show, Read, Generic, Data, Typeable)++_Time :: Iso' Time' TimeOfDay+_Time = iso (\(Time' t) -> t) Time'++-- | This SHOULD be a date in the format of YYYY-MM-DD. It is+-- recommended that you use the "date-time" format instead of "date"+-- unless you need to transfer only the date part.+newtype Date' = Date' Day+ deriving (Eq, Ord, Show, Read, Generic, Data, Typeable)++_Date :: Iso' Date' Day+_Date = iso (\(Date' t) -> t) Date'++-- | This SHOULD be a date in ISO 8601 format of YYYY-MM-+-- DDThh:mm:ssZ in UTC time. This is the recommended form of date/timestamp.+newtype DateTime' = DateTime' UTCTime+ deriving (Eq, Ord, Show, Read, Generic, Data, Typeable)++_DateTime :: Iso' DateTime' UTCTime+_DateTime = iso (\(DateTime' t) -> t) DateTime'++instance FromText Time' where fromText = fmap Time' . parseText timeParser+instance FromText Date' where fromText = fmap Date' . parseText dayParser+instance FromText DateTime' where fromText = Aeson.parseMaybe parseJSON . String++instance FromJSON Time' where+ parseJSON = fmap Time' . withText "time" (run timeParser)++instance FromJSON Date' where+ parseJSON = fmap Date' . withText "date" (run dayParser)++instance FromJSON DateTime' where+ parseJSON = fmap DateTime' . parseJSON++-- FIXME: Revisit once aeson-0.10 is more widely available.+instance ToText Time' where toText = Text.pack . show . view _Time+instance ToText Date' where toText = Text.pack . show . view _Date+instance ToText DateTime' where toText = encodeText++-- FIXME: Revisit once aeson-0.10 is more widely available.+instance ToJSON Time' where toJSON = String . toText+instance ToJSON Date' where toJSON = String . toText+instance ToJSON DateTime' where toJSON = toJSON . view _DateTime++parseText :: Parser a -> Text -> Maybe a+parseText p = either (const Nothing) Just . parseOnly p++encodeText :: ToJSON a => a -> Text+encodeText = LText.toStrict . Build.toLazyText . encodeToTextBuilder . toJSON++-- | Parse a time of the form @HH:MM:SS@.+timeParser :: Parser TimeOfDay+timeParser = do+ h <- twoDigits <* char ':'+ m <- twoDigits <* char ':'+ s <- twoDigits <&> fromIntegral+ if h < 24 && m < 60 && s < 61+ then pure (TimeOfDay h m s)+ else fail "invalid time"++-- | Parse a date of the form @YYYY-MM-DD@.+dayParser :: Parser Day+dayParser = do+ y <- decimal <* char '-'+ m <- twoDigits <* char '-'+ d <- twoDigits+ maybe (fail "invalid date") pure (fromGregorianValid y m d)++-- | Parse a two-digit integer (e.g. day of month, hour).+twoDigits :: Parser Int+twoDigits = do+ a <- digit+ b <- digit+ let c2d c = ord c .&. 15+ pure $! c2d a * 10 + c2d b++-- | Run an attoparsec parser as an aeson parser.+run :: Parser a -> Text -> Aeson.Parser a+run p t =+ case parseOnly (p <* endOfInput) t of+ Left err -> fail $ "could not parse date: " ++ err+ Right r -> pure r
+ src/Network/Google/Prelude.hs view
@@ -0,0 +1,35 @@+-- |+-- Module : Network.Google.Prelude+-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : provisional+-- Portability : non-portable (GHC extensions)+--+module Network.Google.Prelude+ ( module Export+ ) where++import Control.Applicative as Export (pure, (<$>), (<*>))+import Control.Lens as Export (Lens', lens, mapping,+ ( # ), (^.), _Just)+import Data.Data as Export (Data, Typeable)+import Data.Hashable as Export+import Data.HashMap.Strict as Export (HashMap)+import Data.Int as Export (Int32, Int64)+import Data.Maybe as Export+import Data.Monoid as Export (mempty, (<>))+import Data.Proxy as Export+import Data.Text as Export (Text)+import Data.Time as Export (Day, TimeOfDay, UTCTime)+import Data.Word as Export (Word32, Word64, Word8)+import GHC.Generics as Export (Generic)+import Network.Google.Data.JSON as Export+import Network.Google.Data.Numeric as Export+import Network.Google.Data.Time as Export+import Network.Google.Types as Export+import Network.HTTP.Client as Export (RequestBody)+import Numeric.Natural as Export (Natural)+import Prelude as Export hiding (product)+import Servant.API as Export hiding (getResponse)+import Servant.Utils.Links as Export hiding (Link)
+ src/Network/Google/Types.hs view
@@ -0,0 +1,542 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++-- |+-- Module : Network.Google.Types+-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : provisional+-- Portability : non-portable (GHC extensions)+--+module Network.Google.Types where++import Control.Applicative+import Control.Exception.Lens (exception)+import Control.Lens hiding (coerce)+import Control.Monad.Catch+import Control.Monad.Trans.Resource+import Data.Aeson+import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as LBS+import qualified Data.CaseInsensitive as CI+import Data.Coerce+import Data.Conduit+import qualified Data.Conduit.List as CL+import Data.Data+import Data.DList (DList)+import qualified Data.DList as DList+import Data.Foldable (foldl')+import Data.Monoid+import Data.String+import Data.Text (Text)+import qualified Data.Text.Encoding as Text+import Data.Text.Lazy.Builder (Builder)+import qualified Data.Text.Lazy.Builder as Build+import GHC.Generics+import GHC.TypeLits+import Network.HTTP.Client (HttpException, RequestBody (..))+import Network.HTTP.Media hiding (Accept)+import Network.HTTP.Types hiding (Header)+import qualified Network.HTTP.Types as HTTP+import Servant.API++data AltJSON = AltJSON+ deriving (Eq, Ord, Show, Read, Generic, Typeable)++instance ToText AltJSON where+ toText = const "json"++data AltMedia = AltMedia+ deriving (Eq, Ord, Show, Read, Generic, Typeable)++instance ToText AltMedia where+ toText = const "media"++newtype AuthKey = AuthKey Text+ deriving (Eq, Ord, Show, Read, Generic, Typeable, ToText, FromJSON, ToJSON)++newtype OAuthScope = OAuthScope { scopeToText :: Text }+ deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, ToText, FromJSON, ToJSON)++newtype OAuthToken = OAuthToken { tokenToBS :: ByteString }+ deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable)++instance FromJSON OAuthToken where+ parseJSON = withText "oauth_token" (pure . OAuthToken . Text.encodeUtf8)++instance ToJSON OAuthToken where+ toJSON = toJSON . Text.decodeUtf8 . tokenToBS++newtype MediaDownload a = MediaDownload a++data MediaUpload a = MediaUpload a RequestBody++_Coerce :: (Coercible a b, Coercible b a) => Iso' a b+_Coerce = iso coerce coerce++-- | Invalid Iso, exists for ease of composition with the current 'Lens . Iso'+-- chaining to hide internal types from the user.+_Default :: Monoid a => Iso' (Maybe a) a+_Default = iso f Just+ where+ f (Just x) = x+ f Nothing = mempty++type Stream = ResumableSource (ResourceT IO) ByteString++newtype ClientId = ClientId { clientIdToText :: Text }+ deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, ToText, FromJSON, ToJSON)++newtype ServiceId = ServiceId { serviceIdToText :: Text }+ deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, ToText, FromJSON, ToJSON)++data Error+ = TransportError HttpException+ | SerializeError SerializeError+ | ServiceError ServiceError+ deriving (Show, Typeable)++instance Exception Error++data SerializeError = SerializeError'+ { _serializeId :: !ServiceId+ , _serializeHeaders :: [HTTP.Header]+ , _serializeStatus :: !Status+ , _serializeMessage :: !String+ , _serializeBody :: !(Maybe LBS.ByteString)+ } deriving (Eq, Show, Typeable)++data ServiceError = ServiceError'+ { _serviceId :: !ServiceId+ , _serviceStatus :: !Status+ , _serviceHeaders :: ![HTTP.Header]+ , _serviceBody :: !(Maybe LBS.ByteString)+ } deriving (Eq, Show, Typeable)++class AsError a where+ -- | A general Amazonka error.+ _Error :: Prism' a Error+ {-# MINIMAL _Error #-}++ -- | An error occured while communicating over HTTP with a remote service.+ _TransportError :: Prism' a HttpException++ -- | A serialisation error occured when attempting to deserialise a response.+ _SerializeError :: Prism' a SerializeError++ -- | A service specific error returned by the remote service.+ _ServiceError :: Prism' a ServiceError++ _TransportError = _Error . _TransportError+ _SerializeError = _Error . _SerializeError+ _ServiceError = _Error . _ServiceError++instance AsError SomeException where+ _Error = exception++instance AsError Error where+ _Error = id++ _TransportError = prism TransportError $ \case+ TransportError e -> Right e+ x -> Left x++ _SerializeError = prism SerializeError $ \case+ SerializeError e -> Right e+ x -> Left x++ _ServiceError = prism ServiceError $ \case+ ServiceError e -> Right e+ x -> Left x++data Service = Service+ { _svcId :: !ServiceId+ , _svcHost :: !ByteString+ , _svcPath :: !Builder+ , _svcPort :: !Int+ , _svcSecure :: !Bool+ , _svcTimeout :: !(Maybe Seconds)+ }++defaultService :: ServiceId -> ByteString -> Service+defaultService i h = Service+ { _svcId = i+ , _svcHost = h+ , _svcPath = mempty+ , _svcPort = 443+ , _svcSecure = True+ , _svcTimeout = Just 70+ }++serviceHost :: Lens' Service ByteString+serviceHost = lens _svcHost (\s a -> s { _svcHost = a })++servicePath :: Lens' Service Builder+servicePath = lens _svcPath (\s a -> s { _svcPath = a })++servicePort :: Lens' Service Int+servicePort = lens _svcPort (\s a -> s { _svcPort = a })++serviceSecure :: Lens' Service Bool+serviceSecure = lens _svcSecure (\s a -> s { _svcSecure = a })++serviceTimeout :: Lens' Service (Maybe Seconds)+serviceTimeout = lens _svcTimeout (\s a -> s { _svcTimeout = a })++-- | A single part of a multipart message.+data Part = Part MediaType [(HeaderName, ByteString)] RequestBody++data Payload+ = Body !MediaType !RequestBody+ | Related ![Part]++-- | An intermediary request builder.+data Request = Request+ { _rqPath :: !Builder+ , _rqQuery :: !(DList (ByteString, Maybe ByteString))+ , _rqHeaders :: !(DList (HeaderName, ByteString))+ , _rqBody :: !(Maybe Payload)+ }++instance Monoid Request where+ mempty = Request mempty mempty mempty Nothing+ mappend a b = Request+ (_rqPath a <> "/" <> _rqPath b)+ (_rqQuery a <> _rqQuery b)+ (_rqHeaders a <> _rqHeaders b)+ (_rqBody b <|> _rqBody a)++appendPath :: Request -> Builder -> Request+appendPath rq x = rq { _rqPath = _rqPath rq <> "/" <> x }++appendPaths :: ToText a => Request -> [a] -> Request+appendPaths rq = appendPath rq . foldMap (mappend "/" . buildText)++appendQuery :: Request -> ByteString -> Maybe Text -> Request+appendQuery rq k v = rq+ { _rqQuery = DList.snoc (_rqQuery rq) (k, Text.encodeUtf8 <$> v)+ }++appendHeader :: Request -> HeaderName -> Maybe Text -> Request+appendHeader rq _ Nothing = rq+appendHeader rq k (Just v) = rq+ { _rqHeaders = DList.snoc (_rqHeaders rq) (k, Text.encodeUtf8 v)+ }++setBody :: Request -> MediaType -> RequestBody -> Request+setBody rq c x = rq { _rqBody = Just (Body c x) }++setRelated :: Request -> [Part] -> Request+setRelated rq ps = rq { _rqBody = Just (Related ps) }++-- | A materialised 'http-client' request and associated response parser.+data Client a = Client+ { _cliAccept :: !(Maybe MediaType)+ , _cliMethod :: !Method+ , _cliCheck :: !(Status -> Bool)+ , _cliService :: !Service+ , _cliRequest :: !Request+ , _cliResponse :: !(Stream -> ResourceT IO (Either (String, LBS.ByteString) a))+ }++clientService :: Lens' (Client a) Service+clientService = lens _cliService (\s a -> s { _cliService = a })++mime :: FromStream c a => Proxy c -> Method -> [Int] -> Request -> Service -> Client a+mime p = client (fromStream p) (Just (contentType p))++discard :: Method -> [Int] -> Request -> Service -> Client ()+discard = client (\b -> closeResumableSource b >> pure (Right ())) Nothing++client :: (Stream -> ResourceT IO (Either (String, LBS.ByteString) a))+ -> Maybe MediaType+ -> Method+ -> [Int]+ -> Request+ -> Service+ -> Client a+client f cs m ns rq s = Client+ { _cliAccept = cs+ , _cliMethod = m+ , _cliCheck = (`elem` ns) . fromEnum+ , _cliService = s+ , _cliRequest = rq+ , _cliResponse = f+ }++class Accept c => ToBody c a where+ toBody :: Proxy c -> a -> RequestBody++instance ToBody OctetStream RequestBody where+ toBody Proxy = id++instance ToBody OctetStream ByteString where+ toBody Proxy = RequestBodyBS++instance ToBody OctetStream LBS.ByteString where+ toBody Proxy = RequestBodyLBS++instance ToBody PlainText ByteString where+ toBody Proxy = RequestBodyBS++instance ToBody PlainText LBS.ByteString where+ toBody Proxy = RequestBodyLBS++instance ToJSON a => ToBody JSON a where+ toBody Proxy = RequestBodyLBS . encode++class Accept c => FromStream c a where+ fromStream :: Proxy c+ -> Stream+ -> ResourceT IO (Either (String, LBS.ByteString) a)++instance FromStream OctetStream Stream where+ fromStream Proxy = pure . Right++instance FromJSON a => FromStream JSON a where+ fromStream Proxy s = do+ bs <- sinkLBS s+ case eitherDecode bs of+ Left e -> pure $! Left (e, bs)+ Right x -> pure $! Right x++class GoogleRequest a where+ type Rs a :: *++ requestClient :: a -> Client (Rs a)++class GoogleClient fn where+ type Fn fn :: *++ buildClient :: Proxy fn -> Request -> Fn fn++-- | Multiple path captures, with @[xs]@ forming @/<x1>/<x2>/<x2>/...@.+data Captures (s :: Symbol) a+ deriving (Typeable)++-- | Form a Google style sub-resource, such as @/<capture>:<mode>@.+data CaptureMode (s :: Symbol) (m :: Symbol) a+ deriving (Typeable)++data MultipartRelated (cs :: [*]) m b+ deriving (Typeable)++instance ( ToBody c m+ , ToBody OctetStream b+ , GoogleClient fn+ ) => GoogleClient (MultipartRelated (c ': cs) m b :> fn) where+ type Fn (MultipartRelated (c ': cs) m b :> fn) = m -> b -> Fn fn++ buildClient Proxy rq m b = buildClient (Proxy :: Proxy fn) $+ setRelated rq+ [ Part (contentType mc) [] (toBody mc m)+ , Part (contentType mb) [] (toBody mb b)+ ]+ where+ mc = Proxy :: Proxy c+ mb = Proxy :: Proxy OctetStream++instance (KnownSymbol s, GoogleClient fn) => GoogleClient (s :> fn) where+ type Fn (s :> fn) = Fn fn++ buildClient Proxy rq = buildClient (Proxy :: Proxy fn) $+ appendPath rq (buildSymbol (Proxy :: Proxy s))++instance (GoogleClient a, GoogleClient b) => GoogleClient (a :<|> b) where+ type Fn (a :<|> b) = Fn a :<|> Fn b++ buildClient Proxy rq =+ buildClient (Proxy :: Proxy a) rq+ :<|> buildClient (Proxy :: Proxy b) rq++instance ( KnownSymbol s+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (Capture s a :> fn) where+ type Fn (Capture s a :> fn) = a -> Fn fn++ buildClient Proxy rq = buildClient (Proxy :: Proxy fn)+ . appendPath rq+ . buildText++instance ( KnownSymbol s+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (Captures s a :> fn) where+ type Fn (Captures s a :> fn) = [a] -> Fn fn++ buildClient Proxy rq = buildClient (Proxy :: Proxy fn)+ . appendPaths rq++instance ( KnownSymbol s+ , KnownSymbol m+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (CaptureMode s m a :> fn) where+ type Fn (CaptureMode s m a :> fn) = a -> Fn fn++ buildClient Proxy rq x = buildClient (Proxy :: Proxy fn)+ . appendPath rq+ $ buildText x <> buildSymbol (Proxy :: Proxy m)++instance ( KnownSymbol s+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (QueryParam s a :> fn) where+ type Fn (QueryParam s a :> fn) = Maybe a -> Fn fn++ buildClient Proxy rq mx = buildClient (Proxy :: Proxy fn) $+ case mx of+ Nothing -> rq+ Just x -> appendQuery rq k v+ where+ k = byteSymbol (Proxy :: Proxy s)+ v = Just (toText x)++instance ( KnownSymbol s+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (QueryParams s a :> fn) where+ type Fn (QueryParams s a :> fn) = [a] -> Fn fn++ buildClient Proxy rq = buildClient (Proxy :: Proxy fn) . foldl' go rq+ where+ go r = appendQuery r k . Just . toText++ k = byteSymbol (Proxy :: Proxy s)++instance ( KnownSymbol s+ , ToText a+ , GoogleClient fn+ ) => GoogleClient (Header s a :> fn) where+ type Fn (Header s a :> fn) = Maybe a -> Fn fn++ buildClient Proxy rq mx = buildClient (Proxy :: Proxy fn) $+ case mx of+ Nothing -> rq+ Just x -> appendHeader rq (CI.mk k) v+ where+ k = byteSymbol (Proxy :: Proxy s)+ v = Just (toText x)++instance ( ToBody c a+ , GoogleClient fn+ ) => GoogleClient (ReqBody (c ': cs) a :> fn) where+ type Fn (ReqBody (c ': cs) a :> fn) = a -> Fn fn++ buildClient Proxy rq = buildClient (Proxy :: Proxy fn)+ . setBody rq (contentType p)+ . toBody p+ where+ p = Proxy :: Proxy c++instance {-# OVERLAPPABLE #-}+ FromStream c a => GoogleClient (Get (c ': cs) a) where+ type Fn (Get (c ': cs) a) = Service -> Client a++ buildClient Proxy = mime (Proxy :: Proxy c) methodGet [200, 203]++instance {-# OVERLAPPING #-}+ GoogleClient (Get (c ': cs) ()) where+ type Fn (Get (c ': cs) ()) = Service -> Client ()++ buildClient Proxy = discard methodGet [204]++instance {-# OVERLAPPABLE #-}+ (FromStream c a, cs' ~ (c ': cs)) => GoogleClient (Post cs' a) where+ type Fn (Post cs' a) = Service -> Client a++ buildClient Proxy = mime (Proxy :: Proxy c) methodPost [200, 201]++instance {-# OVERLAPPING #-}+ GoogleClient (Post cs ()) where+ type Fn (Post cs ()) = Service -> Client ()++ buildClient Proxy = discard methodPost [204]++instance {-# OVERLAPPABLE #-}+ FromStream c a => GoogleClient (Put (c ': cs) a) where+ type Fn (Put (c ': cs) a) = Service -> Client a++ buildClient Proxy = mime (Proxy :: Proxy c) methodPut [200, 201]++instance {-# OVERLAPPING #-}+ GoogleClient (Put (c ': cs) ()) where+ type Fn (Put (c ': cs) ()) = Service -> Client ()++ buildClient Proxy = discard methodPut [204]++instance {-# OVERLAPPABLE #-}+ FromStream c a => GoogleClient (Patch (c ': cs) a) where+ type Fn (Patch (c ': cs) a) = Service -> Client a++ buildClient Proxy = mime (Proxy :: Proxy c) methodPatch [200, 201]++instance {-# OVERLAPPING #-}+ GoogleClient (Patch (c ': cs) ()) where+ type Fn (Patch (c ': cs) ()) = Service -> Client ()++ buildClient Proxy = discard methodPatch [204]++instance {-# OVERLAPPABLE #-}+ FromStream c a => GoogleClient (Delete (c ': cs) a) where+ type Fn (Delete (c ': cs) a) = Service -> Client a++ buildClient Proxy = mime (Proxy :: Proxy c) methodDelete [200, 202]++instance {-# OVERLAPPING #-}+ GoogleClient (Delete (c ': cs) ()) where+ type Fn (Delete (c ': cs) ()) = Service -> Client ()++ buildClient Proxy = discard methodDelete [204]++sinkLBS :: Stream -> ResourceT IO LBS.ByteString+sinkLBS = fmap LBS.fromChunks . ($$+- CL.consume)++buildText :: ToText a => a -> Builder+buildText = Build.fromText . toText++buildSymbol :: forall n proxy. KnownSymbol n => proxy n -> Builder+buildSymbol = Build.fromString . symbolVal++byteSymbol :: forall n proxy. KnownSymbol n => proxy n -> ByteString+byteSymbol = BS8.pack . symbolVal++-- | An integral value representing seconds.+newtype Seconds = Seconds Int+ deriving+ ( Eq+ , Ord+ , Read+ , Show+ , Enum+ , Num+ , Bounded+ , Integral+ , Real+ , Data+ , Typeable+ , Generic+ )++seconds :: Seconds -> Int+seconds (Seconds n)+ | n < 0 = 0+ | otherwise = n++microseconds :: Seconds -> Int+microseconds = (1000000 *) . seconds
+ test/Main.hs view
@@ -0,0 +1,16 @@+-- Module : Main+-- Copyright : (c) 2015 Brendan Hay+-- License : Mozilla Public License, v. 2.0.+-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>+-- Stability : experimental+-- Portability : non-portable (GHC extensions)++module Main (main) where++import Test.Tasty++main :: IO ()+main = defaultMain $+ testGroup "gogol"+ [+ ]