~tristan957/harvest-almanac

ref: bfe5e7751325f8d81c4689f3396f3f20a4ec6e37 harvest-almanac/harvest-glib/harvest-api-client.c -rw-r--r-- 8.9 KiB
bfe5e775Tristan Partin flatpak: updated manifest file and docs 1 year, 10 months ago
                                                                                
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#include "config.h"

#define G_LOG_DOMAIN "HarvestApiClient"

#include <limits.h>

#include <glib-object.h>
#include <glib/gi18n-lib.h>
#include <json-glib/json-glib.h>
#include <libsoup/soup.h>

#include "harvest-api-client.h"
#include "harvest-common.h"
#include "harvest-http.h"
#include "harvest-request.h"
#include "harvest-response-metadata.h"
#include "harvest-response.h"

#define HARVEST_API_URL "https://api.harvestapp.com/v2"

static HarvestApiClient *API_CLIENT;

struct _HarvestApiClient
{
	GObject parent_instance;

	SoupSession *session;
	char *server;
	char *access_token;
	char *account_id;
};

G_DEFINE_TYPE(HarvestApiClient, harvest_api_client, G_TYPE_OBJECT)

enum HarvestApiClientProps
{
	PROP_0,
	PROP_SESSION,
	PROP_SERVER,
	PROP_ACCESS_TOKEN,
	PROP_ACCOUNT_ID,
	N_PROPS,
};

static GParamSpec *obj_properties[N_PROPS];

static void
harvest_api_client_get_property(GObject *obj, guint prop_id, GValue *val, GParamSpec *pspec)
{
	HarvestApiClient *self = HARVEST_API_CLIENT(obj);

	switch (prop_id) {
	case PROP_SESSION:
		g_value_set_object(val, self->session);
		break;
	case PROP_SERVER:
		g_value_set_string(val, self->server);
		break;
	case PROP_ACCESS_TOKEN:
		g_value_set_string(val, self->access_token);
		break;
	case PROP_ACCOUNT_ID:
		g_value_set_string(val, self->account_id);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, prop_id, pspec);
		break;
	}
}

static void
harvest_api_client_set_property(GObject *obj, guint prop_id, const GValue *val, GParamSpec *pspec)
{
	HarvestApiClient *self = HARVEST_API_CLIENT(obj);

	switch (prop_id) {
	case PROP_SESSION:
		if (self->session != NULL)
			g_object_unref(self->session);
		self->session = g_value_dup_object(val);
		break;
	case PROP_SERVER:
		g_free(self->server);
		self->server = g_value_dup_string(val);
		break;
	case PROP_ACCESS_TOKEN:
		g_free(self->access_token);
		self->access_token = g_strdup_printf("Bearer %s", g_value_get_string(val));
		break;
	case PROP_ACCOUNT_ID:
		g_free(self->account_id);
		self->account_id = g_value_dup_string(val);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, prop_id, pspec);
		break;
	}
}

static void
harvest_api_client_finalize(GObject *obj)
{
	HarvestApiClient *self = HARVEST_API_CLIENT(obj);

	g_free(self->server);
	g_free(self->access_token);
	g_free(self->account_id);

	G_OBJECT_CLASS(harvest_api_client_parent_class)->finalize(obj);
}

static void
harvest_api_client_class_init(HarvestApiClientClass *klass)
{
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize		= harvest_api_client_finalize;
	obj_class->get_property = harvest_api_client_get_property;
	obj_class->set_property = harvest_api_client_set_property;

	obj_properties[PROP_SESSION] = g_param_spec_object("session", _("Session"),
		_("SoupSession object to use to make requests."), SOUP_TYPE_SESSION,
		G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_SERVER]
		= g_param_spec_string("server", _("Server"), _("Base URL for the server."), NULL,
			G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_ACCESS_TOKEN] = g_param_spec_string("access-token", _("Access Token"),
		_("Developer access token for the Harvest API."), NULL,
		G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_ACCOUNT_ID]
		= g_param_spec_string("account-id", _("Account ID"), _("Harvest account ID to use."), NULL,
			G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties(obj_class, N_PROPS, obj_properties);
}

static void
harvest_api_client_init(G_GNUC_UNUSED HarvestApiClient *self)
{}

void
harvest_api_client_initialize(
	SoupSession *session, const char *access_token, const char *account_id)
{
	g_return_if_fail(SOUP_IS_SESSION(session) && access_token != NULL && account_id != NULL);

	if (API_CLIENT != NULL)
		g_object_unref(API_CLIENT);

	API_CLIENT = g_object_new(HARVEST_TYPE_API_CLIENT, "session", session, "server",
		HARVEST_API_URL, "access-token", access_token, "account-id", account_id, NULL);
}

void
harvest_api_client_free()
{
	if (API_CLIENT != NULL)
		g_object_unref(API_CLIENT);
}

static void
harvest_api_client_destroy_request(
	HarvestRequest *req, HarvestResponse *res, G_GNUC_UNUSED gpointer user_data)
{
	g_object_unref(req);
	g_object_unref(res);
}

static HarvestResponse *
create_response(HarvestRequest *req, SoupMessage *msg)
{
	HarvestResponseMetadata *metadata = harvest_request_get_response_metadata(req);
	const GType body_type			  = harvest_response_metadata_get_body_type(metadata);
	const HttpStatusCode expected	  = harvest_response_metadata_get_expected_status(metadata);

	GValue val	= G_VALUE_INIT;
	GError *err = NULL;

	if (msg->status_code != expected) {
		g_set_error(&err, HARVEST_API_CLIENT_ERROR, HARVEST_API_CLIENT_ERROR_UNEXPECTED_STATUS,
			"unexpected status code of %u, expected %u", expected, msg->status_code);
	}

	if (err == NULL && body_type != G_TYPE_NONE) {
		/*
		 * This probably looks absolutely stupid to the naked eye, but goto cannot be used
		 * effectively here due to the location in which the response object is created, and not
		 * wanting to repeat its creation at every error branch. With this do/while, we can use
		 * break to provide effective control flow on error.
		 */
		do {
			g_autoptr(SoupBuffer) buf = soup_message_body_flatten(msg->response_body);
			g_autoptr(GBytes) bytes	  = soup_buffer_get_as_bytes(buf);

			gsize size				= 0;
			gconstpointer body_data = g_bytes_get_data(bytes, &size);

			g_autoptr(JsonNode) node = json_from_string(body_data, &err);
			if (err != NULL) {
				break;
			}

			if (json_node_is_null(node)) {
				break;
			}

			g_value_init(&val, body_type);

			switch (body_type) {
			case G_TYPE_INT:
			case G_TYPE_INT64:
				g_value_set_int64(&val, json_node_get_int(node));
				break;
			case G_TYPE_FLOAT:
			case G_TYPE_DOUBLE:
				g_value_set_double(&val, json_node_get_double(node));
				break;
			case G_TYPE_STRING:
				g_value_set_string(&val, json_node_dup_string(node));
				break;
			case G_TYPE_BOOLEAN:
				g_value_set_boolean(&val, json_node_get_boolean(node));
				break;
			default:
				// Handle non-static GTypes
				if (body_type == JSON_TYPE_NODE) {
					g_value_set_object(&val, node);
				} else if (body_type == JSON_TYPE_ARRAY) {
					g_value_set_object(&val, json_node_dup_array(node));
				} else if (body_type == JSON_TYPE_OBJECT) {
					g_value_set_object(&val, json_node_dup_object(node));
				} else {
					GObject *data = json_gobject_deserialize(body_type, node);
					if (data == NULL) {
						g_set_error_literal(&err, HARVEST_API_CLIENT_ERROR,
							HARVEST_API_CLIENT_ERROR_UNABLE_TO_DESERIALIZE_OBJECT,
							"create_response: unable to deserialize response body into a GObject");

						break;
					}

					g_value_set_object(&val, data);
				}
			}
		} while (FALSE);
	}

	if (err != NULL) {
		g_value_unset(&val);
	}

	HarvestResponse *res = harvest_response_new(&val, msg->status_code, err);

	return res;
}

static void
harvest_api_client_async_callback(
	G_GNUC_UNUSED SoupSession *Session, SoupMessage *msg, gpointer user_data)
{
	HarvestRequest *req	 = HARVEST_REQUEST(user_data);
	HarvestResponse *res = create_response(req, msg);

	g_signal_connect_after(req, "completed", G_CALLBACK(harvest_api_client_destroy_request), res);
	g_signal_emit_by_name(req, "completed", res);
}

static SoupMessage *
create_message(HarvestRequest *req)
{
	SoupMessage *msg = NULL;
	g_autofree char *uri
		= g_strdup_printf("%s%s", API_CLIENT->server, harvest_request_get_endpoint(req));
	gboolean response_has_body = harvest_request_get_data(req) != NULL;
	char *body				   = NULL;
	gsize len				   = 0;

	if (response_has_body) {
		body = json_gobject_to_data(harvest_request_get_data(req), &len);
		len	 = strlen(body);
	}

	switch (harvest_request_get_http_method(req)) {
	case HTTP_METHOD_GET:
		msg = soup_message_new("GET", uri);
		soup_message_set_request(
			msg, response_has_body ? "application/json" : NULL, SOUP_MEMORY_TAKE, body, len);
		break;
	case HTTP_METHOD_POST:
		break;
	case HTTP_METHOD_PATCH:
		break;
	case HTTP_METHOD_DELETE:
		break;
	default:
		g_return_val_if_reached(NULL);
	}

	soup_message_headers_append(msg->request_headers, "Authorization", API_CLIENT->access_token);
	soup_message_headers_append(msg->request_headers, "Harvest-Account-Id", API_CLIENT->account_id);

	return msg;
}

HarvestResponse *
harvest_api_client_execute_request_sync(HarvestRequest *req)
{
	g_return_val_if_fail(HARVEST_IS_REQUEST(req), NULL);

	g_autoptr(SoupMessage) msg = create_message(req);
	soup_session_send_message(API_CLIENT->session, msg);
	HarvestResponse *res = create_response(req, msg);
	g_signal_emit_by_name(req, "completed", res);

	return res;
}

void
harvest_api_client_execute_request_async(HarvestRequest *req)
{
	g_return_if_fail(HARVEST_IS_REQUEST(req));

	SoupMessage *msg = create_message(req);

	soup_session_queue_message(API_CLIENT->session, msg, harvest_api_client_async_callback, req);
}

G_DEFINE_QUARK(harvest_api_client_error, harvest_api_client_error)