2021-09-05 19:30:29 +02:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
|
|
|
2021-09-17 17:36:58 +02:00
|
|
|
{-|
|
2021-09-20 14:19:48 +02:00
|
|
|
Module : Kino.Request
|
2021-09-17 17:36:58 +02:00
|
|
|
Description : Contains code for issuing http requests
|
|
|
|
|
2021-09-20 14:19:48 +02:00
|
|
|
Contains code for issuing http requests
|
|
|
|
-}
|
2021-09-05 19:30:29 +02:00
|
|
|
|
2021-09-20 15:30:10 +02:00
|
|
|
module Kino.Request (setMovies, defaultOptions) where
|
|
|
|
|
|
|
|
import Control.Exception
|
2021-09-05 19:30:29 +02:00
|
|
|
|
|
|
|
import Control.Lens
|
2021-09-20 15:30:10 +02:00
|
|
|
import Data.Aeson hiding (defaultOptions)
|
2021-09-20 14:19:48 +02:00
|
|
|
import Network.Wreq hiding (Options)
|
2021-09-14 17:06:34 +02:00
|
|
|
import qualified Data.Text as T
|
2021-09-20 14:19:48 +02:00
|
|
|
import qualified Network.Wreq as WR (Options)
|
|
|
|
|
|
|
|
import Kino.Types
|
2021-09-20 15:30:10 +02:00
|
|
|
import Kino.Misc
|
2021-09-05 19:30:29 +02:00
|
|
|
|
2021-09-17 17:36:58 +02:00
|
|
|
-- | Sends a request and unwraps the top level respone data structure
|
2021-09-06 21:02:39 +02:00
|
|
|
makeRequest :: (FromJSON a) => String -> WR.Options -> IO (Either T.Text a)
|
|
|
|
makeRequest url opts = do
|
|
|
|
r <- asJSON =<< getWith opts url
|
2021-09-20 14:19:48 +02:00
|
|
|
pure $ case r ^. responseBody of
|
2021-09-07 18:37:21 +02:00
|
|
|
(JSONResponse "ok" _ (Just d)) -> Right d
|
2021-09-19 19:43:19 +02:00
|
|
|
(JSONResponse _ m _) -> Left m
|
2021-09-06 21:02:39 +02:00
|
|
|
|
2021-09-20 15:30:10 +02:00
|
|
|
-- | Sends a request with the given parameters
|
|
|
|
getMovies :: WR.Options -> IO (Either SomeException (Either T.Text JSONListMovies))
|
|
|
|
getMovies = try . makeRequest "https://yts.mx/api/v2/list_movies.json"
|
|
|
|
|
|
|
|
-- | The default options for our requests
|
|
|
|
defaultOptions :: WR.Options
|
|
|
|
defaultOptions = defaults & param "limit" .~ ["50"]
|
|
|
|
& param "page" .~ ["1"]
|
|
|
|
|
|
|
|
-- | Updates the state given a way to request a new movie listing
|
|
|
|
setMovies :: AppS -> IO AppS
|
|
|
|
setMovies s = do
|
|
|
|
m <- getMovies ((s ^. appReqOpts) & param "page" .~ [T.pack (show (s ^. appPage))])
|
|
|
|
pure $ case m of
|
|
|
|
(Left e) -> displayMessage s True (displayException e)
|
|
|
|
(Right r) -> case r of
|
|
|
|
(Left t) -> displayMessage s False (T.unpack t)
|
|
|
|
(Right l) -> s & appListing .~ l
|
|
|
|
& appCursor .~ 0
|
|
|
|
& appExpanded .~ False
|
|
|
|
& appDetails .~ (moviesMovies l !? 0)
|