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