aboutsummaryrefslogtreecommitdiff
path: root/src/Tomato/Retrieve.hs
blob: c43607ee79fccf708c48f1869b3a253fae3e9ea6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module Tomato.Retrieve
    ( randomTomato
    , downloadTomato
    , queryTomato
    ) where

import RIO

import Network.HTTP.Req
    ( jsonResponse
    , bsResponse
    , req
    , Req
    , runReq
    , defaultHttpConfig
    , NoReqBody (..)
    , (/:)
    , (=:)
    , GET (..)
    , https
    , responseBody
    )

import Tomato.App (App (..))
import Tomato.Data.Except (DecodeException (..))
import Tomato.Data.Tomato (Tomato (..), Links (..))

import qualified Data.Aeson as Ae
import qualified RIO.ByteString as B
import qualified RIO.Text as T


-- | Get a random tomato
randomTomato :: RIO App ()
randomTomato = queryTomato >>= downloadTomato

-- | Ask for a tomato
queryTomato :: RIO App Tomato
queryTomato = do
    clientId <- asks appClientId
    let url = https "api.unsplash.com" /: "photos" /: "random"
    js <- rr $ req GET url NoReqBody jsonResponse $
        "query" =: ("tomato" :: Text) <>
        "client_id" =: clientId
    tomato <- case Ae.fromJSON (responseBody js) of
        Ae.Success r -> pure r
        Ae.Error s -> throwM $ DecodeException $
            "Get tomato url: " <>
            T.pack s <>
            T.pack (show (responseBody js))
    return tomato

-- | Download a specific tomato
downloadTomato :: Tomato -> RIO App ()
downloadTomato tom = do
    tomatoFile <- asks appFile
    clientId <- asks appClientId
    let url = download (links tom)
    bs <- rr $ req GET url NoReqBody bsResponse $
        "query" =: ("tomato" :: Text) <>
        "client_id" =: clientId
    B.writeFile tomatoFile (responseBody bs)

rr :: Req a -> RIO App a
rr = runReq defaultHttpConfig