]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/playerstats.qc
Merge branch 'master' into Mario/vaporizer_damage
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / playerstats.qc
1 #if defined(CSQC)
2 #elif defined(MENUQC)
3 #elif defined(SVQC)
4         #include "../dpdefs/progsdefs.qh"
5     #include "../dpdefs/dpextensions.qh"
6     #include "constants.qh"
7     #include "util.qh"
8     #include "weapons/all.qh"
9     #include "../server/weapons/accuracy.qh"
10     #include "../server/defs.qh"
11     #include "playerstats.qh"
12     #include "../server/scores.qh"
13 #endif
14
15 #ifdef SVQC
16 void PlayerStats_Prematch(void)
17 {
18         //foobar
19 }
20
21 void PlayerStats_GameReport_AddPlayer(entity e)
22 {
23         if((PS_GR_OUT_DB < 0) || (e.playerstats_id)) { return; }
24
25         // set up player identification
26         string s = string_null;
27
28         if((e.crypto_idfp != "") && (e.cvar_cl_allow_uidtracking == 1))
29                 { s = e.crypto_idfp; }
30         else if(IS_BOT_CLIENT(e))
31                 { s = sprintf("bot#%g#%s", skill, e.cleanname); }
32
33         if((s == "") || find(world, playerstats_id, s)) // already have one of the ID - next one can't be tracked then!
34         {
35                 if(IS_BOT_CLIENT(e))
36                         { s = sprintf("bot#%d", e.playerid); }
37                 else
38                         { s = sprintf("player#%d", e.playerid); }
39         }
40
41         e.playerstats_id = strzone(s);
42
43         // now add the player to the database
44         string key = sprintf("%s:*", e.playerstats_id);
45         string p = db_get(PS_GR_OUT_DB, key);
46
47         if(p == "")
48         {
49                 if(PS_GR_OUT_PL)
50                 {
51                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_PL);
52                         strunzone(PS_GR_OUT_PL);
53                 }
54                 else { db_put(PS_GR_OUT_DB, key, "#"); }
55                 PS_GR_OUT_PL = strzone(e.playerstats_id);
56         }
57 }
58
59 void PlayerStats_GameReport_AddTeam(float t)
60 {
61         if(PS_GR_OUT_DB < 0) { return; }
62
63         string key = sprintf("%d", t);
64         string p = db_get(PS_GR_OUT_DB, key);
65
66         if(p == "")
67         {
68                 if(PS_GR_OUT_TL)
69                 {
70                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_TL);
71                         strunzone(PS_GR_OUT_TL);
72                 }
73                 else { db_put(PS_GR_OUT_DB, key, "#"); }
74                 PS_GR_OUT_TL = strzone(key);
75         }
76 }
77
78 void PlayerStats_GameReport_AddEvent(string event_id)
79 {
80         if(PS_GR_OUT_DB < 0) { return; }
81
82         string key = sprintf("*:%s", event_id);
83         string p = db_get(PS_GR_OUT_DB, key);
84
85         if(p == "")
86         {
87                 if(PS_GR_OUT_EVL)
88                 {
89                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_EVL);
90                         strunzone(PS_GR_OUT_EVL);
91                 }
92                 else { db_put(PS_GR_OUT_DB, key, "#"); }
93                 PS_GR_OUT_EVL = strzone(event_id);
94         }
95 }
96
97 // referred to by PS_GR_P_ADDVAL and PS_GR_T_ADDVAL
98 float PlayerStats_GameReport_Event(string prefix, string event_id, float value)
99 {
100         if((prefix == "") || PS_GR_OUT_DB < 0) { return 0; }
101
102         string key = sprintf("%s:%s", prefix, event_id);
103         float val = stof(db_get(PS_GR_OUT_DB, key));
104         val += value;
105         db_put(PS_GR_OUT_DB, key, ftos(val));
106         return val;
107 }
108
109 void PlayerStats_GameReport_Accuracy(entity p)
110 {
111         int i;
112
113         for(i = WEP_FIRST; i <= WEP_LAST; ++i)
114         {
115                 entity w = get_weaponinfo(i);
116
117                 #define ACCMAC(suffix,field) \
118                         PS_GR_P_ADDVAL(p, sprintf("acc-%s-%s", w.netname, suffix), p.accuracy.(field[i-1]));
119
120                 ACCMAC("hit", accuracy_hit)
121                 ACCMAC("fired", accuracy_fired)
122                 ACCMAC("cnt-hit", accuracy_cnt_hit)
123                 ACCMAC("cnt-fired", accuracy_cnt_fired)
124                 ACCMAC("frags", accuracy_frags)
125
126                 #undef ACCMAC
127         }
128 }
129
130 void PlayerStats_GameReport_FinalizePlayer(entity p)
131 {
132         if((p.playerstats_id == "") || PS_GR_OUT_DB < 0) { return; }
133
134         // add global info!
135         if(p.alivetime)
136         {
137                 PS_GR_P_ADDVAL(p, PLAYERSTATS_ALIVETIME, time - p.alivetime);
138                 p.alivetime = 0;
139         }
140
141         db_put(PS_GR_OUT_DB, sprintf("%s:_playerid", p.playerstats_id), ftos(p.playerid));
142
143         if(p.cvar_cl_allow_uid2name == 1 || IS_BOT_CLIENT(p))
144                 db_put(PS_GR_OUT_DB, sprintf("%s:_netname", p.playerstats_id), p.netname);
145
146         if(teamplay)
147                 db_put(PS_GR_OUT_DB, sprintf("%s:_team", p.playerstats_id), ftos(p.team));
148
149         if(stof(db_get(PS_GR_OUT_DB, sprintf("%s:%s", p.playerstats_id, PLAYERSTATS_ALIVETIME))) > 0)
150                 PS_GR_P_ADDVAL(p, PLAYERSTATS_JOINS, 1);
151
152         PlayerStats_GameReport_Accuracy(p);
153
154         if(IS_REAL_CLIENT(p))
155         {
156                 if(p.latency_cnt)
157                 {
158                         float latency = (p.latency_sum / p.latency_cnt);
159                         if(latency) { PS_GR_P_ADDVAL(p, PLAYERSTATS_AVGLATENCY, latency); }
160                 }
161         }
162
163         strunzone(p.playerstats_id);
164         p.playerstats_id = string_null;
165 }
166
167 void PlayerStats_GameReport(float finished)
168 {
169         if(PS_GR_OUT_DB < 0) { return; }
170
171         PlayerScore_Sort(score_dummyfield, 0, 0, 0);
172         PlayerScore_Sort(scoreboard_pos, 1, 1, 1);
173         if(teamplay) { PlayerScore_TeamStats(); }
174
175         entity p;
176         FOR_EACH_CLIENT(p)
177         {
178                 // add personal score rank
179                 PS_GR_P_ADDVAL(p, PLAYERSTATS_RANK, p.score_dummyfield);
180
181                 // scoreboard data
182                 if(p.scoreboard_pos)
183                 {
184                         // scoreboard is valid!
185                         PS_GR_P_ADDVAL(p, PLAYERSTATS_SCOREBOARD_VALID, 1);
186
187                         // add scoreboard position
188                         PS_GR_P_ADDVAL(p, PLAYERSTATS_SCOREBOARD_POS, p.scoreboard_pos);
189
190                         // add scoreboard data
191                         PlayerScore_PlayerStats(p);
192
193                         // if the match ended normally, add winning info
194                         if(finished)
195                         {
196                                 PS_GR_P_ADDVAL(p, PLAYERSTATS_WINS, p.winning);
197                                 PS_GR_P_ADDVAL(p, PLAYERSTATS_MATCHES, 1);
198                         }
199                 }
200
201                 // collect final player information
202                 PlayerStats_GameReport_FinalizePlayer(p);
203         }
204
205         if(autocvar_g_playerstats_gamereport_uri != "")
206         {
207                 PlayerStats_GameReport_DelayMapVote = true;
208                 url_multi_fopen(
209                         autocvar_g_playerstats_gamereport_uri,
210                         FILE_APPEND,
211                         PlayerStats_GameReport_Handler,
212                         world
213                 );
214         }
215         else
216         {
217                 PlayerStats_GameReport_DelayMapVote = false;
218                 db_close(PS_GR_OUT_DB);
219                 PS_GR_OUT_DB = -1;
220         }
221 }
222
223 void PlayerStats_GameReport_Init() // initiated before InitGameplayMode so that scores are added properly
224 {
225         if(autocvar_g_playerstats_gamereport_uri == "") { return; }
226
227         PS_GR_OUT_DB = db_create();
228
229         if(PS_GR_OUT_DB >= 0)
230         {
231                 PlayerStats_GameReport_DelayMapVote = true;
232
233                 serverflags |= SERVERFLAG_PLAYERSTATS;
234
235                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ALIVETIME);
236                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_AVGLATENCY);
237                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_WINS);
238                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_MATCHES);
239                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_JOINS);
240                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_SCOREBOARD_VALID);
241                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_SCOREBOARD_POS);
242                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_RANK);
243
244                 // accuracy stats
245                 entity w;
246                 float i;
247                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
248                 {
249                         w = get_weaponinfo(i);
250                         PlayerStats_GameReport_AddEvent(strcat("acc-", w.netname, "-hit"));
251                         PlayerStats_GameReport_AddEvent(strcat("acc-", w.netname, "-fired"));
252                         PlayerStats_GameReport_AddEvent(strcat("acc-", w.netname, "-cnt-hit"));
253                         PlayerStats_GameReport_AddEvent(strcat("acc-", w.netname, "-cnt-fired"));
254                         PlayerStats_GameReport_AddEvent(strcat("acc-", w.netname, "-frags"));
255                 }
256
257                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_3);
258                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_5);
259                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_10);
260                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_15);
261                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_20);
262                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_25);
263                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_30);
264                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_BOTLIKE);
265                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_FIRSTBLOOD);
266                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_FIRSTVICTIM);
267         }
268         else { PlayerStats_GameReport_DelayMapVote = false; }
269 }
270
271 void PlayerStats_GameReport_Handler(entity fh, entity pass, float status)
272 {
273         string t, tn;
274         string p, pn;
275         string e, en;
276         string nn, tt;
277         string s;
278
279         switch(status)
280         {
281                 // ======================================
282                 // -- OUTGOING GAME REPORT INFORMATION --
283                 // ======================================
284                 /* SPECIFICATIONS:
285                  * V: format version (always a fixed number) - this MUST be the first line!
286                  * #: comment (MUST be ignored by any parser)
287                  * R: release information on the server
288                  * G: game type
289                  * O: mod name (icon request) as in server browser
290                  * M: map name
291                  * I: match ID (see "matchid" in g_world.qc)
292                  * S: "hostname" of the server
293                  * C: number of "unpure" cvar changes
294                  * U: UDP port number of the server
295                  * D: duration of the match
296                  * L: "ladder" in which the server is participating in
297                  * P: player ID of an existing player; this also sets the owner for all following "n", "e" and "t" lines (lower case!)
298                  * Q: team number of an existing team (format: team#NN); this also sets the owner for all following "e" lines (lower case!)
299                  * i: player index
300                  * n: nickname of the player (optional)
301                  * t: team ID
302                  * e: followed by an event name, a space, and the event count/score
303                  *  event names can be:
304                  *   alivetime: total playing time of the player
305                  *   avglatency: average network latency compounded throughout the match
306                  *   wins: number of games won (can only be set if matches is set)
307                  *   matches: number of matches played to the end (not aborted by map switch)
308                  *   joins: number of matches joined (always 1 unless player never played during the match)
309                  *   scoreboardvalid: set to 1 if the player was there at the end of the match
310                  *   total-<scoreboardname>: total score of that scoreboard item
311                  *   scoreboard-<scoreboardname>: end-of-game score of that scoreboard item (can differ in non-team games)
312                  *   achievement-<achievementname>: achievement counters (their "count" is usually 1 if nonzero at all)
313                  *   kills-<index>: number of kills against the indexed player
314                  *   rank <number>: rank of player
315                  *   acc-<weapon netname>-hit: total damage dealt
316                  *   acc-<weapon netname>-fired: total damage that all fired projectiles *could* have dealt
317                  *   acc-<weapon netname>-cnt-hit: amount of shots that actually hit
318                  *   acc-<weapon netname>-cnt-fired: amount of fired shots
319                  *   acc-<weapon netname>-frags: amount of frags dealt by weapon
320                  */
321                 case URL_READY_CANWRITE:
322                 {
323                         url_fputs(fh, "V 9\n");
324                         #ifdef WATERMARK
325                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
326                         #endif
327                         url_fputs(fh, sprintf("G %s\n", GetGametype()));
328                         url_fputs(fh, sprintf("O %s\n", modname));
329                         url_fputs(fh, sprintf("M %s\n", GetMapname()));
330                         url_fputs(fh, sprintf("I %s\n", matchid));
331                         url_fputs(fh, sprintf("S %s\n", cvar_string("hostname")));
332                         url_fputs(fh, sprintf("C %d\n", cvar_purechanges_count));
333                         url_fputs(fh, sprintf("U %d\n", cvar("port")));
334                         url_fputs(fh, sprintf("D %f\n", max(0, time - game_starttime)));
335                         url_fputs(fh, sprintf("L %s\n", autocvar_g_playerstats_gamereport_ladder));
336
337                         // TEAMS
338                         if(teamplay)
339                         {
340                                 for(t = PS_GR_OUT_TL; (tn = db_get(PS_GR_OUT_DB, sprintf("%d", stof(t)))) != ""; t = tn)
341                                 {
342                                         // start team section
343                                         url_fputs(fh, sprintf("Q team#%s\n", t));
344
345                                         // output team events // todo: does this do unnecessary loops? perhaps we should do a separate "team_events_last" tracker..."
346                                         for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
347                                         {
348                                                 float v = stof(db_get(PS_GR_OUT_DB, sprintf("team#%d:%s", stof(t), e)));
349                                                 if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
350                                         }
351                                 }
352                         }
353
354                         // PLAYERS
355                         for(p = PS_GR_OUT_PL; (pn = db_get(PS_GR_OUT_DB, sprintf("%s:*", p))) != ""; p = pn)
356                         {
357                                 // start player section
358                                 url_fputs(fh, sprintf("P %s\n", p));
359
360                                 // playerid/index (entity number for this server)
361                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_playerid", p));
362                                 if(nn != "") { url_fputs(fh, sprintf("i %s\n", nn)); }
363
364                                 // player name
365                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_netname", p));
366                                 if(nn != "") { url_fputs(fh, sprintf("n %s\n", nn)); }
367
368                                 // team identification number
369                                 if(teamplay)
370                                 {
371                                         tt = db_get(PS_GR_OUT_DB, sprintf("%s:_team", p));
372                                         url_fputs(fh, sprintf("t %s\n", tt));
373                                 }
374
375                                 // output player events
376                                 for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
377                                 {
378                                         float v = stof(db_get(PS_GR_OUT_DB, sprintf("%s:%s", p, e)));
379                                         if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
380                                 }
381                         }
382                         url_fputs(fh, "\n");
383                         url_fclose(fh);
384                         break;
385                 }
386
387                 // ======================================
388                 // -- INCOMING GAME REPORT INFORMATION --
389                 // ======================================
390                 /* SPECIFICATIONS:
391                  * stuff
392                  */
393                 case URL_READY_CANREAD:
394                 {
395                         // url_fclose is processing, we got a response for writing the data
396                         // this must come from HTTP
397                         LOG_TRACE("Got response from player stats server:\n");
398                         while((s = url_fgets(fh))) { LOG_TRACE("  ", s, "\n"); }
399                         LOG_TRACE("End of response.\n");
400                         url_fclose(fh);
401                         break;
402                 }
403
404                 case URL_READY_CLOSED:
405                 {
406                         // url_fclose has finished
407                         LOG_TRACE("Player stats written\n");
408                         PlayerStats_GameReport_DelayMapVote = false;
409                         if(PS_GR_OUT_DB >= 0)
410                         {
411                                 db_close(PS_GR_OUT_DB);
412                                 PS_GR_OUT_DB = -1;
413                         }
414                         break;
415                 }
416
417                 case URL_READY_ERROR:
418                 default:
419                 {
420                         LOG_INFO("Player stats writing failed: ", ftos(status), "\n");
421                         PlayerStats_GameReport_DelayMapVote = false;
422                         if(PS_GR_OUT_DB >= 0)
423                         {
424                                 db_close(PS_GR_OUT_DB);
425                                 PS_GR_OUT_DB = -1;
426                         }
427                         break;
428                 }
429         }
430 }
431
432 void PlayerStats_PlayerBasic(entity joiningplayer, float newrequest)
433 {
434         // http://stats.xonotic.org/player/GgXRw6piDtFIbMArMuiAi8JG4tiin8VLjZgsKB60Uds=/elo.txt
435         if(autocvar_g_playerstats_playerbasic_uri != "")
436         {
437                 string uri = autocvar_g_playerstats_playerbasic_uri;
438                 if(joiningplayer.crypto_idfp != "")
439                 {
440                         // create the database if it doesn't already exist
441                         if(PS_B_IN_DB < 0)
442                                 PS_B_IN_DB = db_create();
443
444                         // now request the information
445                         uri = strcat(uri, "/player/", uri_escape(uri_escape(joiningplayer.crypto_idfp)), "/elo.txt");
446                         LOG_TRACE("Retrieving playerstats from URL: ", uri, "\n");
447                         url_single_fopen(
448                                 uri,
449                                 FILE_APPEND,
450                                 PlayerStats_PlayerBasic_Handler,
451                                 joiningplayer
452                         );
453
454                         // set status appropriately // todo: check whether the player info exists in the database previously
455                         if(newrequest)
456                         {
457                                 // database still contains useful information, so don't clear it of a useful status
458                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_WAITING;
459                         }
460                         else
461                         {
462                                 // database was previously empty or never hit received status for some reason
463                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_UPDATING;
464                         }
465                 }
466         }
467         else
468         {
469                 // server has this disabled, kill the DB and set status to idle
470                 if(PS_B_IN_DB >= 0)
471                 {
472                         entity player;
473
474                         db_close(PS_B_IN_DB);
475                         PS_B_IN_DB = -1;
476
477                         FOR_EACH_REALCLIENT(player) { player.playerstats_basicstatus = PS_B_STATUS_IDLE; }
478                 }
479         }
480 }
481
482 void PlayerStats_PlayerBasic_CheckUpdate(entity joiningplayer)
483 {
484         // determine whether we should retrieve playerbasic information again
485
486         #if 0
487         LOG_INFOF("PlayerStats_PlayerBasic_CheckUpdate('%s'): %f\n",
488                 joiningplayer.netname,
489                 time
490         );
491         #endif
492
493         // TODO: check to see if this playerid is inside the database already somehow...
494         // for now we'll just check the field, but this won't work for players who disconnect and reconnect properly
495         // although maybe we should just submit another request ANYWAY?
496         if(!joiningplayer.playerstats_basicstatus)
497         {
498                 PlayerStats_PlayerBasic(
499                         joiningplayer,
500                         (joiningplayer.playerstats_basicstatus == PS_B_STATUS_RECEIVED)
501                 );
502         }
503 }
504
505 void PlayerStats_PlayerBasic_Handler(entity fh, entity p, float status)
506 {
507         switch(status)
508         {
509                 case URL_READY_CANWRITE:
510                 {
511                         LOG_TRACE("-- Sending data to player stats server\n");
512                         /*url_fputs(fh, "V 1\n");
513                         #ifdef WATERMARK
514                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
515                         #endif
516                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
517                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
518                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
519                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
520                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
521                         */url_fputs(fh, "\n");
522                         url_fclose(fh);
523                         break;
524                 }
525
526                 case URL_READY_CANREAD:
527                 {
528                         string s = "";
529                         LOG_TRACE("-- Got response from player stats server:\n");
530                         //string gametype = string_null;
531                         while((s = url_fgets(fh)))
532                         {
533                                 LOG_TRACE("  ", s, "\n");
534                                 /*
535                                 string key = "", value = "", data = "";
536
537                                 n = tokenizebyseparator(s, " "); // key (value) data
538                                 if (n == 1)
539                                         continue;
540                                 else if (n == 2)
541                                 {
542                                 key = argv(0);
543                                 data = argv(1);
544                                 }
545                                 else if (n >= 3)
546                                 {
547                                                                 key = argv(0);
548                                                                 value = argv(1);
549                                                                 data = argv(2);
550                                 }
551
552                                 if (data == "")
553                                 continue;
554
555                                 if (key == "#")
556                                 continue;
557                                 else if (key == "V")
558                                 PlayerInfo_AddItem(p, "_version", data);
559                                 else if (key == "R")
560                                 PlayerInfo_AddItem(p, "_release", data);
561                                 else if (key == "T")
562                                 PlayerInfo_AddItem(p, "_time", data);
563                                 else if (key == "S")
564                                 PlayerInfo_AddItem(p, "_statsurl", data);
565                                 else if (key == "P")
566                                 PlayerInfo_AddItem(p, "_hashkey", data);
567                                 else if (key == "n")
568                                 PlayerInfo_AddItem(p, "_playernick", data);
569                                 else if (key == "i")
570                                 PlayerInfo_AddItem(p, "_playerid", data);
571                                 else if (key == "G")
572                                 gametype = data;
573                                 else if (key == "e" && value != "")
574                                 {
575                                 if (gametype == "")
576                                 PlayerInfo_AddItem(p, value, data);
577                                 else
578                                 PlayerInfo_AddItem(p, sprintf("%s/%s", gametype, value), data);
579                                 }
580                                 else
581                                 continue;
582                                 */
583                         }
584                         LOG_TRACE("-- End of response.\n");
585                         url_fclose(fh);
586                         break;
587                 }
588                 case URL_READY_CLOSED:
589                 {
590                         // url_fclose has finished
591                         LOG_INFO("Player stats synchronized with server\n");
592                         break;
593                 }
594
595                 case URL_READY_ERROR:
596                 default:
597                 {
598                         LOG_INFO("Receiving player stats failed: ", ftos(status), "\n");
599                         break;
600                 }
601         }
602 }
603 #endif // SVQC
604
605 #ifdef MENUQC
606
607
608 #if 0 // reading the entire DB at once
609         string e = "", en = "";
610         float i = 0;
611         for(e = PS_D_IN_EVL; (en = db_get(PS_D_IN_DB, e)) != ""; e = en)
612         {
613                 LOG_INFO(sprintf("%d:%s:%s\n", i, e, db_get(PS_D_IN_DB, sprintf("#%s", e))));
614                 ++i;
615         }
616 #endif
617
618 void PlayerStats_PlayerDetail_AddItem(string event, string data)
619 {
620         if(PS_D_IN_DB < 0) { return; }
621
622         // create a marker for the event so that we can access it later
623         string marker = sprintf("%s", event);
624         if(db_get(PS_D_IN_DB, marker) == "")
625         {
626                 if(PS_D_IN_EVL)
627                 {
628                         db_put(PS_D_IN_DB, marker, PS_D_IN_EVL);
629                         strunzone(PS_D_IN_EVL);
630                 }
631                 else { db_put(PS_D_IN_DB, marker, "#"); }
632                 PS_D_IN_EVL = strzone(marker);
633         }
634
635         // now actually set the event data
636         db_put(PS_D_IN_DB, sprintf("#%s", event), data);
637         LOG_TRACE("Added item ", sprintf("#%s", event), "=", data, " to PS_D_IN_DB\n");
638 }
639
640 void PlayerStats_PlayerDetail(void)
641 {
642         // http://stats.xonotic.org/player/me
643         if((autocvar_g_playerstats_playerdetail_uri != "") && (crypto_getmyidstatus(0) > 0))
644         {
645                 // create the database if it doesn't already exist
646                 if(PS_D_IN_DB < 0)
647                         PS_D_IN_DB = db_create();
648
649                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
650                 LOG_TRACE("Retrieving playerstats from URL: ", autocvar_g_playerstats_playerdetail_uri, "\n");
651                 url_single_fopen(
652                         autocvar_g_playerstats_playerdetail_uri,
653                         FILE_APPEND,
654                         PlayerStats_PlayerDetail_Handler,
655                         world
656                 );
657
658                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_WAITING;
659         }
660         else
661         {
662                 // player has this disabled, kill the DB and set status to idle
663                 if(PS_D_IN_DB >= 0)
664                 {
665                         db_close(PS_D_IN_DB);
666                         PS_D_IN_DB = -1;
667                 }
668
669                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_IDLE;
670         }
671 }
672
673 void PlayerStats_PlayerDetail_CheckUpdate(void)
674 {
675         // determine whether we should retrieve playerdetail information again
676         float gamecount = cvar("cl_matchcount");
677
678         #if 0
679         LOG_INFOF("PlayerStats_PlayerDetail_CheckUpdate(): %f >= %f, %d > %d\n",
680                 time,
681                 PS_D_NEXTUPDATETIME,
682                 PS_D_LASTGAMECOUNT,
683                 gamecount
684         );
685         #endif
686
687         if(
688                 (time >= PS_D_NEXTUPDATETIME)
689                 ||
690                 (gamecount > PS_D_LASTGAMECOUNT)
691         )
692         {
693                 PlayerStats_PlayerDetail();
694                 PS_D_NEXTUPDATETIME = (time + autocvar_g_playerstats_playerdetail_autoupdatetime);
695                 PS_D_LASTGAMECOUNT = gamecount;
696         }
697 }
698
699 void PlayerStats_PlayerDetail_Handler(entity fh, entity unused, float status)
700 {
701         switch(status)
702         {
703                 case URL_READY_CANWRITE:
704                 {
705                         LOG_TRACE("PlayerStats_PlayerDetail_Handler(): Sending data to player stats server...\n");
706                         url_fputs(fh, "V 1\n");
707                         #ifdef WATERMARK
708                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
709                         #endif
710                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
711                         //url_fputs(fh, sprintf("c %s\n", cvar_string("_cl_country"))); // country
712                         //url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
713                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
714                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
715                         url_fputs(fh, "\n");
716                         url_fclose(fh);
717                         break;
718                 }
719
720                 case URL_READY_CANREAD:
721                 {
722                         //print("PlayerStats_PlayerDetail_Handler(): Got response from player stats server:\n");
723                         string input = "";
724                         string gametype = "overall";
725                         while((input = url_fgets(fh)))
726                         {
727                                 float count = tokenizebyseparator(input, " ");
728                                 string key = "", event = "", data = "";
729
730                                 if(argv(0) == "#") { continue; }
731
732                                 if(count == 2)
733                                 {
734                                         key = argv(0);
735                                         data = substring(input, argv_start_index(1), strlen(input) - argv_start_index(1));
736                                 }
737                                 else if(count >= 3)
738                                 {
739                                         key = argv(0);
740                                         event = argv(1);
741                                         data = substring(input, argv_start_index(2), strlen(input) - argv_start_index(2));
742                                 }
743                                 else { continue; }
744
745                                 switch(key)
746                                 {
747                                         // general info
748                                         case "V": PlayerStats_PlayerDetail_AddItem("version", data); break;
749                                         case "R": PlayerStats_PlayerDetail_AddItem("release", data); break;
750                                         case "T": PlayerStats_PlayerDetail_AddItem("time", data); break;
751
752                                         // player info
753                                         case "S": PlayerStats_PlayerDetail_AddItem("statsurl", data); break;
754                                         case "P": PlayerStats_PlayerDetail_AddItem("hashkey", data); break;
755                                         case "n": PlayerStats_PlayerDetail_AddItem("playernick", data); break;
756                                         case "i": PlayerStats_PlayerDetail_AddItem("playerid", data); break;
757
758                                         // other/event info
759                                         case "G": gametype = data; break;
760                                         case "e":
761                                         {
762                                                 if(event != "" && data != "")
763                                                 {
764                                                         PlayerStats_PlayerDetail_AddItem(
765                                                                 sprintf(
766                                                                         "%s/%s",
767                                                                         gametype,
768                                                                         event
769                                                                 ),
770                                                                 data
771                                                         );
772                                                 }
773                                                 break;
774                                         }
775
776                                         default:
777                                         {
778                                                 LOG_INFOF(
779                                                         "PlayerStats_PlayerDetail_Handler(): ERROR: "
780                                                         "Key went unhandled? Is our version outdated?\n"
781                                                         "PlayerStats_PlayerDetail_Handler(): "
782                                                         "Key '%s', Event '%s', Data '%s'\n",
783                                                         key,
784                                                         event,
785                                                         data
786                                                 );
787                                                 break;
788                                         }
789                                 }
790
791                                 #if 0
792                                 LOG_INFO(sprintf(
793                                         "PlayerStats_PlayerDetail_Handler(): "
794                                         "Key '%s', Event '%s', Data '%s'\n",
795                                         key,
796                                         event,
797                                         data
798                                 ));
799                                 #endif
800                         }
801                         //print("PlayerStats_PlayerDetail_Handler(): End of response.\n");
802                         url_fclose(fh);
803                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_RECEIVED;
804                         statslist.getStats(statslist);
805                         break;
806                 }
807
808                 case URL_READY_CLOSED:
809                 {
810                         // url_fclose has finished
811                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Player stats synchronized with server.\n");
812                         break;
813                 }
814
815                 case URL_READY_ERROR:
816                 default:
817                 {
818                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Receiving player stats failed: ", ftos(status), "\n");
819                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_ERROR;
820                         if(PS_D_IN_DB >= 0)
821                         {
822                                 db_close(PS_D_IN_DB);
823                                 PS_D_IN_DB = -1;
824                         }
825                         break;
826                 }
827         }
828 }
829 #endif
830
831 /*
832 void PlayerInfo_AddPlayer(entity e)
833 {
834         if(playerinfo_db < 0)
835                 return;
836
837         string key;
838         key = sprintf("#%d:*", e.playerid); // TODO: use hashkey instead?
839
840         string p;
841         p = db_get(playerinfo_db, key);
842         if(p == "")
843         {
844                 if(playerinfo_last)
845                 {
846                         db_put(playerinfo_db, key, playerinfo_last);
847                         strunzone(playerinfo_last);
848                 }
849                 else
850                         db_put(playerinfo_db, key, "#");
851                 playerinfo_last = strzone(ftos(e.playerid));
852                 print("  Added player ", ftos(e.playerid), " to playerinfo_db\n");//DEBUG//
853         }
854 }
855
856 void PlayerInfo_AddItem(entity e, string item_id, string val)
857 {
858         if(playerinfo_db < 0)
859                 return;
860
861         string key;
862         key = sprintf("*:%s", item_id);
863
864         string p;
865         p = db_get(playerinfo_db, key);
866         if(p == "")
867         {
868                 if(playerinfo_events_last)
869                 {
870                         db_put(playerinfo_db, key, playerinfo_events_last);
871                         strunzone(playerinfo_events_last);
872                 }
873                 else
874                         db_put(playerinfo_db, key, "#");
875                 playerinfo_events_last = strzone(item_id);
876         }
877
878         key = sprintf("#%d:%s", e.playerid, item_id);
879         db_put(playerinfo_db, key, val);
880         print("  Added item ", key, "=", val, " to playerinfo_db\n");//DEBUG//
881 }
882
883 string PlayerInfo_GetItem(entity e, string item_id)
884 {
885         if(playerinfo_db < 0)
886                 return "";
887
888         string key;
889         key = sprintf("#%d:%s",  e.playerid, item_id);
890         return db_get(playerinfo_db, key);
891 }
892
893 string PlayerInfo_GetItemLocal(string item_id)
894 {
895         entity p = spawn();
896         p.playerid = 0;
897         return PlayerInfo_GetItem(p, item_id);
898 }
899
900 void PlayerInfo_ready(entity fh, entity p, float status)
901 {
902         float n;
903         string s;
904
905         PlayerInfo_AddPlayer(p);
906
907         switch(status)
908         {
909                 case URL_READY_CANWRITE:
910                         print("-- Sending data to player stats server\n");
911                         url_fputs(fh, "V 1\n");
912 #ifdef WATERMARK
913                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
914 #endif
915 #ifdef MENUQC
916                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
917                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
918                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
919                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
920                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
921 #endif
922                         url_fputs(fh, "\n");
923                         url_fclose(fh);
924                         break;
925                 case URL_READY_CANREAD:
926                         print("-- Got response from player stats server:\n");
927                         string gametype = string_null;
928                         while((s = url_fgets(fh)))
929                         {
930                                 print("  ", s, "\n");
931
932                                 string key = "", value = "", data = "";
933
934                                 n = tokenizebyseparator(s, " "); // key (value) data
935                                 if (n == 1)
936                                         continue;
937                                 else if (n == 2)
938                                 {
939                                         key = argv(0);
940                                         data = argv(1);
941                                 }
942                                 else if (n >= 3)
943                                 {
944                                         key = argv(0);
945                                         value = argv(1);
946                                         data = argv(2);
947                                 }
948
949                                 if (data == "")
950                                         continue;
951
952                                 if (key == "#")
953                                         continue;
954                                 else if (key == "V")
955                                         PlayerInfo_AddItem(p, "_version", data);
956                                 else if (key == "R")
957                                         PlayerInfo_AddItem(p, "_release", data);
958                                 else if (key == "T")
959                                         PlayerInfo_AddItem(p, "_time", data);
960                                 else if (key == "S")
961                                         PlayerInfo_AddItem(p, "_statsurl", data);
962                                 else if (key == "P")
963                                         PlayerInfo_AddItem(p, "_hashkey", data);
964                                 else if (key == "n")
965                                         PlayerInfo_AddItem(p, "_playernick", data);
966                                 else if (key == "i")
967                                         PlayerInfo_AddItem(p, "_playerid", data);
968                                 else if (key == "G")
969                                         gametype = data;
970                                 else if (key == "e" && value != "")
971                                 {
972                                         if (gametype == "")
973                                                 PlayerInfo_AddItem(p, value, data);
974                                         else
975                                                 PlayerInfo_AddItem(p, sprintf("%s/%s", gametype, value), data);
976                                 }
977                                 else
978                                         continue;
979                         }
980                         print("-- End of response.\n");
981                         url_fclose(fh);
982                         break;
983                 case URL_READY_CLOSED:
984                         // url_fclose has finished
985                         print("Player stats synchronized with server\n");
986                         break;
987                 case URL_READY_ERROR:
988                 default:
989                         print("Receiving player stats failed: ", ftos(status), "\n");
990                         break;
991         }
992 }
993
994 void PlayerInfo_Init()
995 {
996         playerinfo_db = db_create();
997 }
998
999 #ifdef SVQC
1000 void PlayerInfo_Basic(entity p)
1001 {
1002         print("-- Getting basic PlayerInfo for player ",ftos(p.playerid)," (SVQC)\n");
1003
1004         if(playerinfo_db < 0)
1005                 return;
1006
1007         string uri;
1008         uri = autocvar_g_playerinfo_uri;
1009         if(uri != "" && p.crypto_idfp != "")
1010         {
1011                 uri = strcat(uri, "/elo/", uri_escape(p.crypto_idfp));
1012                 print("Retrieving playerstats from URL: ", uri, "\n");
1013                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1014         }
1015 }
1016 #endif
1017
1018 #ifdef MENUQC
1019 void PlayerInfo_Details()
1020 {
1021         print("-- Getting detailed PlayerInfo for local player (MENUQC)\n");
1022
1023         if(playerinfo_db < 0)
1024                 return;
1025
1026         string uri;
1027         uri = autocvar_g_playerinfo_uri; // FIXME
1028         if(uri != "" && crypto_getmyidstatus(0) > 0)
1029         {
1030                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1031                 uri = strcat(uri, "/player/me");
1032                 print("Retrieving playerstats from URL: ", uri, "\n");
1033                 url_single_fopen(uri, FILE_APPEND, PlayerInfo_ready, world);
1034         }
1035 }
1036 #endif
1037
1038 #ifdef CSQC
1039 /*
1040  * FIXME - crypto_* builtin functions missing in CSQC (csprogsdefs.qh:885)
1041 void PlayerInfo_Details()
1042 {
1043         print("-- Getting detailed PlayerInfo for local player (CSQC)\n");
1044
1045         if(playerinfo_db < 0)
1046                 return;
1047
1048         string uri;
1049         uri = autocvar_g_playerinfo_uri; // FIXME
1050         if(uri != "" && crypto_getmyidstatus(0) > 0)
1051         {
1052                 uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1053                 print("Retrieving playerstats from URL: ", uri, "\n");
1054                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1055         }
1056 }
1057
1058 #endif
1059 */