1 /*
2  * Copyright 2011 kubtek <kubtek@mail.com>
3  *
4  * This file is part of StarDict.
5  *
6  * StarDict is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * StarDict is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with StarDict.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef _STARDICT_HTTP_CLIENT_H_
21 #define _STARDICT_HTTP_CLIENT_H_
22 
23 #include <glib.h>
24 #include <string>
25 #include <vector>
26 #include <cstring>
27 
28 #ifndef _WIN32
29 #  include <netdb.h>
30 #else
31 typedef unsigned long in_addr_t;
32 #endif
33 
34 #include "stardict-sigc++.h"
35 
36 
37 typedef void (*get_http_response_func_t)(char *buffer, size_t buffer_len, gpointer userdata);
38 enum HttpMethod {HTTP_METHOD_GET, HTTP_METHOD_POST};
39 
40 class HttpClient {
41 public:
42 	sigc::signal<void, HttpClient*, const char *> on_error_;
43 	sigc::signal<void, HttpClient *> on_response_;
44 
45 	HttpClient();
46 	~HttpClient();
47 	void SendHttpGetRequest(const char* shost, const char* sfile, gpointer data);
48 	void SendHttpGetRequestWithCallback(const char* shost, const char* sfile, get_http_response_func_t callback_func, gpointer data);
49 	void SendHttpRequest(const char* shost, const char* sfile, gpointer data);
SetMethod(HttpMethod httpMethod)50 	void SetMethod(HttpMethod httpMethod)
51 	{
52 		httpMethod_ = httpMethod;
53 	}
SetHeaders(const char * headers)54 	void SetHeaders(const char* headers)
55 	{
56 		headers_ = headers;
57 	}
SetBody(const char * body)58 	void SetBody(const char* body)
59 	{
60 		body_ = body;
61 	}
SetAllowAbsoluteURI(bool b)62 	void SetAllowAbsoluteURI(bool b)
63 	{
64 		allow_absolute_URI_ = b;
65 	}
66 
67 	char *buffer;
68 	size_t buffer_len;
69 	gpointer userdata;
70 	get_http_response_func_t callback_func_;
71 private:
72 	std::string host_;
73 	std::string file_;
74 	HttpMethod httpMethod_;
75 	std::string headers_;
76 	std::string body_;
77 	bool allow_absolute_URI_;
78 	int sd_;
79 	GIOChannel *channel_;
80 	guint in_source_id_;
81 	guint out_source_id_;
82 	static void on_resolved(gpointer data, bool resolved, in_addr_t sa);
83 	static void on_connected(gpointer data, bool succeeded);
84 	static gboolean on_io_in_event(GIOChannel *, GIOCondition, gpointer);
85 	static gboolean on_io_out_event(GIOChannel *, GIOCondition, gpointer);
86 	void disconnect();
87 	void write_str(const char *str, GError **err);
88 	bool SendRequest();
89 };
90 
91 #endif
92