summaryrefslogtreecommitdiff
path: root/src/Web/VKHS/API/Base.hs
blob: 34050b618f36c2525b953c010b7a17a377a69f38 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}

module Web.VKHS.API.Base where

import Data.Time
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Cont
import Control.Exception (catch, SomeException)

import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.ByteString.Lazy (fromStrict,toChunks)
import qualified Data.ByteString.Char8 as BS

import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.Aeson.Encode.Pretty as Aeson

import Text.Printf
import Text.Read (readMaybe)

import Web.VKHS.Imports
import Web.VKHS.Types
import Web.VKHS.Client hiding (Response(..))
import Web.VKHS.Monad
import Web.VKHS.Error
import Web.VKHS.API.Types

import Debug.Trace

data APIState = APIState {
    api_access_token :: String
  } deriving (Show)

defaultState = APIState {
    api_access_token = ""
  }

class ToGenericOptions s => ToAPIState s where
  toAPIState :: s -> APIState
  modifyAPIState :: (APIState -> APIState) -> (s -> s)

-- | Modifies VK access token in the internal state as well as in the external
-- storage, if enabled.
--
-- See also 'readInitialAccessToken'
modifyAccessToken :: (MonadIO m, MonadState s m, ToAPIState s) => AccessToken -> m ()
modifyAccessToken at@AccessToken{..} = do
  modify $ modifyAPIState (\as -> as{api_access_token = at_access_token})
  GenericOptions{..} <- getGenericOptions
  case l_access_token_file of
    [] -> return ()
    fl -> liftIO $ writeFile l_access_token_file (show at)
  return ()

-- | Class of monads able to run VK API calls. @m@ - the monad itself, @x@ -
-- type of early error, @s@ - type of state (see alse @ToAPIState@)
class (MonadIO (m (R m x)), MonadClient (m (R m x)) s, ToAPIState s, MonadVK (m (R m x)) (R m x)) =>
  MonadAPI m x s | m -> s

type API m x a = m (R m x) a

-- | Utility function to parse JSON object
--
-- * FIXME Don't raise exception, simply return `Left err`
decodeJSON :: (MonadAPI m x s)
    => ByteString
    -> API m x JSON
decodeJSON bs = do
  case Aeson.decode (fromStrict bs) of
    Just js -> return (JSON js)
    Nothing -> raise (JSONParseFailure bs)

-- | Invoke the request. Returns answer as JSON object .
--
-- See the official documentation:
-- <https://vk.com/dev/methods>
-- <https://vk.com/dev/json_schema>
--
-- * FIXME We currentyl use Text.unpack to encode text into strings. Use encodeUtf8
--   FIXME instead.
-- * FIXME Split into request builder and request executer
apiJ :: (MonadAPI m x s)
    => String
    -- ^ API method name
    -> [(String, Text)]
    -- ^ API method arguments
    -> API m x JSON
apiJ mname (map (id *** tunpack) -> margs) = do
  GenericOptions{..} <- gets toGenericOptions
  APIState{..} <- gets toAPIState
  let protocol = (case o_use_https of
                    True -> "https"
                    False -> "http")
  url <- ensure $ pure
        (urlCreate
          (URL_Protocol protocol)
          (URL_Host o_api_host)
          (Just (URL_Port (show o_port)))
          (URL_Path ("/method/" ++ mname))
          (buildQuery (("access_token", api_access_token):margs)))

  debug $ "> " <> (tshow url)

  req <- ensure (requestCreateGet url (cookiesCreate ()))
  (res, jar') <- requestExecute req
  decodeJSON (responseBody res)


-- | Invoke the request, return answer as a Haskell datatype. On error fall out
-- to the supervizer (e.g. @VKHS.defaultSuperviser@) without possibility to
-- continue
api :: (Aeson.FromJSON a, MonadAPI m x s)
    => String
    -- ^ API method name
    -> [(String, Text)]
    -- ^ API method arguments
    -> API m x a
api m args = do
  j <- apiJ m args
  case parseJSON j of
    Right a -> return a
    Left e -> terminate (JSONParseFailure' j e)

-- | Invoke the request, in case of failure, escalate the probelm to the
-- supervisor. The superwiser has a chance to change the arguments
apiR :: (Aeson.FromJSON a, MonadAPI m x s)
    => MethodName -- ^ API method name
    -> MethodArgs -- ^ API method arguments
    -> API m x a
apiR m0 args0 = go (ReExec m0 args0) where
  go action = do
    j <- do
      case action of
        ReExec m args -> do
          apiJ m args
        ReParse j -> do
          pure j
    case parseJSON j of
      (Right (Response _ a)) -> return a
      (Left e) -> do
        recovery <- raise (CallFailure (m0, args0, j, e))
        go recovery

-- | Invoke the request, in case of failure, escalate the probelm to the
-- supervisor. The superwiser has a chance to change the arguments
apiHM :: forall m x a s . (Aeson.FromJSON a, MonadAPI m x s)
    => MethodName -- ^ API method name
    -> MethodArgs -- ^ API method arguments
    -> (ErrorRecord -> API m x (Maybe a))
    -> API m x a
apiHM m0 args0 handler = go (ReExec m0 args0) where
  go action = do
    j <- do
      case action of
        ReExec m args -> do
          apiJ m args
        ReParse j -> do
          pure j
    case (parseJSON j, parseJSON j) of
      (Left e1, Left e2) -> do
        recovery <- raise (CallFailure (m0, args0, j, e1 <> ";" <> e2))
        go recovery
      (Left e, Right (Response _ err)) -> do
        ma <- (handler err)
        case ma of
          Just a -> return a
          Nothing -> do
            recovery <- raise (CallFailure (m0, args0, j, e))
            go recovery
      (Right _, Right (Response _ err)) -> do
        ma <- (handler err)
        case ma of
          Just a -> return a
          Nothing -> do
            recovery <- raise (CallFailure (m0, args0, j,
              "Response matches both error and result object"))
            go recovery
      (Right (Response _ a), _) -> do
        return a

apiH :: forall m x a s . (Aeson.FromJSON a, MonadAPI m x s)
    => MethodName -- ^ API method name
    -> MethodArgs -- ^ API method arguments
    -> (ErrorRecord -> Maybe a)
    -> API m x a
apiH m args handler = apiHM m args (\e -> pure (handler e) :: API m x (Maybe a))

-- | Invoke the request, return answer as a Haskell datatype or @ErrorRecord@
-- object
apiE :: (Aeson.FromJSON a, MonadAPI m x s)
    => String           -- ^ API method name
    -> [(String, Text)] -- ^ API method arguments
    -> API m x (Either (Response ErrorRecord) a)
apiE m args = apiJ m args >>= convert where
  convert j = do
    err <- pure $ parseJSON j
    ans <- pure $ parseJSON j
    case  (ans, err) of
      (Right a, _) -> return (Right a)
      (Left a, Right e) -> return (Left e)
      (Left a, Left e) -> do
        j' <- raise (JSONCovertionFailure
                     (j, "apiE: " <> Text.pack m <> ": expecting either known response or error"))
        convert j'

-- | Invoke the request, returns answer or the default value in case of error
apiD :: (Aeson.FromJSON a, MonadAPI m x s)
    => a
    -> String           -- ^ API method name
    -> [(String, Text)] -- ^ API method arguments
    -> API m x a
apiD def m args =
  apiE m args >>= \case
    Left err -> return def
    Right x -> return x

-- | String version of @api@
-- Deprecated
api_S :: (Aeson.FromJSON a, MonadAPI m x s)
    => String -> [(String, String)] -> API m x a
api_S m args = api m (map (id *** tpack) args)

-- Encode JSON back to string
jsonEncodeBS :: JSON -> ByteString
jsonEncodeBS JSON{..} = BS.concat $ toChunks $ Aeson.encode js_aeson

jsonEncode :: JSON -> Text
jsonEncode JSON{..} = Text.decodeUtf8 $ BS.concat $ toChunks $ Aeson.encode js_aeson

jsonEncodePrettyBS :: JSON -> ByteString
jsonEncodePrettyBS JSON{..} = BS.concat $ toChunks $ Aeson.encodePretty js_aeson

jsonEncodePretty :: JSON -> Text
jsonEncodePretty JSON{..} = Text.decodeUtf8 $ BS.concat $ toChunks $ Aeson.encodePretty js_aeson