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