]> git.lizzy.rs Git - dragonfireclient.git/blob - src/serverlist.cpp
7053436d055e42b7dc2e06e7c93820a567110201
[dragonfireclient.git] / src / serverlist.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <iostream>
21 #include <sstream>
22 #include <algorithm>
23
24 #include "main.h" // for g_settings
25 #include "settings.h"
26 #include "serverlist.h"
27 #include "filesys.h"
28 #include "porting.h"
29 #include "log.h"
30 #include "json/json.h"
31 #if USE_CURL
32 #include <curl/curl.h>
33 #endif
34
35 namespace ServerList
36 {
37 std::string getFilePath()
38 {
39         std::string serverlist_file = g_settings->get("serverlist_file");
40
41         std::string dir_path = std::string("client") + DIR_DELIM
42                 + "serverlist" + DIR_DELIM;
43         fs::CreateDir(porting::path_user + DIR_DELIM + "client");
44         fs::CreateDir(porting::path_user + DIR_DELIM + dir_path);
45         std::string rel_path = dir_path + serverlist_file;
46         std::string path = porting::path_user + DIR_DELIM + rel_path;
47         return path;
48 }
49
50 std::vector<ServerListSpec> getLocal()
51 {
52         std::string path = ServerList::getFilePath();
53         std::string liststring;
54         if(fs::PathExists(path))
55         {
56                 std::ifstream istream(path.c_str(), std::ios::binary);
57                 if(istream.is_open())
58                 {
59                         std::ostringstream ostream;
60                         ostream << istream.rdbuf();
61                         liststring = ostream.str();
62                         istream.close();
63                 }
64         }
65
66         return ServerList::deSerialize(liststring);
67 }
68
69
70 #if USE_CURL
71
72 static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
73 {
74     ((std::string*)userp)->append((char*)contents, size * nmemb);
75     return size * nmemb;
76 }
77
78
79 std::vector<ServerListSpec> getOnline()
80 {
81         std::string liststring;
82         CURL *curl;
83
84         curl = curl_easy_init();
85         if (curl)
86         {
87                 CURLcode res;
88
89                 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
90                 curl_easy_setopt(curl, CURLOPT_URL, (g_settings->get("serverlist_url")+"/list").c_str());
91                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ServerList::WriteCallback);
92                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &liststring);
93
94                 res = curl_easy_perform(curl);
95                 if (res != CURLE_OK)
96                         errorstream<<"Serverlist at url "<<g_settings->get("serverlist_url")<<" not found (internet connection?)"<<std::endl;
97                 curl_easy_cleanup(curl);
98         }
99         return ServerList::deSerializeJson(liststring);
100 }
101
102 #endif
103
104 /*
105         Delete a server fromt he local favorites list
106 */
107 bool deleteEntry (ServerListSpec server)
108 {
109         std::vector<ServerListSpec> serverlist = ServerList::getLocal();
110         for(unsigned i = 0; i < serverlist.size(); i++)
111         {
112                 if  (serverlist[i]["address"] == server["address"]
113                 &&   serverlist[i]["port"]    == server["port"])
114                 {
115                         serverlist.erase(serverlist.begin() + i);
116                 }
117         }
118
119         std::string path = ServerList::getFilePath();
120         std::ofstream stream (path.c_str());
121         if (stream.is_open())
122         {
123                 stream<<ServerList::serialize(serverlist);
124                 return true;
125         }
126         return false;
127 }
128
129 /*
130         Insert a server to the local favorites list
131 */
132 bool insert (ServerListSpec server)
133 {
134         // Remove duplicates
135         ServerList::deleteEntry(server);
136
137         std::vector<ServerListSpec> serverlist = ServerList::getLocal();
138
139         // Insert new server at the top of the list
140         serverlist.insert(serverlist.begin(), server);
141
142         std::string path = ServerList::getFilePath();
143         std::ofstream stream (path.c_str());
144         if (stream.is_open())
145         {
146                 stream<<ServerList::serialize(serverlist);
147         }
148
149         return false;
150 }
151
152 std::vector<ServerListSpec> deSerialize(std::string liststring)
153 {
154         std::vector<ServerListSpec> serverlist;
155         std::istringstream stream(liststring);
156         std::string line, tmp;
157         while (std::getline(stream, line))
158         {
159                 std::transform(line.begin(), line.end(),line.begin(), ::toupper);
160                 if (line == "[SERVER]")
161                 {
162                         ServerListSpec thisserver;
163                         std::getline(stream, tmp);
164                         thisserver["name"] = tmp;
165                         std::getline(stream, tmp);
166                         thisserver["address"] = tmp;
167                         std::getline(stream, tmp);
168                         thisserver["port"] = tmp;
169                         std::getline(stream, tmp);
170                         thisserver["description"] = tmp;
171                         serverlist.push_back(thisserver);
172                 }
173         }
174         return serverlist;
175 }
176
177 std::string serialize(std::vector<ServerListSpec> serverlist)
178 {
179         std::string liststring;
180         for(std::vector<ServerListSpec>::iterator i = serverlist.begin(); i != serverlist.end(); i++)
181         {
182                 liststring += "[server]\n";
183                 liststring += (*i)["name"].asString() + "\n";
184                 liststring += (*i)["address"].asString() + "\n";
185                 liststring += (*i)["port"].asString() + "\n";
186                 liststring += (*i)["description"].asString() + "\n";
187                 liststring += "\n";
188         }
189         return liststring;
190 }
191
192 std::vector<ServerListSpec> deSerializeJson(std::string liststring)
193 {
194         std::vector<ServerListSpec> serverlist;
195         Json::Value root;
196         Json::Reader reader;
197         std::istringstream stream(liststring);
198         if (!liststring.size()) {
199                 return serverlist;
200         }
201         if (!reader.parse( stream, root ) )
202         {
203                 errorstream  << "Failed to parse server list " << reader.getFormattedErrorMessages();
204                 return serverlist;
205         }
206         if (root["list"].isArray())
207             for (unsigned int i = 0; i < root["list"].size(); i++)
208         {
209                 if (root["list"][i].isObject()) {
210                         serverlist.push_back(root["list"][i]);
211                 }
212         }
213         return serverlist;
214 }
215
216 std::string serializeJson(std::vector<ServerListSpec> serverlist)
217 {
218         Json::Value root;
219         Json::Value list(Json::arrayValue);
220         for(std::vector<ServerListSpec>::iterator i = serverlist.begin(); i != serverlist.end(); i++)
221         {
222                 list.append(*i);
223         }
224         root["list"] = list;
225         Json::StyledWriter writer;
226         return writer.write( root );
227 }
228
229
230 #if USE_CURL
231 static size_t ServerAnnounceCallback(void *contents, size_t size, size_t nmemb, void *userp)
232 {
233     return 0;
234     //((std::string*)userp)->append((char*)contents, size * nmemb);
235     //return size * nmemb;
236 }
237 void sendAnnounce(std::string action, u16 clients, double uptime, std::string gameid) {
238         Json::Value server;
239         if (action.size())
240                 server["action"]        = action;
241         server["port"] = g_settings->get("port");
242         if (action != "del") {
243                 server["name"]          = g_settings->get("server_name");
244                 server["description"]   = g_settings->get("server_description");
245                 server["address"]       = g_settings->get("server_address");
246                 server["version"]       = VERSION_STRING;
247                 server["url"]           = g_settings->get("server_url");
248                 server["creative"]      = g_settings->get("creative_mode");
249                 server["damage"]        = g_settings->get("enable_damage");
250                 server["dedicated"]     = g_settings->get("server_dedicated");
251                 server["password"]      = g_settings->getBool("disallow_empty_password");
252                 server["pvp"]           = g_settings->getBool("enable_pvp");
253                 server["clients"]       = clients;
254                 server["clients_max"]   = g_settings->get("max_users");
255                 if (uptime >=1) server["uptime"] = (int)uptime;
256                 if (gameid!="") server["gameid"] = gameid;
257                 
258         }
259         if(server["action"] == "start")
260                 actionstream << "announcing to " << g_settings->get("serverlist_url") << std::endl;
261         Json::StyledWriter writer;
262         CURL *curl;
263         curl = curl_easy_init();
264         if (curl)
265         {
266                 CURLcode res;
267                 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
268                 curl_easy_setopt(curl, CURLOPT_URL, (g_settings->get("serverlist_url")+std::string("/announce?json=")+curl_easy_escape(curl, writer.write( server ).c_str(), 0)).c_str());
269                 //curl_easy_setopt(curl, CURLOPT_USERAGENT, "minetest");
270                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ServerList::ServerAnnounceCallback);
271                 //curl_easy_setopt(curl, CURLOPT_WRITEDATA, &liststring);
272                 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);
273                 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1);
274                 res = curl_easy_perform(curl);
275                 //if (res != CURLE_OK)
276                 //      errorstream<<"Serverlist at url "<<g_settings->get("serverlist_url")<<" not found (internet connection?)"<<std::endl;
277                 curl_easy_cleanup(curl);
278         }
279
280 }
281 #endif
282
283 } //namespace ServerList