-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameJoltAPI.java
1361 lines (1271 loc) · 48 KB
/
GameJoltAPI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.gamejolt;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Set;
import org.gamejolt.DataStore.DataStoreOperation;
import org.gamejolt.DataStore.DataStoreType;
import org.gamejolt.Trophy.Achieved;
/**
* <b>GameJoltAPI</b><br/>
* This is the main class that you use to implement the GameJolt Trophy, DataStore and HighScore systems.
*
* @since 0.90
* @version 0.99
* @author Ashley Gwinnell
*/
public interface GameJoltAPIIF extends DetectIntextTexts
{
private final String protocol = new String("http://");
//private final String api_root = new String("staging.gamejolt.com/api/game/");
//private final String api_root = new String("staging.gamejolt.com/game-api/");
private final String api_root = new String("gamejolt.com/api/game/");
//private final String api_root = new String("gamejoltdevash.dyndns.org/api/game/");
public enum Format {
XML,
JSON,
KEYPAIR;
public GameJoltResponseParser getParser(){
if (this == XML) {
return new GameJoltXMLParser();
} else if (this == JSON) {
return new GameJoltJSONParser();
}
return new GameJoltKeypairsParser(); // default type
}
@Override
public String toString() {
if (this == XML) {
return "xml";
} else if (this == JSON) {
return "json";
}
return "keypair"; // default
}
};
// the parser used for responses
private GameJoltResponseParser parser;
public Format format;
private int gameId;
private String privateKey;
private String version = "1_1";
//private double version = 0.95;
private String username;
private String usertoken;
private String quickplay_username;
private String quickplay_usertoken;
private boolean verbose = false;
private boolean verified = false;
/**
* Create a new GameJoltAPI object without trying to verify the user.
*
* This method will try to read the Game Jolt Quick Play file (gjapi-credentials.txt).
* If that file exists, then it will attempt to verify the user.
*
* @param gameId Your Game's Unique ID.
* @param privateKey Your Game's Unique (Private) Key.
*/
public GameJoltAPI(int gameId, String privateKey)
{
this.gameId = gameId;
this.privateKey = privateKey;
File f = new File("gjapi-credentials.txt");
if (f.exists()) {
try(Scanner sc = new Scanner(f)) {
this.quickplay_username = sc.nextLine();
this.quickplay_usertoken = sc.nextLine();
//this.verifyUser(username, usertoken);
} catch(FileNotFoundException exc) {
} catch(NoSuchElementException exc) {
if(verbose)
System.err.println(exc.getCause());
}
}
// the initial parser
format = Format.KEYPAIR;
parser = format.getParser();
}
/**
* Create a new GameJoltAPI and tries to verify the user.
* @param gameId Your Game's Unique ID.
* @param privateKey Your Game's Unique (Private) Key.
*/
public GameJoltAPI(int gameId, String privateKey, String username, String userToken)
{
this.gameId = gameId;
this.privateKey = privateKey;
this.verifyUser(username, userToken);
}
/**
* Set the version of the GameJolt API to use.
* @param version The version of the GameJolt API to be using.
*/
public void setVersion(String version) {
this.version = version;
}
/**
* Get the version of the GameJolt API you are using.
* @return The API version in use.
*/
public String getVersion() {
return version;
}
/**
* Sets whether the API should print out debug information to the Console.
* By default, this is set to true.
* @param b whether the API should print out debug informationto the Console.
*/
public void setVerbose(boolean b) {
this.verbose = b;
}
/**
* Returns true if the GJ API is set to print out it's debug information.
* @return True if the GJ API is set to print out it's debug information.
*/
public boolean isVerbose() {
return verbose;
}
/**
* Check whether the user/player has verified their credentials.
* @return whether the user/player has verified their credentials or not.
*/
public boolean isVerified() {
return verified;
}
/**
* Returns true if the API could find the gjapi-credentials.txt file.
* @return true if the API could find the gjapi-credentials.txt file.
*/
public boolean hasQuickplay() {
if (this.quickplay_username == null && this.quickplay_usertoken == null) {
return false;
}
return true;
}
/**
* reloads the quickplay-file. This will reset the verified-status.
* This should normally have no effect, since the quickplay-file is created when the user starts a quickplay-game, and not while the game is running.
*/
public void reloadQuickplay(){
File f = new File("gjapi-credentials.txt");
if (f.exists()) {
try(Scanner sc = new Scanner(f)) {
this.quickplay_username = sc.nextLine();
this.quickplay_usertoken = sc.nextLine();
} catch(FileNotFoundException exc) { }
}else{
this.quickplay_username = null;
this.quickplay_usertoken = null;
}
verified=false;
}
/**
* Gets the user object of the quickplay user if the game has the gjapi-credentials.txt file.
* if you only want to get the name and token, use {@link #getQuickplayUserCredientals()}
* @return the User object if the game has the gjapi-credentials.txt file.
*/
public User getQuickplayUser(){
if (!hasQuickplay())
return null;
User u = getUser(quickplay_username);
u.setToken(quickplay_usertoken);
return u;
}
/**
* Return the User object if the game has the gjapi-credentials.txt file.
* Note that the User object returned will only have a name and token set!
* @return the User object if the game has the gjapi-credentials.txt file.
*/
public User getQuickplayUserCredientals() {
if (!hasQuickplay())return null;
User u = new User();
u.setName(this.quickplay_username);
u.setToken(this.quickplay_usertoken);
return u;
}
/**
* gets the User object of the user with a certain name
* This User will not have a token
* @param name the name of the user
* @return the Userobject of the user or null if no user with this name exists
*/
public User getUser(String name){
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", name);
return getUserRequest(params);
}
/**
* gets the User object of the user with a certain id
* This User will not have a token
* @param id the id of the user
* @return the Userobject of the user or null if no user with this id exists
*/
public User getUser(int id){
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", String.valueOf(id));
return getUserRequest(params);
}
/**
* Sends a user fetch request using the given parameters.
* @param params The parameter to send for the user fetch request.
* @return The user object that was returned if it succeeds, or null if it fails.
*/
private User getUserRequest(HashMap<String, String> params) {
String response = request("users/", params, false);
if (verbose) { System.out.println(response); }
try {
User u = parser.parseUserRequestResponse(response);
if (verbose && u == null) {
System.err.println("GameJoltAPI: Could not get the Verified User with Username: " + this.username);
System.err.println(response);
}
return u;
} catch (Exception pe) {
pe.printStackTrace();
return null;
}
}
/**
* Return the User object if the user is verified, otherwise return null.
* @return the User object if the user is verified, otherwise null.
*/
public User getVerifiedUser() {
if (this.verified) {
return getQuickplayUser();
} else {
if (this.verbose) { System.err.println("GameJoltAPI: Could not get the (currently verified) user."); }
return null;
}
}
/**
* Retrieve the first 100 of the Highscores from GameJolt for the game in an array.
* @return all of the Highscores from GameJolt for the game in an array.
*/
public ArrayList<Highscore> getHighscores() {
return this.getHighscores(true, 100);
}
/**
* Retrieve the first 100 Highscores from GameJolt for either a game or the verified user.
*
* @param all If set to true, this will retrieve all highscores. Otherwise it will retrieve the currently verified user's highscores.
* @return An array of Highscore objects on success, an empty array or null on failure.
*/
public ArrayList<Highscore> getHighscores(boolean all) {
return this.getHighscores(all, 100);
}
/**
* Retrieve all of the Highscores of the Highscoretable from GameJolt for the game in an array.
* @param id the id of the Highscoretable
* @return all of the Highscores from GameJolt for the game in an array.
*/
public ArrayList<Highscore> getHighscores(int id) {
return this.getHighscores(id,true, 100);
}
/**
* Retrieve a list of Highscores from GameJolt for either a game or the verified user.
*
* @param id the id of the Highscoretable. If 0 is given it will use
* the primary high score table.
* @param all If set to true, this will retrieve all highscores. Otherwise it will retrieve the currently verified user's highscores.
* @return An array of Highscore objects on success, an empty array or null on failure.
*/
public ArrayList<Highscore> getHighscores(int id,boolean all) {
return this.getHighscores(id, all, 100);
}
/**
* Retrieve a list of Highscores from GameJolt for either a game or the verified user.
* THis will use the primary high score table.
*
* @param all If set to true, this will retrieve all highscores. Otherwise it will retrieve the currently verified user's highscores.
* @param limit the maximum amount of highscores to receive
* @return An array of Highscore objects on success, an empty array or null on failure.
*/
public ArrayList<Highscore> getHighscores(boolean all, int limit) {
return getHighscores(0,all,limit);
}
/**
* Retrieve a list of Highscores from GameJolt for either a game or the verified user.
* @param id the id of the table. If 0 is given it will use the primary
* high score table
*
* @param all If set to true, this will retrieve all highscores. Otherwise it will retrieve the currently verified user's highscores.
* @param limit the number of scores you want to receive (max. 100)
* @return An array of Highscore objects on success, an empty array or null on failure.
*/
public ArrayList<Highscore> getHighscores(int id, boolean all, int limit) {
if (all == false && !this.verified) {
if (verbose) { System.err.println("GameJoltAPI: Could not get the Highscores for the verified user as the user is not verified."); }
return null;
}
try {
HashMap<String, String> params = new HashMap<String, String>();
String response = null;
if (id!=0)
params.put("table_id", String.valueOf(id));
if (all == true) { // all highscores
params.put("limit", (""+limit));
response = request("scores", params, false);
} else { // verified user's highscores.
params.put("username", username);
params.put("user_token", usertoken);
params.put("limit", ""+limit);
response = request("scores", params, true);
}
if (verbose) {
System.out.println(response);
}
ArrayList<Highscore> highscores = parser.parseHighscoreResponse(response);
if (highscores == null) {
if (verbose) {
System.err.println("GameJoltAPI: Could not get the highscores "
+ "from the table with the id '" + id + "'");
}
}
return highscores;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
/**
* retrieve the Rank with the score closest to the given score from
* the primary high score table.
* @param score the score for which the rank should be retrieved
* @return the closest rank to the score
*/
public int getHighscoreRank(int score){
return getHighscoreRank(score, 0);
}
/**
* retrieve the Rank with the score closest to the given score.
* @param score the score for which the rank should be retrieved
* @param id the id of the HighscoreTable. If this is 0, it will
* get the primary high score table.
* @return the closest rank to the score, or -1 if there was an error
*/
public int getHighscoreRank(int score, int id){
try {
HashMap<String, String> params = new HashMap<String, String>();
// if no ID is supplied, it will get the primary score table.
if (id!=0)
params.put("table_id", String.valueOf(id));
params.put("sort", String.valueOf(score));
String response = request("scores/get-rank", params, false);
if (verbose) {
System.out.println(response);
}
int rank = parser.parseHighscoreRankResponse(response);
if (rank == -1) {
if (verbose) {
System.err.println("GameJoltAPI: Could not get the highscore "
+ "rank for the score '" + score + "' and id '" + id + "'");
}
}
return rank;
} catch (Exception pe) {
pe.printStackTrace();
return -1;
}
}
/**
* gets a List of all Highscoretables available for this game
* @return a list of Highscoretables, or null if there is an error or it's not successful
*/
public ArrayList<HighscoreTable> getHighscoreTables(){
String response = null;
try {
HashMap<String, String> params = new HashMap<String, String>();
response = request("scores/tables", params, false);
if (verbose) {
System.out.println(response);
}
ArrayList<HighscoreTable> tables = parser.parseHighscoreTableResponse(response);
if (tables == null) {
if (verbose) {
System.err.println("GameJoltAPI: Could not get a list of highscore tables");
}
}
return tables;
} catch (Exception pe) {
pe.printStackTrace();
}
return null;
}
/**
* Add a highscore for the currently verified Game Jolt user.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @return true if successful, otherwise false.
*/
public boolean addHighscore(String score, int sort) {
return this.addHighscore(0,score, sort, "");
}
/**
* Add a highscore for the currently verified Game Jolt user.
* @param id the id of the Highscoretable
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @return true if successful, otherwise false.
*/
public boolean addHighscore(int id, String score, int sort) {
return this.addHighscore(id, score, sort, "");
}
/**
* Add a highscore for the currently verified Game Jolt user.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @param extra Extra information to be stored about this score as a String, such as how the score was made, or time taken. This is not shown on the site.
* @return true if successful, otherwise false.
*/
public boolean addHighscore(String score, int sort, String extra) {
return addHighscore(0, score, sort,"");
}
/**
* Add a highscore for the currently verified Game Jolt user.
* @param id the id of the Highscoretable
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @param extra Extra information to be stored about this score as a String, such as how the score was made, or time taken. This is not shown on the site.
* @return true if successful, otherwise false.
*/
public boolean addHighscore(int id, String score, int sort, String extra) {
if (!this.verified) {
if (verbose) { System.err.println("GameJoltAPI: Could not add the High Score because the user is not verified."); }
return false;
}
String response = null;
try {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("user_token", usertoken);
params.put("score", ""+score);
params.put("extra_data", ""+extra);
params.put("sort", ""+sort);
if (id!=0)
params.put("table_id", String.valueOf(id));
response = request("scores/add",params,true);
if (verbose) { System.out.println(response); }
if (!parser.isSuccessful(response) || response.equals("REQUEST_FAILED")) {
if (verbose) { System.err.println("GameJoltAPI: Could not add the High Score."); }
if (verbose) { System.out.println(response); }
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* Adds a HighScore for a Guest!
* @param guest_username The desired name of the guest you want to add the highscore for.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @return true if successful, false otherwise.
*/
public boolean addHighscore(String guest_username, String score, int sort) {
return this.addHighscore(0,guest_username, score, sort, "");
}
/**
* Adds a HighScore for a Guest!
* @param if the id of the HighscoreTable
* @param guest_username The desired name of the guest you want to add the highscore for.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @return true if successful, false otherwise.
*/
public boolean addHighscore(int id,String guest_username, String score, int sort) {
return this.addHighscore(id,guest_username, score, sort, "");
}
/**
* Adds a HighScore for a Guest with additional data!
* @param guest_username The desired name of the guest you want to add the highscore for.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @param extra Extra information to be stored about this score as a String, such as how the score was made, or time taken. This is not shown on the site.
* @return true if successful, false otherwise.
*/
public boolean addHighscore(String guest_username, String score, int sort, String extra) {
return addHighscore(0, guest_username,score, sort);
}
/**
* Adds a HighScore for a Guest!
* @param id the id of the highscoretable
* @param guest_username The desired name of the guest you want to add the highscore for.
* @param score The String of the score, e.g. "5 Grapefruits". This is shown on the site.
* @param sort The sortable value of the score, e.g. 5. This is shown on the site.
* @param extra Extra information to be stored about this score as a String, such as how the score was made, or time taken. This is not shown on the site.
* @return true if successful, false otherwise.
*/
public boolean addHighscore(int id,String guest_username, String score, int sort, String extra) {
String response = null;
try {
HashMap<String, String> params = new HashMap<String, String>();
params.put("guest", guest_username);
params.put("score", ""+score);
params.put("sort", ""+sort);
params.put("extra_data", (""+extra));
if (id!=0)
params.put("table_id", String.valueOf(id));
response = request("scores/add", params, false);
if (verbose) { System.out.println(response); }
if (!parser.isSuccessful(response) || response.equals("REQUEST_FAILED")) {
if (verbose) { System.err.println("GameJoltAPI: Could not add the Guest High Score."); }
if (verbose && response.contains("Guests are not allowed to enter scores for this game.")) { // TODO: optimisation.
System.err.println("Guests are not allowed to enter scores for this game.");
}
if (verbose) { System.out.println(response); }
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/*
* Data Storage
*
* /api/game/data-store/
* ?game_id
* ?username [empty|username]
* ?user_token [empty|user_token]
* ?key
*
* /api/game/data-store/set/
* ?game_id
* ?username [empty|username]
* ?user_token [empty|user_token]
* ?key
* ?data (serialized string)
*
* /api/game/data-store/remove/
* ?game_id
* ?username [empty|username]
* ?user_token [empty|user_token]
* ?key
*/
/**
* updates the data of an existing entry on the gamejolts servers by performing a {@link DataStoreOperation} between the data on the Server and the values
* @param type the Type of the Data Store. Should be either DataTypeStore.USER or DataTypeStore.GAME.
* @param key key for which to store the data. You use this key to retrieve the DataStore.
* @param operation the operation to perform on the entry
* @param value
* @return
*/
public DataStore updateDataStore(DataStoreType type, String key, DataStoreOperation operation, int value)
{
return updateDataStore(type, key, operation, ""+value);
}
/**
* updates the data of an existing entry on the gamejolts servers by performing a {@link DataStoreOperation} between the data on the Server and the values
* @param type the Type of the Data Store. Should be either DataTypeStore.USER or DataTypeStore.GAME.
* @param key key for which to store the data. You use this key to retrieve the DataStore.
* @param operation the operation to perform on the entry
* @param value
* @return
*/
public DataStore updateDataStore(DataStoreType type, String key, DataStoreOperation operation, String value)
{
String response=null;
try {
if (type == DataStoreType.GAME) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("operation", operation.toString().toLowerCase());
params.put("value", value);
params.put("key", ""+key);
params.put("format", "dump");
response = request("data-store/update/", params, false);
if (verbose) { System.out.println(response); }
} else if (type == DataStoreType.USER) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("operation", operation.toString().toLowerCase());
params.put("value", value);
params.put("key", ""+key);
params.put("format", "dump");
response = request("data-store/update/", params, true);
// response = this.request("data-store/update/", "key=" + key + "&operation=" + operation.toString().toLowerCase() + "&value=" + value);
if (verbose) {
System.out.println(response);
}
}
} catch(Exception e) {
System.err.println("urg");
return null;
}
if (!response.substring(0, 7).equals("SUCCESS")) {
if (verbose) { System.err.println("could not update DataStore");}
return null;
}
DataStore ds = new DataStore();
ds.setKey(key);
ds.setData(response.substring(9));
ds.setType(type);
return ds;
}
/**
* Adds a piece of data to Game Jolt's servers replacing
* any that already exists with the key and type given.
*
* @param type The type of the Data Store. Should be either DataTypeStore.USER or DataTypeStore.GAME.
* @param key The key for which to store the data. You use this key to retrieve the DataStore.
* @param data Data to keep on Game Jolt servers. This data is normally xml, json, or serialised memory.
* @return A DataStore Object for the data you passed in.
*/
public DataStore setDataStore(DataStoreType type, String key, String data) {
String response = null;
if (type == DataStoreType.GAME) {
HashMap<String, String> params = new HashMap<String, String>();
HashMap<String,String> postParams = new HashMap<String,String>();
params.put("key", ""+key);
postParams.put("data", ""+data);
response=requestAsPost("data-store/set", params,postParams, false);
} else {
HashMap<String, String> params = new HashMap<String, String>();
HashMap<String,String> postParams = new HashMap<String,String>();
params.put("key", ""+key);
postParams.put("data", ""+data);
response = this.requestAsPost("data-store/set", params,postParams,true);
if (verbose) { System.out.println(response); }
}
if (!parser.isSuccessful(response)) {
if (verbose) { System.err.println("GameJoltAPI: Could not add " + type + " DataStore with Key \"" + key + "\"."); }
// if (verbose) { System.out.println(response); }
return null;
}
//if (verbose) { System.out.println(response); }
DataStore ds = new DataStore();
ds.setKey(key);
ds.setData(data);
ds.setType(type);
return ds;
}
/**
* Remove a piece of data from Game Jolt's servers
* as specified by the type and key.
*
* @param type The type of the Data Store. Should be either DataTypeStore.USER or DataTypeStore.GAME.
* @param key The key for which to remove the data.
* @return True if the DataStore was removed successfully. Note this will return false if no item exists with the key given.
*/
public boolean removeDataStore(DataStoreType type, String key) {
String response = null;
if (type == DataStoreType.GAME) {
HashMap<String, String> params = new HashMap<>();
params.put("key",(""+key));
response = request("data-store/remove", params, false);
if (verbose) { System.out.println(response); }
}
else {
response = this.request("data-store/remove", "key=" + key);
if (verbose) { System.out.println(response); }
}
if (!parser.isSuccessful(response)) {
if (verbose) { System.err.println("GameJoltAPI: Could not get " + type + " DataStore with Key \"" + key + "\"."); }
if (verbose) { System.out.println(response); }
return false;
}
return true;
}
/**
* Retrieve a list of DataStore Objects for the type specified by the parameter.
* This method loops through all of the keys and creates all objects using a new http request for each key.
* For this reason, it is slow, and it is advised that you use GameJoltAPI.getDataStoreKeys();
* In Big O notation, this method takes O(n + 1) time.
*
* @param type The Type of keys to get, either DataStoreType.USER or DataStoreType.GAME.
* @return a list of Data Store keys for the type specified by the parameters.
*/
public ArrayList<DataStore> getDataStoreObjects(DataStoreType type) {
ArrayList<String> keys = this.getDataStoreKeys(type);
ArrayList<DataStore> datastores = new ArrayList<DataStore>();
for (int i = 0; i < keys.size(); i++) {
datastores.add(this.getDataStore(type, keys.get(i)));
}
return datastores;
}
/**
* Retrieve a list of Data Store keys for the type specified by the parameter.
*
* @param type The Type of keys to get, either DataStoreType.USER or DataStoreType.GAME.
* @return a list of Data Store keys for the type specified by the parameters.
* If there was an error, it returns null.
*/
public ArrayList<String> getDataStoreKeys(DataStoreType type) {
try {
String response;
if (type == DataStoreType.GAME) {
response = request("data-store/get-keys",new HashMap<String,String>(),false);
} else {
response = this.request("data-store/get-keys", new HashMap<String,String>(),true);
}
if (verbose) {
System.out.println(response);
}
ArrayList<String> keys_list = parser.parseDatastoresKeysResponse(response);
if (keys_list == null) {
if (verbose) {
System.err.println("GameJoltAPI: Could not get the ServerTime.");
}
}
return keys_list;
} catch (Exception e) {
if (verbose) {
System.err.println("GameJoltAPI: Error while getting Datastore keys");
e.printStackTrace();
}
}
return null;
}
/**
* Retrieve a piece of data from Game Jolt's servers
* as specified by type and key.
*
* @param type The type of the Data Store. Should be either DataTypeStore.USER or DataTypeStore.GAME.
* @param key The key for which the data was stored.
* @return The DataStore Object for the key passed in.
*/
public DataStore getDataStore(DataStoreType type, String key){
String response = null;
if (type == DataStoreType.GAME) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("format", "dump");
params.put("key", ""+key);
response = request("data-store/", params, false);
if (verbose) { System.out.println(response); }
} else {
response = this.request("data-store/", "key=" + key + "&format=dump");
if (verbose) { System.out.println(response); }
}
if (!response.substring(0, 7).equals("SUCCESS")) {
if (verbose) { System.err.println("GameJoltAPI: " + response.substring(9)); }
if (verbose) { System.out.println(response); }
return null;
}
DataStore ds = new DataStore();
ds.setKey(key);
ds.setData(response.substring(9));
ds.setType(type);
return ds;
}
/*
* Status
*
* /api/game/status/open/
* ?game_id
* ?username
* ?user_token
*
* /api/game/status/ping/
* ?game_id
* ?username
* ?user_token
* ?status=[active|idle](optional)
*
* /api/game/status/close/
* ?game_id
* ?username
* ?user_token
*/
/**
* Open a new play session with Game Jolt.
* This requires a user to be verified (logged in).
* You should do this before you ping or update. This will close the previously open session.
*
* @return true if a new play session was opened successfully. false if request fails or if the user is not verified.
*/
public boolean sessionOpen() {
if (!this.verified) {
if (verbose) {
System.err.println("GameJoltAPI: Could not open Play Session: User must be verified.\n");
}
return false;
}
String response = "";
response = this.request("sessions/open/", "");
if (this.verbose) { System.out.println(response); }
if (parser.isSuccessful(response)) {
return true;
} else {
if (verbose) {
System.err.println("GameJoltAPI: Could not open Play Session.\n");
System.err.println(response);
}
return false;
}
}
/**
* Check if a session exists for the player
* @return true if the session exists, false if no session exists or the player is not verified.
*/
public boolean sessionCheck(){
if (!this.verified) {
if (verbose) {
System.err.println("GameJoltAPI: Could not check Play Session: User must be verified.\n");
}
return false;
}
String response = this.request("sessions/check/", "");
if (this.verbose) { System.out.println(response); }
if (parser.isSuccessful(response)) {
return true;
}else{
if (verbose) {
System.err.println("GameJoltAPI: Could not update (ping) Play Session.\n");
System.err.println(response);
}
return false;
}
}
/**
* Update the current play session with Game Jolt.
* You should call this every 60 seconds as Game Jolt closes play sessions after 120 seconds of inactivity.
* This method will set the user as ACTIVE. Use the other method to set the user as IDLE.
* This requires a user to be verified (logged in).
* This method will return false if there is no session to update.
*
* @return true if the play session was updated (pinged) successfully, false if request fails (no current session) or if the user is not verified.
*/
public boolean sessionUpdate() {
return this.sessionUpdate(true);
}
/**
* Update the current play session with Game Jolt.
* You should call this every 60 seconds as Game Jolt closes play sessions after 120 seconds of inactivity.
* This requires a user to be verified (logged in).
* This method will return false if there is no session to update.
*
* @param active You can set the game player as ACTIVE with true or IDLE with false. A good example of this would be sending an idle message if the user is on a menu or pause screen.
* @return true if the play session was updated (pinged) successfully, false if request fails (no current session) or if the user is not verified.
*/
public boolean sessionUpdate(boolean active) {
if (!this.verified) {
if (verbose) {
System.err.println("GameJoltAPI: Could not update (ping) Play Session: User must be verified.\n");
}
return false;
}
HashMap<String,String> params = new HashMap<String,String>();
if (active){
params.put("status", "active");
}else{
params.put("status", "idle");
}
String response = this.request("sessions/ping/", params);
if (this.verbose) { System.out.println(response); }
if (parser.isSuccessful(response)) {
return true;
} else {
if (verbose) {
System.err.println("GameJoltAPI: Could not update (ping) Play Session.\n");
System.err.println(response);
}
return false;
}
}
/**
* Close the current play session at Game Jolt.
* This requires a user to be verified (logged in).
* You should do this when closing or exiting your game.
* This method will return false if there is no session to close.
*
* @return true if the play session was closed successfully, false if request fails (no current session) or if the user is not verified.
*/
public boolean sessionClose() {
if (!this.verified) {
if (verbose) {
System.err.println("GameJoltAPI: Could not close Play Session: User must be verified.\n");
}
return false;
}
String response = this.request("sessions/close/", "");
if (this.verbose) { System.out.println(response); }
if (parser.isSuccessful(response)) {
return true;
} else {
if (verbose) {
System.err.println("GameJoltAPI: Could not close Play Session.\n");
System.err.println(response);
}
return false;
}
}
/**
* Give the currently verified user a trophy specified by Trophy object.
* This method uses the trophy's ID.
* @param t The Trophy to give.
* @return true on successfully given trophy.
*/
public boolean achieveTrophy(Trophy t) {
return achieveTrophy(Integer.parseInt(t.getId()));
}
/**
* Give the currently verified user a trophy specified by Id.
* @param trophyId The ID of the Trophy to give.
* @return true on successfully given trophy.
*/
public boolean achieveTrophy(int trophyId) {
String response = this.request("trophies/add-achieved", "trophy_id=" + trophyId);
if (parser.isSuccessful(response)) {
return true;
} else {
if (verbose) {
System.err.println("GameJoltAPI: Could not give Trophy to user.\n");
System.err.println(response);
}
return false;
}
}
/**
* Get a list of all trophies.
* @return A list of trophy objects.
*/