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