packages feed

webfinger-client (empty) → 0.1.0.0

raw patch · 9 files changed

+556/−0 lines, 9 filesdep +aesondep +basedep +bytestringsetup-changed

Dependencies added: aeson, base, bytestring, data-default-class, hashable, http-client, http-client-tls, http-types, text, unordered-containers, uri-bytestring

Files

+ AUTHORS view
@@ -0,0 +1,1 @@+fr33domlover <fr33domlover@riseup.net>
+ COPYING view
@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+    HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++  i. the right to reproduce, adapt, distribute, perform, display,+     communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+     likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+     subject to the limitations in paragraph 4(a), below;+  v. rights protecting the extraction, dissemination, use and reuse of data+     in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+     European Parliament and of the Council of 11 March 1996 on the legal+     protection of databases, and under any national implementation+     thereof, including any amended or successor version of such+     directive); and+vii. other similar, equivalent or corresponding rights throughout the+     world based on applicable law or treaty, and any national+     implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+    surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+    warranties of any kind concerning the Work, express, implied,+    statutory or otherwise, including without limitation warranties of+    title, merchantability, fitness for a particular purpose, non+    infringement, or the absence of latent or other defects, accuracy, or+    the present or absence of errors, whether or not discoverable, all to+    the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+    that may apply to the Work or any use thereof, including without+    limitation any person's Copyright and Related Rights in the Work.+    Further, Affirmer disclaims responsibility for obtaining any necessary+    consents, permissions or other rights required for any use of the+    Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+    party to this document and has no duty or obligation with respect to+    this CC0 or use of the Work.
+ ChangeLog view
@@ -0,0 +1,17 @@+The changes are recorded by the version control system, Darcs. To see a log+quickly from the terminal, run:++  $ darcs changes --repo http://hub.darcs.net/fr33domlover/webfinger-client++There is also a web interface at <http://hub.darcs.net> which, among other+things, can display the history log.++To see the log in a local clone, first get a copy of the repository if you+haven't yet:++  $ darcs get http://hub.darcs.net/fr33domlover/webfinger-client++Then move into the newly created directory and run darcs:++  $ cd webfinger-client+  $ darcs changes
+ INSTALL view
@@ -0,0 +1,13 @@+Install from Hackage:++    $ cabal install webfinger-client++Install from unpacked release tarball or source repo:++    $ cd webfinger-client+    $ cabal install++Just play with it without installing:++    $ cabal build+    $ cabal repl
+ NEWS.md view
@@ -0,0 +1,23 @@+This file lists the user-visible interesting changes between releases. For a+full list of changes to the source, see the ChangeLog.++++webfinger-client 0.1.0.0 -- 2015-12-12+======================================++General, build and documentation changes:++* (This is the first release, so everything is new)++New APIs, features and enhancements:++* (This is the first release, so everything is a new feature)++Bug fixes:++* (This is just the first release, many bugs haven't been discovered yet)++Dependency changes:++* (This is the first release)
+ README.md view
@@ -0,0 +1,14 @@+See the .cabal file for more info and link to project website the version+control.++The official download location is Hackage:++<http://hackage.haskell.org/package/webfinger-client>++This library is free software, and is committed to software freedom. It is+released to the public domain using the CC0 Public Domain Dedication. For the+boring "legal" details see the file 'COPYING'.++See the file 'INSTALL' for hints on installation. The file 'ChangeLog' explains+how to see the history log of the changes done in the code. 'NEWS' provides a+friendly overview of the changes for each release.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ src/Web/Finger/Client.hs view
@@ -0,0 +1,324 @@+{- This file is part of webfinger-client.+ -+ - Written in 2015 by fr33domlover <fr33domlover@riseup.net>.+ -+ - ♡ Copying is an act of love. Please copy, reuse and share.+ -+ - The author(s) have dedicated all copyright and related and neighboring+ - rights to this software to the public domain worldwide. This software is+ - distributed without any warranty.+ -+ - You should have received a copy of the CC0 Public Domain Dedication along+ - with this software. If not, see+ - <http://creativecommons.org/publicdomain/zero/1.0/>.+ -}++-- For Text and ByteString literals+{-# LANGUAGE OverloadedStrings #-}++-- For generating Hashable instance+{-# LANGUAGE DeriveGeneric #-}++-- To allow Language-hashed maps be FromJSON+{-# LANGUAGE FlexibleInstances #-}++module Web.Finger.Client+    ( Account (..)+    , Resource (..)+    , Auth (..)+    , Query (..)+    , Link (..)+    , Description (..)+    , Result (..)+    , newManager+    , webfinger+    )+where++import Control.Applicative+import Control.Exception+import Data.Aeson hiding (Result, Success)+import Data.Aeson.Types (typeMismatch)+import Data.Default.Class+import Data.Hashable+import Data.Monoid ((<>))+import GHC.Generics (Generic)++import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as BC+import qualified Data.HashMap.Lazy as M+import qualified Data.Text as T+import qualified Network.HTTP.Client as H+import qualified Network.HTTP.Client.TLS as H+import qualified Network.HTTP.Types as HT+import qualified URI.ByteString as U++{- URI ideas++* [/] allow to pass a URI string or a URI as per Network.URI, does http-client not depend on it anyway?+* [x]                  - // -                    URI.ByteString+* [x] allow to pass user and host and treat as an acct URI+* [/] if URI has no scheme and a single @, assume it is user@host and treat as acct+* [x] if URI has no ':' but does have '@', treat as an acct URI+* [x] in Go it takes absolute URL or email - should I require that a URI passed be+  absolute? what does it mean not to be absolute? DONE assume it's absolute+* [x] make acct URIs get parsed, i.e. hostname extracted correctly++ - Other Nodes++* [ ] Add a list of properties and link relations, the Python module has one...+* [x] Add an HTTP Accept header containing the JRD MIME type, the python module+  does it. But first read in the RFC to make sure it's ok+-}++-- | A given user at a given host. For example, /john@example.org/ means the+-- user is /john/ and the host is /example.org/.+data Account = Account+    { acctUser :: B.ByteString+    , acctHost :: B.ByteString+    }++-- | A web resource about which you'd like to make a query.+data Resource+    = ResAccount Account+    | ResUri U.URI+    | ResUriStr B.ByteString++-- | HTTP user authentication details.+data Auth = Auth+    { authUser     :: B.ByteString+    , authPassword :: B.ByteString+    }++-- | A WebFinger query, for which the client can get a response.+--+-- In the 'Default' instance, all fields are empty/null and there are no+-- auth details. Therefore you must at least (but it is also enough to) specify+-- the 'qryTarget' URI.+data Query = Query+    { -- | A URI representing an entity about which you would like to get+      -- information.+      qryTarget   :: Resource+      -- | A list of link relations by which to filter the link list in the+      -- returned description. If you'd like to receive /all/ the links, leave+      -- this list empty.+    , qryLinkRels :: [B.ByteString]+      -- | You can explicitly specify a host (e.g. @www.example.org@) here, to+      -- which the WebFinger query will be sent. If you don't specify a host+      -- here, it will be extracted from the 'qryTarget' field (if it has a+      -- host part). Therefore this field is useful in special cases where the+      -- WebFinger server isn't the one referred by the target URI, or the URI+      -- doesn't have a host.+    , qryHost     :: Maybe B.ByteString+      -- | HTTP authentication details. If the WebFinger server requires a+      -- username and password to access it, specify them here. For publicly+      -- available WebFinger servers, pass 'Nothing'.+    , qryAuth     :: Maybe Auth+    }++instance Default Query where+    def = Query+        { qryTarget   = ResUriStr B.empty+        , qryLinkRels = []+        , qryHost     = Nothing+        , qryAuth     = Nothing+        }++-- | Natural Language code. Used to express in which language a text string is+-- written.+data Language+    -- | A specific language specified using a code, e.g. @en-us@.+    = LanguageCode T.Text+    -- | No specific language. However it doesn't mean that nothing is+    -- specified. It means that "language undefined" is explicity specified.+    | LanguageUndefined+    deriving (Eq, Generic, Show)++instance Hashable Language++toLang :: T.Text -> Language+toLang t =+    if t == "und"+        then LanguageUndefined+        else LanguageCode t++instance FromJSON (M.HashMap Language T.Text) where+    parseJSON v = M.fromList . map f . M.toList <$> parseJSON v+        where+        f (l, t) = (toLang l, t)++-- | Represents a link from the target resource to some other web resource.+-- This is more than a simple webpage link: It also has a relation type (i.e.+-- what is the relation between the target resource and the referred resource)+-- and additional properties.+data Link = Link+    { -- | The link relation type. Determines the relation between the target+      -- resource (about which the query was made) and the resource referred by+      -- the link. For example, if the target resource is a user and the linked+      -- resource is the user's avatar image, the link relation may be+      -- /avatar/.+      --+      -- A link relation may be a URI or one of the registered relation type+      -- names.+      lnkRelation   :: T.Text --TODO: URI or registered relation type. Maybe parse it and give more typed info?+      -- | The MIME type to be expected of the content behind the link URI. For+      -- example, if the link refers to a user's avatar image, the MIME type+      -- may be @image/png@ (i.e. an image file in PNG format).+    , lnkMediaType  :: Maybe T.Text+      -- | The link address itself. It is optional, because there may be cases+      -- in which all the information about the link is provided by the+      -- properties (the 'lnkProperties' field). For example, if the link is a+      -- user's avatar image, the address may be+      -- @https://example.org/users/john/avatar.png@.+    , lnkAddress    :: Maybe T.Text+      -- | Optional title(s) for the link, possibly in various languages.+    , lnkTitles     :: M.HashMap Language T.Text+      -- | Additional properties the link may have. Maps property names, which+      -- are URIs, to string values.+    , lnkProperties :: M.HashMap T.Text (Maybe T.Text) --TODO use IANA database to parse known values?+    }+    deriving (Show)++instance FromJSON Link where+    parseJSON (Object o) =+        Link <$>+        o .:  "rel"                    <*>+        o .:? "type"                   <*>+        o .:? "href"                   <*>+        o .:? "titles"     .!= M.empty <*>+        o .:? "properties" .!= M.empty+    parseJSON v          = typeMismatch "Link" v++-- | Information about the target resource, returned when a query succeeds.+data Description = Description+    { -- | A URI representing the resource being described. This is the same+      -- resource specified in the query, but the URI may slightly differ (e.g.+      -- appear in canonical form).+      desSubject    :: Maybe T.Text+      -- | List of URIs which identify the same resource as the 'desSubject'+      -- URI.+    , desAliases    :: [T.Text]+      -- | Additional information about the subject. Maps property names, which+      -- are URIs, to string values.+    , desProperties :: M.HashMap T.Text (Maybe T.Text) --TODO use IANA database to parse known values?+      -- | Links of various relation types from the subject resource to other+      -- resources represented by URIs.+    , desLinks      :: [Link]+    }+    deriving (Show)++instance FromJSON Description where+    parseJSON (Object o) =+        Description <$>+        o .:? "subject"                <*>+        o .:? "aliases"    .!= []      <*>+        o .:? "properties" .!= M.empty <*>+        o .:? "links"      .!= []+    parseJSON v          = typeMismatch "Description" v++-- | Response to the query.+data Result+    -- | The WebFinger server returned a valid resource description.+    = Success Description+    -- | The server returned a description but we failed to parse it.+    | InvalidDesc String+    -- | The server doesn't have information about the query target.+    | NoInfoFound+    -- | The server says the target URI is either absent from the HTTP request,+    -- or is malformed.+    | TargetMalformed+    -- | We (client side) couldn't determine the host to which to send the+    -- query. This usually means no host was explicitly specified, and the+    -- attempt to extract the host from the query target resource failed.+    | HostNotDetected String+    deriving (Show)++-- | A connection manager, see "Network.HTTP.Client" for details. This function+-- creates a manager which can handle HTTPS, which is /required/ for WebFinger+-- and regular HTTP /isn't allowed/. If you'd like to make queries in other+-- ways which require more support (e.g. perhaps Tor), create your own manager+-- instead using one of the @http-client-*@ packages.+newManager :: IO H.Manager+newManager = H.newManager H.tlsManagerSettings++-- | Try to get the host from a resource URI.+getHost :: U.URI -> Either String B.ByteString+getHost uri =+    case U.uriAuthority uri of+        Nothing -> Left "Resource URI has no authority part"+        Just au -> Right $ U.hostBS $ U.authorityHost au++-- | Determine URI and host from resource. If no host is found, return a+-- message instead which explains why.+parseResource :: Resource -> (B.ByteString, Either String B.ByteString)+parseResource (ResAccount a) =+    ( "acct:" <> acctUser a <> "@" <> acctHost a -- escape user! do i need to espcape host?+    , Right $ acctHost a                         -- do i need to escape host? does http-client do it anyway?+    )+parseResource (ResUri u) =+    ( U.serializeURI' u+    , getHost u+    )+parseResource (ResUriStr s) =+    let prefix = "acct:"+        s' = if ':' `BC.notElem` s && '@' `BC.elem` s+                then prefix <> s+                else s+        rest = B.drop (B.length prefix) s'+        needSlash = not (B.null rest) && BC.head rest /= '/'+        s'' = if prefix `B.isPrefixOf` s' && needSlash+                then prefix <> "//" <> rest+                else s'+    in  ( s'+        , case U.parseURI U.laxURIParserOptions s'' of+            Left e    -> Left $ show e+            Right uri -> getHost uri+        )++-- | Send a WebFinger query over HTTPS to a WebFinger server, and get a+-- response.+--+-- Some HTTP exceptions which represent common query results are caught and+-- used to determine the return value, i.e. the 'Result'. All other HTTP+-- exceptions aren't handled.+webfinger :: H.Manager+          -- ^ Connection manager. See 'newManager'.+          -> Query+          -- ^ A query expressing what you'd like to know, and whom to ask.+          -> IO Result+webfinger manager q =+    let (uri, eith) = parseResource $ qryTarget q+        eith' = maybe eith Right $ qryHost q+    in  case eith' of+            Left err -> return $ HostNotDetected err+            Right host -> do+                let req = def+                        { H.method         = HT.methodGet+                        , H.secure         = True+                        , H.host           = host+                        , H.port           = 443+                        , H.path           = "/.well-known/webfinger" --TODO maybe make a Haskell package for well-known URIs?+                        , H.requestHeaders =+                            [(HT.hAccept, "application/jrd+json")]+                        }+                    req' = case qryAuth q of+                            Nothing               -> req+                            Just (Auth user pass) -> H.applyBasicAuth user pass req+                    res = ("resource", Just uri)+                    rels = map ((,) "rel" . Just) $ qryLinkRels q+                    params = res : rels+                    req'' = H.setQueryString params req'+                eresp <- try (H.httpLbs req'' manager)+                case eresp of+                    Left e ->+                        case e :: H.HttpException of+                            H.StatusCodeException s _ _+                                | s == HT.badRequest400 ->+                                    return TargetMalformed+                                | s == HT.notFound404   -> return NoInfoFound+                                | otherwise             -> throwIO e+                            _ -> throwIO e+                    Right resp ->+                        return $ case eitherDecode $ H.responseBody resp of+                            Left err   -> InvalidDesc err+                            Right desc -> Success desc
+ webfinger-client.cabal view
@@ -0,0 +1,41 @@+name:                webfinger-client+version:             0.1.0.0+synopsis:            WebFinger client library+description:+  This is a client library for querying a+  <https://webfinger.net WebFinger>+  resource and parsing the response.+homepage:            http://hub.darcs.net/fr33domlover/webfinger-client+bug-reports:         http://hub.darcs.net/fr33domlover/webfinger-client/issues+license:             PublicDomain+license-file:        COPYING+author:              fr33domlover+maintainer:          fr33domlover@riseup.net+copyright:           ♡ Copying is an act of love. Please copy, reuse and share.+category:            Network, Web+build-type:          Simple+extra-source-files:  AUTHORS ChangeLog COPYING INSTALL NEWS.md README.md+cabal-version:       >=1.10++source-repository head+  type:                darcs+  location:            http://hub.darcs.net/fr33domlover/webfinger-client++library+  exposed-modules:     Web.Finger.Client+  -- other-modules:       +  -- other-extensions:    +  build-depends:       aeson                >=0.7+                     , base                 >=4.7 && <5+                     , bytestring+                     , data-default-class+                     , hashable+                     , http-client          >=0.3.6+                     , http-client-tls      >=0.2.2+                     , http-types+                     , text+                     , unordered-containers >=0.2.5+                     , uri-bytestring       >=0.1.7+  hs-source-dirs:      src+  default-language:    Haskell2010+  ghc-options:         -Wall