HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
FS_WebAPI.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * COMMENTS:
7  *
8  * Sample usage:
9  * FS_WebAPIResponse response =
10  * FS_WebAPI("http://www.orbolt.com/api").call1(
11  * "is_asset_in_store", "SideFX::spaceship");
12  * response.myJSONResult.dump();
13  * std::cout << "\nerrors: " << response.myErrors.nonNullBuffer()
14  * << std::endl;
15  * Prints:
16  * true
17  * errors:
18  */
19 
20 #ifndef __FS_WebAPI_h__
21 #define __FS_WebAPI_h__
22 
23 #include "FS_API.h"
24 
25 #include <type_traits>
26 
27 #include <UT/UT_String.h>
28 #include <UT/UT_StringHolder.h>
29 #include <UT/UT_WorkBuffer.h>
30 
31 #include <UT/UT_ScopeExit.h>
32 #include <UT/UT_JSONValue.h>
33 #include <UT/UT_JSONWriter.h>
34 #include <UT/UT_UniquePtr.h>
35 #include <UT/UT_DeepString.h>
36 #include <UT/UT_Optional.h>
37 #include <UT/UT_Lock.h>
38 #include <UT/UT_StringArray.h>
39 #include <UT/UT_ArrayStringMap.h>
40 
41 // Static check to see if the type is a string type. Note decay the type so that
42 // any provided type will be checked to see if its a string object
43 template <class T>
44 struct FS_IsString : std::integral_constant<bool,
45  std::is_same<UT_String, typename std::decay<T>::type>::value ||
46  std::is_same<UT_StringHolder, typename std::decay<T>::type>::value ||
47  std::is_same<UT_WorkBuffer, typename std::decay<T>::type>::value ||
48  std::is_same<std::string, typename std::decay<T>::type>::value>
49 {};
50 
51 // NOTE: Not a full list of http status codes
53 {
54  // Curl uses zero to indicate no status code received
56  // Info Codes
59  // Success Codes
60  FS_HTTPOk = 200,
67  // Redirect Codes
70  FS_HTTPFound = 302,
75  // Client Error Codes
86  FS_HTTPGone = 410,
100  // Server Error Codes
108 };
109 
110 // Response from client request
112 {
113 public:
115  FS_HTTPResponse();
119  const UT_StringHolder& data);
120  FS_HTTPResponse(FS_HTTPStatusCode code, const HeaderMap& headers,
121  const UT_StringHolder& data);
122  FS_HTTPResponse(FS_HTTPStatusCode code, const HeaderMap& headers);
123 
124  operator bool() const { return myStatus == FS_HTTPOk; }
125 
126  FS_HTTPStatusCode status() const { return myStatus; }
127  bool isRequestNotFound() const { return myStatus == FS_HTTPNotFound; }
128  bool hasTimedout() const { return myStatus == FS_HTTPRequestTimeout; }
129 
130  const UT_StringHolder& headers() const { return myHeaders; }
131  HeaderMap headersAsMap() const;
132 
133  // Does this response object have a specific option specified.
134  bool hasHeaderOption(const char* header_opt) const;
135 
136  void setHeaders(const HeaderMap& headers);
137  void setHeaders(const UT_StringHolder& headers)
138  {
139  myHeaders = headers;
140  }
141  void setData(const char* data)
142  {
143  myData = data;
144  }
145 
146  bool errorReceivedNothing() const;
147 
148  const UT_StringHolder& data() const { return myData; }
149  const UT_StringHolder& errors() const
150  {
151  // If there are errors then return it
152  if (myErrors.length() > 0)
153  return myErrors;
154 
155  // If the request was not successful then return the bodies data
156  // instead as that will hold the error information for the request.
157  if (myStatus != FS_HTTPOk)
158  return myData;
159 
160  return myErrors;
161  }
162 
163  static UT_Optional<const UT_StringHolder&> getHeaderContentType(const HeaderMap& headers);
164  static UT_Optional<exint> getHeaderContentLength(const HeaderMap& headers);
165 
166  // Get the stock message based on the status code
167  static void stockMsgFromCode(FS_HTTPStatusCode code, UT_WorkBuffer& msg);
168 
169 private:
170  friend class FS_WebAPI;
171 
172  int myCommError;
173  FS_HTTPStatusCode myStatus;
174  UT_StringHolder myHeaders;
175  UT_StringHolder myData;
176  UT_StringHolder myErrors;
177 };
178 
180 {
181 public:
184 };
185 
187 {
188 public:
190 
191  FS_WebAPI(const char *api_url);
192 
193  static UT_StringHolder decodeUri(const UT_StringView uri);
194  static UT_StringHolder encodeUri(const UT_StringView uri);
195 
196  void setProxy(const UT_StringHolder& proxy);
197  const UT_StringHolder& proxy() const { return myProxy; }
198 
199  void setTimeout(int timeout);
200  void followRedirects(bool follow);
201  bool shouldFollowRedirects() const { return myFollowRedirects; }
202 
203  // Send an HTTP post request
204  bool post(FS_HTTPResponse& resp, const WebMap& variables,
205  const UT_Optional<const WebMap&>& headers = UT_Optional<const WebMap&>()) const;
206 
207  // The following method lets you make API calls to named functions in
208  // the Web API. Call the appropriate method for the given number of
209  // arguments.
210  template <typename... Args>
211  FS_WebAPIResponse call(const char* api_url, Args&&... args);
212 
213  bool hasValidProxy() const
214  {
215  return !myProxy.isEmpty();
216  }
217 
218  const UT_String& getAPIUrl() const { return myAPIURL; }
219  int getTimeout() const { return myTimeout; }
220  const UT_WorkBuffer& getCookies() const { return myCookies; }
221 
222  // Set the ssl certificate for ssl communication.
223  void sslCertificate(const UT_StringHolder& cert) { myCert = cert; }
224  const UT_StringHolder& getCertificate() const { return myCert; }
225 
226  // This is a really simple implementation. It doesn't check for duplicates
227  // or anything like that.
228  //
229  // USE AT YOUR OWN RISK
230  void addCookie(const char *name, const char *value);
231  void clearCookies();
232 
233  // Determines CURLOPT_CAPATH
234  static UT_StringHolder determineCAPath();
235  // Determines CURLOPT_CAINFO
236  static UT_StringHolder determineCAInfo();
237 private:
238  // Send http request in our APIs format
239  FS_WebAPIResponse post(const WebMap &variables) const;
240 
241  static void webCall(UT_JSONWriter& writer);
242  template <typename T>
243  static void webCall(UT_JSONWriter& writer, T&& arg);
244  template <typename T, typename... REST>
245  static void webCall(UT_JSONWriter& writer, T&& args, REST&&... rest);
246 
247  FS_WebAPIResponse callFunctionWithJSONArgs(
248  const UT_WorkBuffer &json_data) const;
249 
250  FS_WebAPIResponse postAndGetJSONResponse(
251  void *curl, const char *post_data) const;
252 
253  void writeAPICallPrefixToJSON(
254  UT_JSONWriter &writer, const char *api_function) const;
255  void writeAPICallSuffixToJSON(UT_JSONWriter &writer) const;
256 
257  UT_String myAPIURL;
258  UT_StringHolder myProxy;
259  UT_WorkBuffer myCookies;
260  int myTimeout;
261  bool myFollowRedirects;
262  UT_StringHolder myCert;
263 };
264 
265 //---------------------------------------------------------------------------
266 
267 // Needed until we switch to c++17 (needs constexpr if)
268 inline
269 void
270 FS_WebAPI::webCall(UT_JSONWriter& writer)
271 {}
272 
273 template <typename T>
274 inline
275 void
276 FS_WebAPI::webCall(UT_JSONWriter& writer, T&& arg)
277 {
278  writer.jsonValue(arg);
279 }
280 
281 template <typename T, typename ...REST>
282 void
283 FS_WebAPI::webCall(UT_JSONWriter& writer, T&& arg, REST&&... rest)
284 {
285  writer.jsonValue(arg);
286  webCall(writer, std::forward<REST>(rest)...);
287 }
288 
289 template <typename ...Args>
290 inline
292 FS_WebAPI::call(const char* api_function, Args&&... args)
293 {
294  UT_WorkBuffer json_data;
295  UT_UniquePtr<UT_JSONWriter> json_writer(
296  UT_JSONWriter::allocWriter(json_data));
297 
298  writeAPICallPrefixToJSON(*json_writer, api_function);
299  // When we switch to c++17 switch this to check if the number of elements is
300  // > 0 so we don't need the no-op function (needs constexpr if)
301  webCall(*json_writer, std::forward<Args>(args)...);
302  writeAPICallSuffixToJSON(*json_writer);
303  return callFunctionWithJSONArgs(json_data);
304 }
305 
306 #endif
FS_WebAPIResponse call(const char *api_url, Args &&...args)
Definition: FS_WebAPI.h:292
int getTimeout() const
Definition: FS_WebAPI.h:219
bool jsonValue(bool value)
const UT_StringHolder & getCertificate() const
Definition: FS_WebAPI.h:224
GLuint const GLchar * name
Definition: glew.h:1814
const Args & args
Definition: printf.h:628
internal::named_arg< T, char > arg(string_view name, const T &arg)
Definition: core.h:1393
static UT_JSONWriter * allocWriter(UT_WorkBuffer &buffer)
Class which writes ASCII or binary JSON streams.
Definition: UT_JSONWriter.h:32
const UT_StringHolder & headers() const
Definition: FS_WebAPI.h:130
FS_HTTPStatusCode status() const
Definition: FS_WebAPI.h:126
UT_JSONValue myJSONResult
Definition: FS_WebAPI.h:182
A utility class to do read-only operations on a subset of an existing string.
Definition: UT_StringView.h:32
hboost::optional< T > UT_Optional
Definition: UT_Optional.h:16
const UT_StringHolder & proxy() const
Definition: FS_WebAPI.h:197
GLint GLenum GLsizei GLint GLsizei const void * data
Definition: glew.h:1379
void setData(const char *data)
Definition: FS_WebAPI.h:141
bool hasValidProxy() const
Definition: FS_WebAPI.h:213
void sslCertificate(const UT_StringHolder &cert)
Definition: FS_WebAPI.h:223
const UT_String & getAPIUrl() const
Definition: FS_WebAPI.h:218
UT_DeepString myErrors
Definition: FS_WebAPI.h:183
const UT_StringHolder & data() const
Definition: FS_WebAPI.h:148
const UT_WorkBuffer & getCookies() const
Definition: FS_WebAPI.h:220
bool shouldFollowRedirects() const
Definition: FS_WebAPI.h:201
const UT_StringHolder & errors() const
Definition: FS_WebAPI.h:149
Class to store JSON objects as C++ objects.
Definition: UT_JSONValue.h:76
bool isRequestNotFound() const
Definition: FS_WebAPI.h:127
FS_HTTPStatusCode
Definition: FS_WebAPI.h:52
GLbitfield GLuint64 timeout
Definition: glew.h:6605
bool hasTimedout() const
Definition: FS_WebAPI.h:128
GridType::Ptr curl(const GridType &grid, bool threaded, InterruptT *interrupt)
Compute the curl of the given vector-valued grid.
GA_API const UT_StringHolder rest
GLsizei const GLfloat * value
Definition: glew.h:1849
#define FS_API
Definition: FS_API.h:10
void setHeaders(const UT_StringHolder &headers)
Definition: FS_WebAPI.h:137