]> git.stg.codes - stg.git/blob - projects/sgconf/users.cpp
e9be65a608b9df6815a069fd020079107fcaadb0
[stg.git] / projects / sgconf / users.cpp
1 #include "users.h"
2
3 #include "api_action.h"
4 #include "options.h"
5 #include "config.h"
6 #include "utils.h"
7
8 #include "stg/servconf.h"
9 #include "stg/servconf_types.h"
10 #include "stg/user_conf.h"
11 #include "stg/user_stat.h"
12 #include "stg/user_ips.h"
13 #include "stg/common.h"
14
15 #include <iostream>
16 #include <algorithm>
17 #include <string>
18 #include <map>
19
20 namespace
21 {
22
23 std::string Indent(size_t level, bool dash = false)
24 {
25 if (level == 0)
26     return "";
27 return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' ');
28 }
29
30 void PrintUser(const STG::GET_USER::INFO & info, size_t level = 0)
31 {
32 std::cout << Indent(level, true) << "login: " << info.login << "\n"
33           << Indent(level)       << "password: " << info.password << "\n"
34           << Indent(level)       << "cash: " << info.cash << "\n"
35           << Indent(level)       << "credit: " << info.credit << "\n"
36           << Indent(level)       << "credit expire: " << TimeToString(info.creditExpire) << "\n"
37           << Indent(level)       << "last cash add: " << info.lastCashAdd << "\n"
38           << Indent(level)       << "last cash add time: " << TimeToString(info.lastCashAddTime) << "\n"
39           << Indent(level)       << "prepaid traffic: " << info.prepaidTraff << "\n"
40           << Indent(level)       << "disabled: " << (info.disabled ? "t" : "f") << "\n"
41           << Indent(level)       << "passive: " << (info.passive ? "t" : "f") << "\n"
42           << Indent(level)       << "disabled detail stat: " << (info.disableDetailStat ? "t" : "f") << "\n"
43           << Indent(level)       << "connected: " << (info.connected ? "t" : "f") << "\n"
44           << Indent(level)       << "always on-line: " << (info.alwaysOnline ? "t" : "f") << "\n"
45           << Indent(level)       << "IP: " << inet_ntostring(info.ip) << "\n"
46           << Indent(level)       << "IPs: " << info.ips << "\n"
47           << Indent(level)       << "tariff: " << info.tariff << "\n"
48           << Indent(level)       << "group: " << info.group << "\n"
49           << Indent(level)       << "note: " << info.note << "\n"
50           << Indent(level)       << "email: " << info.email << "\n"
51           << Indent(level)       << "name: " << info.name << "\n"
52           << Indent(level)       << "address: " << info.address << "\n"
53           << Indent(level)       << "phone: " << info.phone << "\n"
54           << Indent(level)       << "corporation: " << info.corp << "\n"
55           << Indent(level)       << "last ping time: " << TimeToString(info.pingTime) << "\n"
56           << Indent(level)       << "last activity time: " << TimeToString(info.lastActivityTime) << "\n"
57           << Indent(level)       << "traffic:\n";
58 for (size_t i = 0; i < DIR_NUM; ++i)
59     {
60     std::cout << Indent(level + 1, true) << "dir: " << i << "\n"
61               << Indent(level + 1)       << "session upload: " << info.stat.su[i] << "\n"
62               << Indent(level + 1)       << "session download: " << info.stat.sd[i] << "\n"
63               << Indent(level + 1)       << "month upload: " << info.stat.mu[i] << "\n"
64               << Indent(level + 1)       << "month download: " << info.stat.md[i] << "\n";
65     }
66 std::cout << Indent(level)       << "user data:\n";
67 for (size_t i = 0; i < USERDATA_NUM; ++i)
68     std::cout << Indent(level + 1, true) << "user data " << i << ": " << info.userData[i] << "\n";
69 if (!info.services.empty())
70     {
71     std::cout << Indent(level) << "services:\n";
72     for (size_t i = 0; i < info.services.size(); ++i)
73         std::cout << Indent(level + 1, true) << info.services[i] << "\n";
74     }
75 if (!info.authBy.empty())
76     {
77     std::cout << Indent(level) << "auth by:\n";
78     for (size_t i = 0; i < info.authBy.size(); ++i)
79         std::cout << Indent(level + 1, true) << info.authBy[i] << "\n";
80     }
81 }
82
83 std::vector<SGCONF::API_ACTION::PARAM> GetUserParams()
84 {
85 std::vector<SGCONF::API_ACTION::PARAM> params;
86 params.push_back(SGCONF::API_ACTION::PARAM("password", "<password>", "\tuser's password"));
87 params.push_back(SGCONF::API_ACTION::PARAM("cash-add", "<cash[:message]>", "cash to add (with optional comment)"));
88 params.push_back(SGCONF::API_ACTION::PARAM("cash-set", "<cash[:message]>", "cash to set (with optional comment)"));
89 params.push_back(SGCONF::API_ACTION::PARAM("credit", "<amount>", "\tuser's credit"));
90 params.push_back(SGCONF::API_ACTION::PARAM("credit-expire", "<date>", "\tcredit expiration"));
91 params.push_back(SGCONF::API_ACTION::PARAM("free", "<free mb>", "\tprepaid traffic"));
92 params.push_back(SGCONF::API_ACTION::PARAM("disabled", "<flag>", "\tdisable user (y|n)"));
93 params.push_back(SGCONF::API_ACTION::PARAM("passive", "<flag>", "\tmake user passive (y|n)"));
94 params.push_back(SGCONF::API_ACTION::PARAM("disable-detail-stat", "<flag>", "disable detail stat (y|n)"));
95 params.push_back(SGCONF::API_ACTION::PARAM("always-online", "<flag>", "\tmake user always online (y|n)"));
96 params.push_back(SGCONF::API_ACTION::PARAM("ips", "<ips>", "\t\tcoma-separated list of ips"));
97 params.push_back(SGCONF::API_ACTION::PARAM("tariff", "<tariff name>", "\tcurrent tariff"));
98 params.push_back(SGCONF::API_ACTION::PARAM("next-tariff", "<tariff name>", "tariff starting from the next month"));
99 params.push_back(SGCONF::API_ACTION::PARAM("group", "<group>", "\t\tuser's group"));
100 params.push_back(SGCONF::API_ACTION::PARAM("note", "<note>", "\t\tuser's note"));
101 params.push_back(SGCONF::API_ACTION::PARAM("email", "<email>", "\t\tuser's email"));
102 params.push_back(SGCONF::API_ACTION::PARAM("name", "<real name>", "\tuser's real name"));
103 params.push_back(SGCONF::API_ACTION::PARAM("address", "<address>", "\tuser's postal address"));
104 params.push_back(SGCONF::API_ACTION::PARAM("phone", "<phone>", "\t\tuser's phone number"));
105 params.push_back(SGCONF::API_ACTION::PARAM("corp", "<corp name>", "\tcorporation name"));
106 params.push_back(SGCONF::API_ACTION::PARAM("session-traffic", "<up/dn, ...>", "coma-separated session upload and download"));
107 params.push_back(SGCONF::API_ACTION::PARAM("month-traffic", "<up/dn, ...>", "coma-separated month upload and download"));
108 params.push_back(SGCONF::API_ACTION::PARAM("user-data", "<value, ...>", "coma-separated user data values"));
109 return params;
110 }
111
112 std::vector<SGCONF::API_ACTION::PARAM> GetCheckParams()
113 {
114 std::vector<SGCONF::API_ACTION::PARAM> params;
115 params.push_back(SGCONF::API_ACTION::PARAM("password", "<password>", "\tuser's password"));
116 return params;
117 }
118
119 std::vector<SGCONF::API_ACTION::PARAM> GetMessageParams()
120 {
121 std::vector<SGCONF::API_ACTION::PARAM> params;
122 params.push_back(SGCONF::API_ACTION::PARAM("logins", "<login, ...>", "\tlist of logins to send a message"));
123 params.push_back(SGCONF::API_ACTION::PARAM("text", "<text>", "\t\tmessage text"));
124 return params;
125 }
126
127 void ConvBool(const std::string & value, RESETABLE<int> & res)
128 {
129 res = !value.empty() && value[0] == 'y';
130 }
131
132 void Splice(std::vector<RESETABLE<std::string> > & lhs, const std::vector<RESETABLE<std::string> > & rhs)
133 {
134 for (size_t i = 0; i < lhs.size(); ++i)
135     lhs[i].splice(rhs[i]);
136 }
137
138 RESETABLE<std::string> ConvString(const std::string & value)
139 {
140 return value;
141 }
142
143 void ConvStringList(std::string value, std::vector<RESETABLE<std::string> > & res)
144 {
145 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
146 Splice(res, Split<std::vector<RESETABLE<std::string> > >(value, ',', ConvString));
147 }
148
149 void ConvServices(std::string value, RESETABLE<std::vector<std::string> > & res)
150 {
151 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
152 res = Split<std::vector<std::string> >(value, ',');
153 }
154
155 void ConvCreditExpire(const std::string & value, RESETABLE<time_t> & res)
156 {
157 struct tm brokenTime;
158 if (stg_strptime(value.c_str(), "%Y-%m-%d %H:%M:%S", &brokenTime) == NULL)
159     throw SGCONF::ACTION::ERROR("Credit expiration should be in format 'YYYY-MM-DD HH:MM:SS'. Got: '" + value + "'");
160 res = stg_timegm(&brokenTime);
161 }
162
163 void ConvIPs(const std::string & value, RESETABLE<USER_IPS> & res)
164 {
165 res = StrToIPS(value);
166 }
167
168 struct TRAFF
169 {
170     uint64_t up;
171     uint64_t down;
172 };
173
174 TRAFF ConvTraff(const std::string & value)
175 {
176 TRAFF res;
177 size_t slashPos = value.find_first_of('/');
178 if (slashPos == std::string::npos)
179     throw SGCONF::ACTION::ERROR("Traffic record should be in format 'upload/download'. Got: '" + value + "'");
180
181 if (str2x(value.substr(0, slashPos), res.up) < 0)
182     throw SGCONF::ACTION::ERROR("Traffic value should be an integer. Got: '" + value.substr(0, slashPos) + "'");
183 if (str2x(value.substr(slashPos + 1, value.length() - slashPos), res.down) < 0)
184     throw SGCONF::ACTION::ERROR("Traffic value should be an integer. Got: '" + value.substr(slashPos + 1, value.length() - slashPos) + "'");
185 return res;
186 }
187
188 void ConvSessionTraff(std::string value, USER_STAT_RES & res)
189 {
190 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
191 std::vector<TRAFF> traff(Split<std::vector<TRAFF> >(value, ',', ConvTraff));
192 if (traff.size() != DIR_NUM)
193     throw SGCONF::ACTION::ERROR("There should be prcisely " + x2str(DIR_NUM) + " records of session traffic.");
194 for (size_t i = 0; i < DIR_NUM; ++i)
195     {
196     res.sessionUp[i] = traff[i].up;
197     res.sessionDown[i] = traff[i].down;
198     }
199 }
200
201 void ConvMonthTraff(std::string value, USER_STAT_RES & res)
202 {
203 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
204 std::vector<TRAFF> traff(Split<std::vector<TRAFF> >(value, ',', ConvTraff));
205 if (traff.size() != DIR_NUM)
206     throw SGCONF::ACTION::ERROR("There should be prcisely " + x2str(DIR_NUM) + " records of month traffic.");
207 for (size_t i = 0; i < DIR_NUM; ++i)
208     {
209     res.monthUp[i] = traff[i].up;
210     res.monthDown[i] = traff[i].down;
211     }
212 }
213
214 void ConvCashInfo(const std::string & value, RESETABLE<CASH_INFO> & res)
215 {
216 CASH_INFO info;
217 size_t pos = value.find_first_of(':');
218 if (pos == std::string::npos)
219     {
220     if (str2x(value, info.first) < 0)
221         throw SGCONF::ACTION::ERROR("Cash should be a double value. Got: '" + value + "'");
222     }
223 else
224     {
225     if (str2x(value.substr(0, pos), info.first) < 0)
226         throw SGCONF::ACTION::ERROR("Cash should be a double value. Got: '" + value + "'");
227     info.second = value.substr(pos + 1);
228     }
229 res = info;
230 }
231
232 void SimpleCallback(bool result,
233                     const std::string & reason,
234                     void * /*data*/)
235 {
236 if (!result)
237     {
238     std::cerr << "Operation failed. Reason: '" << reason << "'." << std::endl;
239     return;
240     }
241 std::cout << "Success.\n";
242 }
243
244 void GetUsersCallback(bool result,
245                       const std::string & reason,
246                       const std::vector<STG::GET_USER::INFO> & info,
247                       void * /*data*/)
248 {
249 if (!result)
250     {
251     std::cerr << "Failed to get user list. Reason: '" << reason << "'." << std::endl;
252     return;
253     }
254 std::cout << "Users:\n";
255 for (size_t i = 0; i < info.size(); ++i)
256     PrintUser(info[i], 1);
257 }
258
259 void GetUserCallback(bool result,
260                      const std::string & reason,
261                      const STG::GET_USER::INFO & info,
262                      void * /*data*/)
263 {
264 if (!result)
265     {
266     std::cerr << "Failed to get user. Reason: '" << reason << "'." << std::endl;
267     return;
268     }
269 PrintUser(info);
270 }
271
272 bool GetUsersFunction(const SGCONF::CONFIG & config,
273                       const std::string & /*arg*/,
274                       const std::map<std::string, std::string> & /*options*/)
275 {
276 STG::SERVCONF proto(config.server.data(),
277                     config.port.data(),
278                     config.userName.data(),
279                     config.userPass.data());
280 return proto.GetUsers(GetUsersCallback, NULL) == STG::st_ok;
281 }
282
283 bool GetUserFunction(const SGCONF::CONFIG & config,
284                      const std::string & arg,
285                      const std::map<std::string, std::string> & /*options*/)
286 {
287 STG::SERVCONF proto(config.server.data(),
288                     config.port.data(),
289                     config.userName.data(),
290                     config.userPass.data());
291 return proto.GetUser(arg, GetUserCallback, NULL) == STG::st_ok;
292 }
293
294 bool DelUserFunction(const SGCONF::CONFIG & config,
295                      const std::string & arg,
296                      const std::map<std::string, std::string> & /*options*/)
297 {
298 STG::SERVCONF proto(config.server.data(),
299                     config.port.data(),
300                     config.userName.data(),
301                     config.userPass.data());
302 return proto.DelUser(arg, SimpleCallback, NULL) == STG::st_ok;
303 }
304
305 bool AddUserFunction(const SGCONF::CONFIG & config,
306                      const std::string & arg,
307                      const std::map<std::string, std::string> & options)
308 {
309 USER_CONF_RES conf;
310 SGCONF::MaybeSet(options, "password", conf.password);
311 SGCONF::MaybeSet(options, "passive", conf.passive, ConvBool);
312 SGCONF::MaybeSet(options, "disabled", conf.disabled, ConvBool);
313 SGCONF::MaybeSet(options, "disable-detail-stat", conf.disabledDetailStat, ConvBool);
314 SGCONF::MaybeSet(options, "always-online", conf.alwaysOnline, ConvBool);
315 SGCONF::MaybeSet(options, "tariff", conf.tariffName);
316 SGCONF::MaybeSet(options, "address", conf.address);
317 SGCONF::MaybeSet(options, "phone", conf.phone);
318 SGCONF::MaybeSet(options, "email", conf.email);
319 SGCONF::MaybeSet(options, "note", conf.note);
320 SGCONF::MaybeSet(options, "name", conf.realName);
321 SGCONF::MaybeSet(options, "corp", conf.corp);
322 SGCONF::MaybeSet(options, "services", conf.services, ConvServices);
323 SGCONF::MaybeSet(options, "group", conf.group);
324 SGCONF::MaybeSet(options, "credit", conf.credit);
325 SGCONF::MaybeSet(options, "next-tariff", conf.nextTariff);
326 SGCONF::MaybeSet(options, "user-data", conf.userdata, ConvStringList);
327 SGCONF::MaybeSet(options, "credit-expire", conf.creditExpire, ConvCreditExpire);
328 SGCONF::MaybeSet(options, "ips", conf.ips, ConvIPs);
329 USER_STAT_RES stat;
330 SGCONF::MaybeSet(options, "cash-set", stat.cashSet, ConvCashInfo);
331 SGCONF::MaybeSet(options, "free", stat.freeMb);
332 SGCONF::MaybeSet(options, "session-traffic", stat, ConvSessionTraff);
333 SGCONF::MaybeSet(options, "month-traffic", stat, ConvMonthTraff);
334 STG::SERVCONF proto(config.server.data(),
335                     config.port.data(),
336                     config.userName.data(),
337                     config.userPass.data());
338 return proto.AddUser(arg, conf, stat, SimpleCallback, NULL) == STG::st_ok;
339 }
340
341 bool ChgUserFunction(const SGCONF::CONFIG & config,
342                      const std::string & arg,
343                      const std::map<std::string, std::string> & options)
344 {
345 USER_CONF_RES conf;
346 SGCONF::MaybeSet(options, "password", conf.password);
347 SGCONF::MaybeSet(options, "passive", conf.passive, ConvBool);
348 SGCONF::MaybeSet(options, "disabled", conf.disabled, ConvBool);
349 SGCONF::MaybeSet(options, "disable-detail-stat", conf.disabledDetailStat, ConvBool);
350 SGCONF::MaybeSet(options, "always-online", conf.alwaysOnline, ConvBool);
351 SGCONF::MaybeSet(options, "tariff", conf.tariffName);
352 SGCONF::MaybeSet(options, "address", conf.address);
353 SGCONF::MaybeSet(options, "phone", conf.phone);
354 SGCONF::MaybeSet(options, "email", conf.email);
355 SGCONF::MaybeSet(options, "note", conf.note);
356 SGCONF::MaybeSet(options, "name", conf.realName);
357 SGCONF::MaybeSet(options, "corp", conf.corp);
358 SGCONF::MaybeSet(options, "services", conf.services, ConvServices);
359 SGCONF::MaybeSet(options, "group", conf.group);
360 SGCONF::MaybeSet(options, "credit", conf.credit);
361 SGCONF::MaybeSet(options, "next-tariff", conf.nextTariff);
362 SGCONF::MaybeSet(options, "user-data", conf.userdata, ConvStringList);
363 SGCONF::MaybeSet(options, "credit-expire", conf.creditExpire, ConvCreditExpire);
364 SGCONF::MaybeSet(options, "ips", conf.ips, ConvIPs);
365 USER_STAT_RES stat;
366 SGCONF::MaybeSet(options, "cash-add", stat.cashAdd, ConvCashInfo);
367 SGCONF::MaybeSet(options, "cash-set", stat.cashSet, ConvCashInfo);
368 SGCONF::MaybeSet(options, "free", stat.freeMb);
369 SGCONF::MaybeSet(options, "session-traffic", stat, ConvSessionTraff);
370 SGCONF::MaybeSet(options, "month-traffic", stat, ConvMonthTraff);
371 STG::SERVCONF proto(config.server.data(),
372                     config.port.data(),
373                     config.userName.data(),
374                     config.userPass.data());
375 return proto.ChgUser(arg, conf, stat, SimpleCallback, NULL) == STG::st_ok;
376 }
377
378 bool CheckUserFunction(const SGCONF::CONFIG & config,
379                        const std::string & arg,
380                        const std::map<std::string, std::string> & options)
381 {
382 std::map<std::string, std::string>::const_iterator it(options.find("password"));
383 if (it == options.end())
384     throw SGCONF::ACTION::ERROR("Password is not specified.");
385 STG::SERVCONF proto(config.server.data(),
386                     config.port.data(),
387                     config.userName.data(),
388                     config.userPass.data());
389 return proto.CheckUser(arg, it->second, SimpleCallback, NULL) == STG::st_ok;
390 }
391
392 bool SendMessageFunction(const SGCONF::CONFIG & config,
393                          const std::string & /*arg*/,
394                          const std::map<std::string, std::string> & options)
395 {
396 std::map<std::string, std::string>::const_iterator it(options.find("logins"));
397 if (it == options.end())
398     throw SGCONF::ACTION::ERROR("Logins are not specified.");
399 std::string logins = it->second;
400 for (size_t i = 0; i < logins.length(); ++i)
401     if (logins[i] == ',')
402         logins[i] = ':';
403 it = options.find("text");
404 if (it == options.end())
405     throw SGCONF::ACTION::ERROR("Message text is not specified.");
406 std::string text = it->second;
407 STG::SERVCONF proto(config.server.data(),
408                     config.port.data(),
409                     config.userName.data(),
410                     config.userPass.data());
411 return proto.SendMessage(logins, text, SimpleCallback, NULL) == STG::st_ok;
412 }
413
414 } // namespace anonymous
415
416 void SGCONF::AppendUsersOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks)
417 {
418 std::vector<API_ACTION::PARAM> params(GetUserParams());
419 blocks.Add("User management options")
420       .Add("get-users", SGCONF::MakeAPIAction(commands, GetUsersFunction), "\tget user list")
421       .Add("get-user", SGCONF::MakeAPIAction(commands, "<login>", GetUserFunction), "get user")
422       .Add("add-user", SGCONF::MakeAPIAction(commands, "<login>", params, AddUserFunction), "add user")
423       .Add("del-user", SGCONF::MakeAPIAction(commands, "<login>", DelUserFunction), "del user")
424       .Add("chg-user", SGCONF::MakeAPIAction(commands, "<login>", params, ChgUserFunction), "change user")
425       .Add("check-user", SGCONF::MakeAPIAction(commands, "<login>", GetCheckParams(), CheckUserFunction), "check user existance and credentials")
426       .Add("send-message", SGCONF::MakeAPIAction(commands, GetMessageParams(), SendMessageFunction), "send message");
427 }