+/*
+ * Copyright (C) 2010-2013 jeanfi@gmail.com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA
+ */
+#include <locale.h>
+#include <libintl.h>
+#define _(str) gettext(str)
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <curl/curl.h>
+#include <json/json.h>
+
+#include "url.h"
+
+struct ucontent {
+ char *data;
+ size_t len;
+};
+
+static CURL *curl;
+
+static size_t cbk_curl(void *buffer, size_t size, size_t nmemb, void *userp)
+{
+ size_t realsize;
+ struct ucontent *mem;
+
+ realsize = size * nmemb;
+ mem = (struct ucontent *)userp;
+
+ mem->data = realloc(mem->data, mem->len + realsize + 1);
+
+ memcpy(&(mem->data[mem->len]), buffer, realsize);
+ mem->len += realsize;
+ mem->data[mem->len] = 0;
+
+ return realsize;
+}
+
+void phttp_init()
+{
+ curl = curl_easy_init();
+}
+
+void phttp_cleanup()
+{
+ curl_easy_cleanup(curl);
+}
+
+json_object *get_json_object(const char *url)
+{
+ struct ucontent chunk;
+ json_object *obj;
+
+ obj = NULL;
+
+ if (!curl)
+ return NULL;
+
+ chunk.data = malloc(1);
+ chunk.len = 0;
+
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+ curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cbk_curl);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
+
+ if (curl_easy_perform(curl) == CURLE_OK)
+ obj = json_tokener_parse(chunk.data);
+ else
+ fprintf(stderr, _("Fail to connect to: %s"), url);
+
+ free(chunk.data);
+
+ return obj;
+}
+
+static json_object *post(const char *url, const char *body)
+{
+ struct ucontent chunk;
+ json_object *obj;
+
+ obj = NULL;
+
+ chunk.data = malloc(1);
+ chunk.len = 0;
+
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+ curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
+ if (body) {
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(body));
+ }
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cbk_curl);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
+
+ if (curl_easy_perform(curl) == CURLE_OK)
+ obj = json_tokener_parse(chunk.data);
+ else
+ fprintf(stderr, _("Fail to connect to: %s"), url);
+ free(chunk.data);
+
+ return obj;
+}
+
+json_object *post_json_object(const char *url, struct json_object *j)
+{
+ return post(url, json_object_to_json_string(j));
+}