packages feed

sauron (empty) → 0.0.0.0

raw patch · 18 files changed

+1480/−0 lines, 18 filesdep +aesondep +aeson-prettydep +base

Dependencies added: aeson, aeson-pretty, base, hedgehog, hspec, hspec-hedgehog, http-client, http-client-tls, iris, optparse-applicative, relude, sauron, servant, servant-client, servant-client-core, time

Files

+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Changelog++`sauron` uses [PVP Versioning][1].+The changelog is available [on GitHub][2].++## 0.0.0.0++* Initially created.++[1]: https://pvp.haskell.org+[2]: https://github.com/chshersh/sauron/releases
+ LICENSE view
@@ -0,0 +1,373 @@+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.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++  This Source Code Form is "Incompatible With Secondary Licenses", as+  defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,42 @@+# sauron++[![GitHub CI](https://github.com/chshersh/sauron/workflows/CI/badge.svg)](https://github.com/chshersh/sauron/actions)+[![Hackage](https://img.shields.io/hackage/v/sauron.svg?logo=haskell)](https://hackage.haskell.org/package/sauron)+[![MPL-2.0 license](https://img.shields.io/badge/license-MPL--2.0-blue.svg)](LICENSE)++👁 `sauron` is a CLI tool that fetches info from Twitter and analyses it.++> 🌈 `sauron` is a demo project implemented using [Iris][iris] — a Haskell CLI+> framework.++[iris]: https://github.com/chshersh/iris++## Features++Features currently supported by `sauron`:++* Get top tweets of a Twitter account (limited by only 3200 recent tweets)+* Save intermediate results to a file (to avoid hitting Twitter API limit too early)+* Read cached results from a file++## How to use?++1. [Generate your own Twitter token][token] and export it as the+   `$TWITTER_TOKEN` variable.++2. Clone the project.++    ```shell+    git clone git@github.com:chshersh/sauron.git+    cd sauron+    ```++3. Build and run the tool+    +    > ⚠️ Requires GHC 9.2++    ```shell+    cabal run sauron -- top @<twitter-handle> --max=20 --to-file=path/to/save/results.json+    ```++[token]: https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api
+ app/Main.hs view
@@ -0,0 +1,1 @@+module Main (main) where import Sauron (main)
+ sauron.cabal view
@@ -0,0 +1,134 @@+cabal-version:       3.0+name:                sauron+version:             0.0.0.0+synopsis:            The eye that watches everything you did on Twitter+description:+    The eye that watches everything you did on Twitter.+    See [README.md](https://github.com/chshersh/sauron#sauron) for more details.+homepage:            https://github.com/chshersh/sauron+bug-reports:         https://github.com/chshersh/sauron/issues+license:             MPL-2.0+license-file:        LICENSE+author:              Dmitrii Kovanikov+maintainer:          Dmitrii Kovanikov <kovanikov@gmail.com>+copyright:           2022 Dmitrii Kovanikov+build-type:          Simple+extra-doc-files:     README.md+                     CHANGELOG.md+tested-with:         GHC == 9.2.4++source-repository head+  type:                git+  location:            https://github.com/chshersh/sauron.git++common common-options+  build-depends:       base   ^>= 4.16+                     , relude ^>= 1.1++  mixins:              base hiding (Prelude)+                     , relude (Relude as Prelude)+                     , relude++  ghc-options:         -Wall+                       -Wcompat+                       -Widentities+                       -Wincomplete-uni-patterns+                       -Wincomplete-record-updates+                       -Wredundant-constraints+                       -Wnoncanonical-monad-instances+  if impl(ghc >= 8.2)+    ghc-options:       -fhide-source-paths+  if impl(ghc >= 8.4)+    ghc-options:       -Wmissing-export-lists+                       -Wpartial-fields+  if impl(ghc >= 8.8)+    ghc-options:       -Wmissing-deriving-strategies+                       -fwrite-ide-info+                       -hiedir=.hie+  if impl(ghc >= 9.0)+    ghc-options:       -Winvalid-haddock+  if impl(ghc >= 9.2)+    ghc-options:       -Wredundant-bang-patterns+                       -Woperator-whitespace++  default-language:    Haskell2010+  default-extensions:  ConstraintKinds+                       DeriveGeneric+                       DerivingStrategies+                       GeneralizedNewtypeDeriving+                       InstanceSigs+                       KindSignatures+                       LambdaCase+                       NumericUnderscores+                       OverloadedStrings+                       RecordWildCards+                       ScopedTypeVariables+                       StandaloneDeriving+                       StrictData+                       TupleSections+                       TypeApplications+                       ViewPatterns++library+  import:              common-options+  hs-source-dirs:      src++  autogen-modules:     Paths_sauron+  other-modules:       Paths_sauron++  exposed-modules:+    Sauron+      Sauron.App+      Sauron.Cli+      Sauron.Top+        Sauron.Top.Client+        Sauron.Top.Json+        Sauron.Top.User+        Sauron.Top.Tweet++  build-depends:+    , aeson                ^>= 2.1+    , aeson-pretty         ^>= 0.8+    , http-client          ^>= 0.7+    , http-client-tls      ^>= 0.3+    , iris                 ^>= 0.0+    , optparse-applicative ^>= 0.17+    , servant              ^>= 0.19+    , servant-client       ^>= 0.19+    , servant-client-core  ^>= 0.19+    , time                 ^>= 1.11++executable sauron+  import:              common-options+  hs-source-dirs:      app+  main-is:             Main.hs+  build-depends:       sauron+  ghc-options:         -threaded+                       -rtsopts+                       -with-rtsopts=-N++test-suite sauron-test+  import:              common-options+  type:                exitcode-stdio-1.0+  hs-source-dirs:      test+  main-is:             Spec.hs++  other-modules:+    Test.Sauron+      Test.Sauron.Top+        Test.Sauron.Top.Client+        Test.Sauron.Top.Tweet++  build-depends:+    , sauron+    , aeson+    , hedgehog       ^>= 1.2+    , hspec           >= 2.9.7 && < 2.11+    , hspec-hedgehog ^>= 0.0+    , servant+    , servant-client-core+    , time++  ghc-options:         -threaded+                       -rtsopts+                       -with-rtsopts=-N
+ src/Sauron.hs view
@@ -0,0 +1,25 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++The eye that watches everything you did on Twitter+-}++module Sauron+    ( main+    ) where++import Sauron.App (App, runApp)+import Sauron.Cli (Cmd (..))+import Sauron.Top (runTop)++import qualified Iris+++main :: IO ()+main = runApp app++app :: App ()+app = Iris.asksCliEnv Iris.cliEnvCmd >>= \case+    Top topArgs -> runTop topArgs
+ src/Sauron/App.hs view
@@ -0,0 +1,85 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++Main application monad and its environment to run the app.+-}++module Sauron.App+    ( App (..)+    , Env (..)+    , runApp+    ) where++import Control.Exception (throwIO)+import Network.HTTP.Client (Manager)+import Network.HTTP.Client.TLS (newTlsManager)+import System.IO.Error (userError)++import Sauron.Cli (Cmd, cmdP)++import qualified Iris+import qualified Paths_sauron as Autogen+++-- | Sauron CLI application monad.+newtype App a = App+    { unApp :: Iris.CliApp Cmd Env a+    } deriving newtype+        ( Functor+        , Applicative+        , Monad+        , MonadIO+        , MonadReader (Iris.CliEnv Cmd Env)+        )++-- | Sauron CLI application environment.+data Env = Env+    { envManager :: Manager+    , envToken   :: Text+    }++-- | Sauron application settings+appSettings :: Env -> Iris.CliEnvSettings Cmd Env+appSettings env = Iris.defaultCliEnvSettings+    { Iris.cliEnvSettingsCmdParser = cmdP++    , Iris.cliEnvSettingsAppEnv = env++    , Iris.cliEnvSettingsHeaderDesc =+        "sauron - an evil eye that watches your Twitter"++    , Iris.cliEnvSettingsProgDesc =+        "A CLI tool to get insights from Twitter (top tweets, etc.)"++    , Iris.cliEnvSettingsVersionSettings =+        Just (Iris.defaultVersionSettings Autogen.version)+            { Iris.versionSettingsMkDesc = \v -> "Sauron v" <> v+            }++    , Iris.cliEnvSettingsRequiredTools = []+    }++-- | Create application environment.+mkEnv :: IO Env+mkEnv = do+    envManager <- newTlsManager++    envToken <- lookupEnv "TWITTER_TOKEN" >>= \case+        Just token -> pure $ toText token+        Nothing -> throwIO $ userError "The environment variable 'TWITTER_TOKEN' not found"++    pure Env{..}++{- | Run the Sauron CLI application monad by:++  1. Creating application environment.+  2. Creating application settings.+  3. Running the monadic action.+-}+runApp :: App a -> IO a+runApp app = do+    env <- mkEnv+    let settings = appSettings env+    Iris.runCliApp settings $ unApp app
+ src/Sauron/Cli.hs view
@@ -0,0 +1,77 @@+{-# LANGUAGE ApplicativeDo #-}++{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++Command-line arguments parsing+-}++module Sauron.Cli+    ( Cmd (..)+    , cmdP++      -- * sauron top+    , TopArgs (..)+    , CacheMode (..)+    ) where++import Options.Applicative as Opt+++data Cmd+    = Top TopArgs++data TopArgs = TopArgs+    { topArgsUsername  :: Text  -- ^ Twitter username handle+    , topArgsMax       :: Int   -- ^ Max top tweets to extract+    , topArgsCacheMode :: CacheMode  -- ^ Store to file or read from file+    }++data CacheMode+    = ToFile FilePath+    | FromFile FilePath++-- | All possible commands.+cmdP :: Opt.Parser Cmd+cmdP = Opt.subparser $ mconcat+    [ Opt.command "top"+          $ Opt.info (Opt.helper <*> topP)+          $ Opt.progDesc "Top tweets of a user"+    ]++topP :: Opt.Parser Cmd+topP = do+    topArgsUsername <- Opt.strArgument $ mconcat+        [ Opt.metavar "TWITTER_NAME"+        , Opt.help "Twitter user handle: @my-name or my-name"+        ]++    topArgsMax <- Opt.option Opt.auto $ mconcat+        [ Opt.long "max"+        , Opt.short 'm'+        , Opt.metavar "POSITIVE_NUMBER"+        , Opt.help "Max number of tweets to output in the terminal"+        ]++    topArgsCacheMode <- cacheModeP++    pure $ Top TopArgs{..}++cacheModeP :: Opt.Parser CacheMode+cacheModeP = (ToFile <$> toFileP) <|> (FromFile <$> fromFileP)+  where+    toFileP :: Opt.Parser FilePath+    toFileP = Opt.strOption $ mconcat+        [ Opt.long "to-file"+        , Opt.metavar "FILE_PATH"+        , Opt.help "Save the Twitter output to a file (to avoid hitting the fetch limit)"+        ]++    fromFileP :: Opt.Parser FilePath+    fromFileP = Opt.strOption $ mconcat+        [ Opt.long "from-file"+        , Opt.metavar "FILE_PATH"+        , Opt.help "Read data from a previously saved file with the '--to-file' option"+        ]
+ src/Sauron/Top.hs view
@@ -0,0 +1,161 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++The 'sauron top' command.++-}++module Sauron.Top+    ( runTop+    ) where++import Data.Aeson.Encode.Pretty (encodePretty)+import Data.List (minimum)+import Data.Time.Clock (UTCTime, getCurrentTime)+import Servant.Client.Core (ClientError)++import Sauron.App (App)+import Sauron.Cli (CacheMode (..), TopArgs (..))+import Sauron.Top.Client (getTweets, getUserByUsername)+import Sauron.Top.Json (Data (..), Meta (..), Page (..))+import Sauron.Top.Tweet (Tweet (..), showTime, subtractSecond, topTweets)+import Sauron.Top.User (User (..), UserId (..), mkUsername)++import qualified Data.Aeson as Aeson+++runTop :: TopArgs -> App ()+runTop TopArgs{..} = do+    let username = mkUsername topArgsUsername+    User{..} <- getUserByUsername username++    putTextLn $ "[info] User id of " <> topArgsUsername <> " is: " <> unUserId userId+    putTextLn $ "[info] Total number of tweets: " <> show userTweetCount++    tweets <- case topArgsCacheMode of+        ToFile toFile     -> timelineLoop userId toFile+        FromFile fromFile -> parseCachedTweets fromFile++    putTextLn $ topTweets topArgsMax username tweets++-- | Parse already saved tweets in the file+parseCachedTweets :: FilePath -> App [Tweet]+parseCachedTweets path =+    liftIO (Aeson.eitherDecodeFileStrict @[Tweet] path) >>= \case+        Right tweets -> pure tweets+        Left err -> do+            putStrLn $ "Error parsing " <> path <> ": " <> err+            exitFailure++{- | A data type representing the current state of fetching the+Twitter timeline+-}+data TimelineState+    -- | Fetching the timeline for the first time+    = Start++    -- | An error occurred; dump the current tweets to the file and exit with error+    | Error TimelineError [Tweet]++    -- | We haven't exhausted our queries+    | NextPage+        UTCTime -- ^ Timestamp used to fetch the previous page(s)+        Text    -- ^ Pagination token+        [Tweet]++    -- | We've reached the 3200 limit. Now change the end date.+    | NextDate+        UTCTime  -- ^ Time of the last tweet minus one second+        [Tweet]++    -- | Successfully fetched the entire timeline!+    | Finish [Tweet]++data TimelineError+    = InvalidRequest ClientError++displayTimelineError :: TimelineError -> Text+displayTimelineError = \case+    InvalidRequest err -> "[InvalidRequest] " <> show err++timelineLoop :: UserId -> FilePath -> App [Tweet]+timelineLoop userId savePath = loop Start+  where+    loop :: TimelineState -> App [Tweet]+    loop Start = do+        now <- liftIO getCurrentTime++        let endTime = showTime now+        putStrLn $ "[debug] Current time: " <> endTime++        getTweets userId endTime Nothing >>= \case+            Left err -> loop $ Error (InvalidRequest err) []+            Right Page{..} -> do+                let tweets = unData pageData+                case metaNextToken pageMeta of+                    Nothing ->+                        loop $ Finish $ unData pageData+                    Just nextToken ->+                        loop $ NextPage now nextToken tweets++    loop (Error err tweets) = do+        putTextLn $ "[error] " <> displayTimelineError err+        saveTweets savePath tweets+        exitFailure++    loop (Finish tweets) = do+        saveTweets savePath tweets+        pure tweets++    loop (NextPage time currentToken tweets) = do+        debugTweets tweets++        let endTime = showTime time+        getTweets userId endTime (Just currentToken) >>= \case+            Left err -> loop $ Error (InvalidRequest err) tweets+            Right Page{..} -> do+                let newTweets = unData pageData+                case metaNextToken pageMeta of+                    -- We fetched all pages+                    Nothing -> do+                        let earliestTime = minimum $ map tweetCreatedAt tweets+                        let newEndTime = subtractSecond earliestTime+                        loop $ NextDate newEndTime (newTweets ++ tweets)++                    -- More pages to fetch+                    Just nextToken ->+                        loop $ NextPage time nextToken (newTweets ++ tweets)++    loop (NextDate time tweets) = do+        putTextLn $ "[debug] Next date: " <> show time+        debugTweets tweets++        let endTime = showTime time+        getTweets userId endTime Nothing >>= \case+            Left err -> loop $ Error (InvalidRequest err) tweets+            Right Page{..} -> do+                let newTweets = unData pageData+                case metaNextToken pageMeta of+                    -- We fetched all the tweets+                    Nothing ->+                        loop $ Finish (newTweets ++ tweets)++                    -- More pages to fetch+                    Just nextToken ->+                        loop $ NextPage time nextToken (newTweets ++ tweets)+++debugTweets :: [Tweet] -> App ()+debugTweets tweets = do+    let len = length tweets+    putTextLn $ "[debug] Fetched total tweets: " <> show len++saveTweets :: FilePath -> [Tweet] -> App ()+saveTweets savePath tweets = do+    let tweetsCount = length tweets+    putTextLn $ "[info] Saving " <> show tweetsCount <> " tweets to: " <> toText savePath++    let json = encodePretty tweets+    writeFileLBS savePath json
+ src/Sauron/Top/Client.hs view
@@ -0,0 +1,142 @@+{-# LANGUAGE DataKinds     #-}+{-# LANGUAGE TypeOperators #-}++{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++Functions for querying Twitter API.++__Auth:__++@+Authorization: Bearer $TWITTER_TOKEN+@+-}++module Sauron.Top.Client+    ( -- * User+      getUserByUsername+    , getTweets++      -- * Tweets+    , GetTweets++      -- * Internals+    , twitterBaseUrl+    ) where++import Control.Exception (throwIO)+import Servant.API (Capture, Get, Header', JSON, QueryParam, Required, Strict, (:>))+import Servant.Client (BaseUrl (..), ClientM, Scheme (Https), client, mkClientEnv, runClientM)+import Servant.Client.Core (ClientError)++import Sauron.App (App, Env (..))+import Sauron.Top.Json (Data (..), Page (..))+import Sauron.Top.Tweet (Tweet)+import Sauron.Top.User (User, UserId, Username (..))++import qualified Iris+++-- | URL for acessing Twitter API v2+twitterBaseUrl :: BaseUrl+twitterBaseUrl = BaseUrl+    { baseUrlScheme = Https+    , baseUrlHost   = "api.twitter.com"+    , baseUrlPort   = 443+    , baseUrlPath   = "/2"+    }++type RequiredHeader = Header' '[Required, Strict]++{- | API type for the following URL:++@+https://api.twitter.com/2/users/by/username/:username+@+-}+type GetUserByUsername+    =  RequiredHeader "Authorization" Text+    :> "users"+    :> "by"+    :> "username"+    :> Capture "username" Username+    :> QueryParam "user.fields" Text+    :> Get '[JSON] (Data User)++getUserByUsernameClient :: Text -> Username -> Maybe Text -> ClientM (Data User)+getUserByUsernameClient = client $ Proxy @GetUserByUsername++getUserByUsername :: Username -> App User+getUserByUsername username = do+    manager <- Iris.asksAppEnv envManager+    let clientEnv = mkClientEnv manager twitterBaseUrl++    token <- Iris.asksAppEnv envToken+    let auth = "Bearer " <> token++    let request = getUserByUsernameClient auth username (Just "public_metrics")++    res <- liftIO $ runClientM request clientEnv+    case res of+      Right (Data userId) -> pure userId+      Left err -> do+          putStrLn $ "Error getting user ID: " ++ show err+          liftIO $ throwIO err++{- | API type for the following URL:++@+https://api.twitter.com/2/users/2164623379/tweets?max_results=5&exclude=retweets&tweet.fields=created_at,public_metrics&end_time=2022-09-01T13%3A52%3A14Z+@+-}+type GetTweets+    =  RequiredHeader "Authorization" Text+    :> "users"+    :> Capture "id" UserId+    :> "tweets"+    :> QueryParam "max_results" Int+    :> QueryParam "exclude" Text+    :> QueryParam "tweet.fields" Text+    :> QueryParam "end_time" String+    :> QueryParam "pagination_token" Text+    :> Get '[JSON] (Page [Tweet])++getTweetsClient+    :: Text+    -> UserId+    -> Maybe Int+    -> Maybe Text+    -> Maybe Text+    -> Maybe String+    -> Maybe Text+    -> ClientM (Page [Tweet])+getTweetsClient = client $ Proxy @GetTweets++getTweetsClientRequest :: Text -> UserId -> String -> Maybe Text -> ClientM (Page [Tweet])+getTweetsClientRequest authToken userId endTime paginationToken = getTweetsClient+    authToken+    userId+    (Just 100)  -- Return 100 requests (max allowed)+    (Just "retweets")  -- exclude retweets & replies+    (Just "created_at,public_metrics")  -- extra fields to return+    (Just endTime)+    paginationToken++getTweets :: UserId -> String -> Maybe Text -> App (Either ClientError (Page [Tweet]))+getTweets userId endTime paginationToken = do+    manager <- Iris.asksAppEnv envManager+    let clientEnv = mkClientEnv manager twitterBaseUrl++    token <- Iris.asksAppEnv envToken+    let auth = "Bearer " <> token++    let request = getTweetsClientRequest+            auth+            userId+            endTime+            paginationToken++    liftIO $ runClientM request clientEnv
+ src/Sauron/Top/Json.hs view
@@ -0,0 +1,77 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++JSON parsing helpers and common utilities+-}++module Sauron.Top.Json+    ( Data (..)+    , Meta (..)+    , Page (..)+    ) where++import Data.Aeson (FromJSON (..), Result (..), Value (Object), fromJSON, withObject, (.:), (.:?))+import Relude.Extra.Type (typeName)+++{- | Newtype wrapper for parsing JSON data inside the "data"+field. For example:++@+{ "data": ...+@+-}+newtype Data a = Data+    { unData :: a+    } deriving stock (Show)+      deriving newtype (Eq)++instance (FromJSON a, Typeable a) => FromJSON (Data a) where+    parseJSON = withObject ("Data " <> type_) $ \o -> do+        data_ <- o .: "data"+        pure $ Data data_+      where+        type_ :: String+        type_ = toString $ typeName @a++{- | Parses relevant parts of the "meta" object++@+  "meta": {+    "result_count": 5,+    "newest_id": "1565283709275803650",+    "oldest_id": "1565246649185849344",+    "next_token": "7140dibdnow9c7btw4232rrxi2153ga6h81clvyarutkk"+  }+@+-}+data Meta = Meta+    { metaResultCount :: Int+    , metaNextToken   :: Maybe Text+    } deriving stock (Show, Eq)++instance FromJSON Meta where+    parseJSON = withObject "Meta" $ \o -> do+        metaResultCount <- o .:  "result_count"+        metaNextToken   <- o .:? "next_token"+        pure Meta{..}++{- | A result of a pagination request+-}+data Page a = Page+    { pageData :: Data a+    , pageMeta :: Meta+    } deriving stock (Show, Eq)++instance (FromJSON a, Typeable a) => FromJSON (Page a) where+    parseJSON = withObject ("Page " <> type_) $ \o -> do+        pageData <- case fromJSON @(Data a) (Object o) of+            Error err -> fail err+            Success a -> pure a+        pageMeta <- o .: "meta"+        pure Page{..}+      where+        type_ :: String+        type_ = toString $ typeName @a
+ src/Sauron/Top/Tweet.hs view
@@ -0,0 +1,118 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++The 'Tweet' type in the JSON API response.+-}++module Sauron.Top.Tweet+    ( Tweet (..)+    , topTweets++      -- * Internals+    , parseTime+    , showTime+    , subtractSecond+    ) where++import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, (.:), (.=))+import Data.Time.Clock (UTCTime, addUTCTime)+import Data.Time.Format (defaultTimeLocale, formatTime)+import Data.Time.Format.ISO8601 (formatParseM, iso8601Format)++import Sauron.Top.User (Username (..))++import qualified Data.Text as Text+++data Tweet = Tweet+    { tweetId        :: Text+    , tweetText      :: Text+    , tweetLikeCount :: Int+    , tweetCreatedAt :: UTCTime+    } deriving stock (Show, Eq)++parseTime :: String -> Maybe UTCTime+parseTime = formatParseM iso8601Format++showTime :: UTCTime -> String+showTime = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ"++subtractSecond :: UTCTime -> UTCTime+subtractSecond = addUTCTime (-1)++{- | Parses Tweet from the following JSON object:++@+{+  "public_metrics": {+    "retweet_count": 0,+    "reply_count": 1,+    "like_count": 1,+    "quote_count": 0+  },+  "text": "🔮 I still had some theories about the space leak...",+  "created_at": "2022-09-01T07:54:18.000Z",+  "id": "1565246655103995905"+}+@+-}+instance FromJSON Tweet where+    parseJSON = withObject "Tweet" $ \o -> do+        tweetId   <- o .: "id"+        tweetText <- o .: "text"++        createdAt <- o .: "created_at"+        tweetCreatedAt <- case parseTime createdAt of+            Nothing   -> fail $ "Error parsing time: " <> createdAt+            Just time -> pure time++        publicMetrics <- o .: "public_metrics"+        tweetLikeCount <- publicMetrics .: "like_count"++        pure Tweet{..}++instance ToJSON Tweet where+    toJSON Tweet{..} = object+        [ "id"         .= tweetId+        , "created_at" .= showTime tweetCreatedAt+        , "text"       .= tweetText+        , "public_metrics" .= object+            [ "like_count" .= tweetLikeCount+            ]+        ]++-- | Extract top N tweets and pretty format them.+topTweets :: Int -> Username -> [Tweet] -> Text+topTweets maxTweets username+    = formatTweets username+    . take maxTweets+    . sortWith (Down . tweetLikeCount)++formatTweets :: Username -> [Tweet] -> Text+formatTweets _ [] = "No tweets found"+formatTweets username tweets = foldMap formatTweet tweets+  where+    formatTweet :: Tweet -> Text+    formatTweet Tweet{..} = unlines+        [ "URL          : " <> tweetUrl+        , "Tweeted at   : " <> toText (showTime tweetCreatedAt)+        , "Likes        : " <> show tweetLikeCount+        , "Awesome text :"+        , chunkedText+        ]+      where+        tweetUrl :: Text+        tweetUrl = mconcat+            [ "https://twitter.com/"+            , unUsername username+            , "/status/"+            , tweetId+            ]++        chunkedText :: Text+        chunkedText+            = unlines+            $ map ("    " <>)+            $ Text.chunksOf 60 tweetText
+ src/Sauron/Top/User.hs view
@@ -0,0 +1,75 @@+{- |+Copyright: (c) 2022 Dmitrii Kovanikov+SPDX-License-Identifier: MPL-2.0+Maintainer: Dmitrii Kovanikov <kovanikov@gmail.com>++User-related types in the 'sauron top' command.+-}++module Sauron.Top.User+    ( -- * Core types+      User (..)+    , UserId (..)+    , Username (..)+    , mkUsername+    ) where++import Data.Aeson (FromJSON (..), withObject, (.:))+import Servant.API (ToHttpApiData)++import qualified Data.Text as Text+++-- | A Twitter User ID like: "2244994945"+newtype UserId = UserId+    { unUserId :: Text+    } deriving newtype (FromJSON, ToHttpApiData)++{- | Stores Twitter Username handle without \@.++Use 'mkUsername' for safe creation.+-}+newtype Username = Username+    { unUsername :: Text+    } deriving newtype (ToHttpApiData)++-- | Strips \@ from the username+mkUsername :: Text -> Username+mkUsername username+    = Username+    $ fromMaybe username+    $ Text.stripPrefix "@" username++data User = User+    { userId         :: UserId+    , userTweetCount :: Int+    }+++{- | Parses 'UserId' from JSON (excluding the data part, it's handled+by the 'Data' type):++@+{+  "data": {+    "id": "2164623379",+    "username": "ChShersh",+    "name": "Dmitrii Kovanikov",+    "public_metrics": {+      "followers_count": 2977,+      "following_count": 489,+      "tweet_count": 6502,+      "listed_count": 59+    }+  }+}+@+-}+instance FromJSON User where+    parseJSON = withObject "User" $ \o -> do+        userId <- o .: "id"++        publicMetrics <- o .: "public_metrics"+        userTweetCount <- publicMetrics .: "tweet_count"++        pure User{..}
+ test/Spec.hs view
@@ -0,0 +1,9 @@+module Main (main) where++import Test.Hspec (hspec)++import Test.Sauron (sauronSpec)+++main :: IO ()+main = hspec sauronSpec
+ test/Test/Sauron.hs view
@@ -0,0 +1,10 @@+module Test.Sauron (sauronSpec) where++import Test.Hspec (Spec, describe)++import Test.Sauron.Top (topSpec)+++sauronSpec :: Spec+sauronSpec = describe "Sauron" $ do+    topSpec
+ test/Test/Sauron/Top.hs view
@@ -0,0 +1,12 @@+module Test.Sauron.Top (topSpec) where++import Test.Hspec (Spec, describe)++import Test.Sauron.Top.Client (clientSpec)+import Test.Sauron.Top.Tweet (tweetSpec)+++topSpec :: Spec+topSpec = describe "Top" $ do+    clientSpec+    tweetSpec
+ test/Test/Sauron/Top/Client.hs view
@@ -0,0 +1,36 @@+module Test.Sauron.Top.Client (clientSpec) where++import Servant.Client.Core.BaseUrl (showBaseUrl)+import Servant.Links (allLinks, linkURI)+import Test.Hspec (Spec, describe, it, shouldBe)++import Sauron.Top.Client (GetTweets, twitterBaseUrl)+import Sauron.Top.User (UserId (..))+++clientSpec :: Spec+clientSpec = describe "Client" $ do+    it "the GetTweets URL is correct" $+        generatedUrl `shouldBe` expectedUrl++generatedUrl :: Text+generatedUrl = mconcat+    [ toText $ showBaseUrl twitterBaseUrl+    , "/"+    , path+    ]+  where+    path :: Text+    path = show+         $ linkURI+         $ allLinks+             (Proxy @GetTweets)+             (UserId "2164623379")+             (Just 5)+             (Just "retweets")+             (Just "created_at,public_metrics")+             (Just "2022-09-01T13:52:14Z")+             Nothing++expectedUrl :: Text+expectedUrl = "https://api.twitter.com/2/users/2164623379/tweets?max_results=5&exclude=retweets&tweet.fields=created_at%2Cpublic_metrics&end_time=2022-09-01T13%3A52%3A14Z"
+ test/Test/Sauron/Top/Tweet.hs view
@@ -0,0 +1,92 @@+module Test.Sauron.Top.Tweet (tweetSpec) where++import Data.Time.Calendar (fromGregorian)+import Data.Time.Clock (DiffTime, UTCTime (..), secondsToDiffTime)+import Data.Time.Format (defaultTimeLocale, parseTimeM)+import Hedgehog (Gen, forAll, tripping)+import Test.Hspec (Spec, describe, it, shouldBe, shouldReturn)+import Test.Hspec.Hedgehog (hedgehog)++import Sauron.Top.Tweet (Tweet (..), parseTime, showTime, subtractSecond)++import qualified Data.Aeson as Aeson+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+++tweetSpec :: Spec+tweetSpec = describe "Tweet" $ do+    it "parses the time" $ do+        parseTime "2022-09-01T07:54:18.000Z" `shouldBe`+            Just (UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:18"))++    it "shows the time" $ do+        showTime (UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:18"))+            `shouldBe` "2022-09-01T07:54:18Z"++    it "subtracts one second" $ do+        subtractSecond (UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:18"))+            `shouldBe` (UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:17"))++    it "parses the example JSON tweet timeline" $+        Aeson.eitherDecodeFileStrict "example.json" `shouldReturn` Right exampleTweets++    it "decodeJSON . encodeJSON = id" $ hedgehog $ do+        tweet <- forAll genTweet+        tripping tweet Aeson.encode Aeson.eitherDecode++parseTod :: String -> DiffTime+parseTod+    = fromMaybe (error "parsing time")+    . parseTimeM True defaultTimeLocale "%H:%M:%S"++exampleTweets :: [Tweet]+exampleTweets =+    [ Tweet+        { tweetId = "1565283709275803650"+        , tweetText = "@klarkc In this particular case, laziness wasn't the problem. Something weirder was going on 🤔"+        , tweetLikeCount = 0+        , tweetCreatedAt = UTCTime (fromGregorian 2022 9 1) (parseTod "10:21:32")+        }+    , Tweet+        { tweetId = "1565246658128056320"+        , tweetText = "If you haven't finished your tea, I invite you to read one of my previous journeys into the wonders of the SQLite type system 🗺️🫖🚂\n\nhttps://t.co/4RElElHu0Z"+        , tweetLikeCount = 1+        , tweetCreatedAt = UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:18")+        }+    , Tweet+        { tweetId = "1565246655103995905"+        , tweetText = "🔮 I still had some theories about the space leak. All the metrics show that it's not the Haskell process that leaks memory.\n\nI was even suspecting space leaks in SQLite itself as my setup was unusual. But I didn't have the time to verify my hypothesis so we'll never know..."+        , tweetLikeCount = 1+        , tweetCreatedAt = UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:18")+        }+    , Tweet+        { tweetId = "1565246652121767936"+        , tweetText = "Are you still here? Do you still want to know how I solved this space leak? Very simple:\n\n🏝️ I left my job\n\nNow, it's no longer my problem and somebody else will continue what I've started 👶"+        , tweetLikeCount = 6+        , tweetCreatedAt = UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:17")+        }+    , Tweet+        { tweetId = "1565246649185849344"+        , tweetText = "🗺️ Now, real digging started. I had to use old Unix tools as my grandpa did in the good old times.\n\nI sampled the output of the /proc/rss values to check the real memory usage of my process. I've even looked at the diff between mmaped memory regions.\n\nStill, no results 🙅"+        , tweetLikeCount = 1+        , tweetCreatedAt = UTCTime (fromGregorian 2022 9 1) (parseTod "07:54:16")+        }+    ]++genTweet :: Gen Tweet+genTweet = Tweet+    <$> Gen.text (Range.linear 1 20) Gen.digit+    <*> Gen.text (Range.linear 1 280) Gen.unicode+    <*> Gen.int (Range.linear 0 100_000)+    <*> genUTCTime++genUTCTime :: Gen UTCTime+genUTCTime = do+    y <- toInteger <$> Gen.int (Range.constant 2000 2022)+    m <- Gen.int (Range.constant 1 12)+    d <- Gen.int (Range.constant 1 28)+    let day = fromGregorian y m d+    secs <- toInteger <$> Gen.int (Range.constant 0 86401)+    let diff = secondsToDiffTime secs+    pure $ UTCTime day diff