6a68e0eacc0ad31febfe82e859f6b459e248c0e4
[oweals/minetest.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 #include "convert_json.h"
32 #if USE_CURL
33 #include <curl/curl.h>
34 #endif
35
36 namespace ServerList
37 {
38 std::string getFilePath()
39 {
40         std::string serverlist_file = g_settings->get("serverlist_file");
41
42         std::string dir_path = std::string("client") + DIR_DELIM
43                 + "serverlist" + DIR_DELIM;
44         fs::CreateDir(porting::path_user + DIR_DELIM + "client");
45         fs::CreateDir(porting::path_user + DIR_DELIM + dir_path);
46         std::string rel_path = dir_path + serverlist_file;
47         std::string path = porting::path_user + DIR_DELIM + rel_path;
48         return path;
49 }
50
51 std::vector<ServerListSpec> getLocal()
52 {
53         std::string path = ServerList::getFilePath();
54         std::string liststring;
55         if(fs::PathExists(path))
56         {
57                 std::ifstream istream(path.c_str());
58                 if(istream.is_open())
59                 {
60                         std::ostringstream ostream;
61                         ostream << istream.rdbuf();
62                         liststring = ostream.str();
63                         istream.close();
64                 }
65         }
66
67         return ServerList::deSerialize(liststring);
68 }
69
70
71 #if USE_CURL
72 std::vector<ServerListSpec> getOnline()
73 {
74         Json::Value root = fetchJsonValue((g_settings->get("serverlist_url")+"/list").c_str(),0);
75
76         std::vector<ServerListSpec> serverlist;
77
78         if (root.isArray()) {
79                 for (unsigned int i = 0; i < root.size(); i++)
80                 {
81                         if (root[i].isObject()) {
82                                 serverlist.push_back(root[i]);
83                         }
84                 }
85         }
86
87         return serverlist;
88 }
89
90 #endif
91
92 /*
93         Delete a server fromt he local favorites list
94 */
95 bool deleteEntry (ServerListSpec server)
96 {
97         std::vector<ServerListSpec> serverlist = ServerList::getLocal();
98         for(unsigned i = 0; i < serverlist.size(); i++)
99         {
100                 if  (serverlist[i]["address"] == server["address"]
101                 &&   serverlist[i]["port"]    == server["port"])
102                 {
103                         serverlist.erase(serverlist.begin() + i);
104                 }
105         }
106
107         std::string path = ServerList::getFilePath();
108         std::ofstream stream (path.c_str());
109         if (stream.is_open())
110         {
111                 stream<<ServerList::serialize(serverlist);
112                 return true;
113         }
114         return false;
115 }
116
117 /*
118         Insert a server to the local favorites list
119 */
120 bool insert (ServerListSpec server)
121 {
122         // Remove duplicates
123         ServerList::deleteEntry(server);
124
125         std::vector<ServerListSpec> serverlist = ServerList::getLocal();
126
127         // Insert new server at the top of the list
128         serverlist.insert(serverlist.begin(), server);
129
130         std::string path = ServerList::getFilePath();
131         std::ofstream stream (path.c_str());
132         if (stream.is_open())
133         {
134                 stream<<ServerList::serialize(serverlist);
135         }
136
137         return false;
138 }
139
140 std::vector<ServerListSpec> deSerialize(std::string liststring)
141 {
142         std::vector<ServerListSpec> serverlist;
143         std::istringstream stream(liststring);
144         std::string line, tmp;
145         while (std::getline(stream, line))
146         {
147                 std::transform(line.begin(), line.end(),line.begin(), ::toupper);
148                 if (line == "[SERVER]")
149                 {
150                         ServerListSpec thisserver;
151                         std::getline(stream, tmp);
152                         thisserver["name"] = tmp;
153                         std::getline(stream, tmp);
154                         thisserver["address"] = tmp;
155                         std::getline(stream, tmp);
156                         thisserver["port"] = tmp;
157                         std::getline(stream, tmp);
158                         thisserver["description"] = tmp;
159                         serverlist.push_back(thisserver);
160                 }
161         }
162         return serverlist;
163 }
164
165 std::string serialize(std::vector<ServerListSpec> serverlist)
166 {
167         std::string liststring;
168         for(std::vector<ServerListSpec>::iterator i = serverlist.begin(); i != serverlist.end(); i++)
169         {
170                 liststring += "[server]\n";
171                 liststring += (*i)["name"].asString() + "\n";
172                 liststring += (*i)["address"].asString() + "\n";
173                 liststring += (*i)["port"].asString() + "\n";
174                 liststring += (*i)["description"].asString() + "\n";
175                 liststring += "\n";
176         }
177         return liststring;
178 }
179
180 std::string serializeJson(std::vector<ServerListSpec> serverlist)
181 {
182         Json::Value root;
183         Json::Value list(Json::arrayValue);
184         for(std::vector<ServerListSpec>::iterator i = serverlist.begin(); i != serverlist.end(); i++)
185         {
186                 list.append(*i);
187         }
188         root["list"] = list;
189         Json::StyledWriter writer;
190         return writer.write( root );
191 }
192
193
194 #if USE_CURL
195 static size_t ServerAnnounceCallback(void *contents, size_t size, size_t nmemb, void *userp)
196 {
197     return 0;
198     //((std::string*)userp)->append((char*)contents, size * nmemb);
199     //return size * nmemb;
200 }
201 void sendAnnounce(std::string action, u16 clients, double uptime, std::string gameid) {
202         Json::Value server;
203         if (action.size())
204                 server["action"]        = action;
205         server["port"] = g_settings->get("port");
206         if (action != "del") {
207                 server["name"]          = g_settings->get("server_name");
208                 server["description"]   = g_settings->get("server_description");
209                 server["address"]       = g_settings->get("server_address");
210                 server["version"]       = VERSION_STRING;
211                 server["url"]           = g_settings->get("server_url");
212                 server["creative"]      = g_settings->get("creative_mode");
213                 server["damage"]        = g_settings->get("enable_damage");
214                 server["dedicated"]     = g_settings->get("server_dedicated");
215                 server["password"]      = g_settings->getBool("disallow_empty_password");
216                 server["pvp"]           = g_settings->getBool("enable_pvp");
217                 server["clients"]       = clients;
218                 server["clients_max"]   = g_settings->get("max_users");
219                 if (uptime >=1) server["uptime"] = (int)uptime;
220                 if (gameid!="") server["gameid"] = gameid;
221                 
222         }
223         if(server["action"] == "start")
224                 actionstream << "announcing to " << g_settings->get("serverlist_url") << std::endl;
225         Json::StyledWriter writer;
226         CURL *curl;
227         curl = curl_easy_init();
228         if (curl)
229         {
230                 CURLcode res;
231                 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
232                 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());
233                 //curl_easy_setopt(curl, CURLOPT_USERAGENT, "minetest");
234                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ServerList::ServerAnnounceCallback);
235                 //curl_easy_setopt(curl, CURLOPT_WRITEDATA, &liststring);
236                 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);
237                 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1);
238                 res = curl_easy_perform(curl);
239                 //if (res != CURLE_OK)
240                 //      errorstream<<"Serverlist at url "<<g_settings->get("serverlist_url")<<" not found (internet connection?)"<<std::endl;
241                 curl_easy_cleanup(curl);
242         }
243
244 }
245 #endif
246
247 } //namespace ServerList