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