-
Notifications
You must be signed in to change notification settings - Fork 54
/
client.ts
2066 lines (1824 loc) · 76.5 KB
/
client.ts
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
/**
* Copyright 2020 The Nakama Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ApiAccount,
ApiAccountCustom,
ApiAccountDevice,
ApiAccountEmail,
ApiAccountFacebook,
ApiAccountFacebookInstantGame,
ApiAccountGoogle,
ApiAccountGameCenter,
ApiAccountSteam,
ApiChannelMessageList,
ApiCreateGroupRequest,
ApiDeleteStorageObjectsRequest,
ApiEvent,
ApiFriendList,
ApiGroup,
ApiGroupList,
ApiGroupUserList,
ApiLeaderboardRecord,
ApiLeaderboardRecordList,
ApiMatchList,
ApiNotificationList,
ApiReadStorageObjectsRequest,
ApiRpc,
ApiStorageObjectAcks,
ApiStorageObjectList,
ApiStorageObjects,
ApiTournamentList,
ApiTournamentRecordList,
ApiUpdateAccountRequest,
ApiUpdateGroupRequest,
ApiUsers,
ApiUserGroupList,
ApiWriteStorageObjectsRequest,
NakamaApi,
ApiSession,
ApiAccountApple,
ApiLinkSteamRequest,
ApiValidatePurchaseResponse,
ApiFriendsOfFriendsList,
ApiStoreEnvironment,
ApiStoreProvider,
ApiValidateSubscriptionResponse,
ApiValidatedSubscription,
} from "./api.gen";
import { Session } from "./session";
import { DefaultSocket, Socket } from "./socket";
import { WebSocketAdapter, WebSocketAdapterText } from "./web_socket_adapter";
const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_PORT = "7350";
const DEFAULT_SERVER_KEY = "defaultkey";
const DEFAULT_TIMEOUT_MS = 7000;
const DEFAULT_EXPIRED_TIMESPAN_MS = 5 * 60 * 1000;
/** Response for an RPC function executed on the server. */
export interface RpcResponse {
/** The identifier of the function. */
id?: string;
/** The payload of the function which must be a JSON object. */
payload?: object;
}
/** Represents a complete leaderboard record with all scores and associated metadata. */
export interface LeaderboardRecord {
/** The UNIX time when the leaderboard record was created. */
create_time?: string;
/** The UNIX time when the leaderboard record expires. */
expiry_time?: string;
/** The ID of the leaderboard this score belongs to. */
leaderboard_id?: string;
/** Metadata. */
metadata?: object;
/** The number of submissions to this score record. */
num_score?: number;
/** The ID of the score owner, usually a user or group. */
owner_id?: string;
/** The rank of this record. */
rank?: number;
/** The score value. */
score?: number;
/** An optional subscore value. */
subscore?: number;
/** The UNIX time when the leaderboard record was updated. */
update_time?: string;
/** The username of the score owner, if the owner is a user. */
username?: string;
/** The maximum number of score updates allowed by the owner. */
max_num_score?: number;
}
/** A set of leaderboard records, may be part of a leaderboard records page or a batch of individual records. */
export interface LeaderboardRecordList {
/** The cursor to send when retrieving the next page, if any. */
next_cursor?: string;
/** A batched set of leaderboard records belonging to specified owners. */
owner_records?: Array<LeaderboardRecord>;
/** The cursor to send when retrieving the previous page, if any. */
prev_cursor?: string;
// The total number of ranks available.
rank_count?: number;
/** A list of leaderboard records. */
records?: Array<LeaderboardRecord>;
}
/** A Tournament on the server. */
export interface Tournament {
/** Whether the leaderboard was created authoritatively or not. */
authoritative?: boolean;
/** The ID of the tournament. */
id?: string;
/** The title for the tournament. */
title?: string;
/** The description of the tournament. May be blank. */
description?: string;
/** The UNIX timestamp for duration of a tournament. */
duration?: number;
/** The category of the tournament. e.g. "vip" could be category 1. */
category?: number;
/** ASC or DESC sort mode of scores in the tournament. */
sort_order?: number;
/** The current number of players in the tournament. */
size?: number;
/** The maximum number of players for the tournament. */
max_size?: number;
/** The maximum score updates allowed per player for the current tournament. */
max_num_score?: number;
/** True if the tournament is active and can enter. A computed value. */
can_enter?: boolean;
/** The UNIX timestamp when the tournament stops being active until next reset. A computed value. */
end_active?: number;
/** The UNIX timestamp when the tournament is next playable. A computed value. */
next_reset?: number;
/** Additional information stored as a JSON object. */
metadata?: object;
/** The UNIX time when the tournament was created. */
create_time?: string;
/** The UNIX time when the tournament will start. */
start_time?: string;
/** The UNIX time when the tournament will be stopped. */
end_time?: string;
/** The UNIX time when the tournament start being active. A computed value. */
start_active?: number;
}
/** A list of tournaments. */
export interface TournamentList {
/** The list of tournaments returned. */
tournaments?: Array<Tournament>;
/** A pagination cursor (optional). */
cursor?: string,
}
/** A set of tournament records, may be part of a tournament records page or a batch of individual records. */
export interface TournamentRecordList {
/** The cursor to send when retireving the next page, if any. */
next_cursor?: string;
/** A batched set of tournament records belonging to specified owners. */
owner_records?: Array<LeaderboardRecord>;
/** The cursor to send when retrieving the previous page, if any. */
prev_cursor?: string;
/** A list of tournament records. */
records?: Array<LeaderboardRecord>;
}
/** Record values to write. */
export interface WriteTournamentRecord {
/** Optional record metadata. */
metadata?: object;
/** The score value to submit. */
score?: string;
/** An optional secondary value. */
subscore?: string;
}
/** Record values to write. */
export interface WriteLeaderboardRecord {
/** Optional record metadata. */
metadata?: object;
/** The score value to submit. */
score?: string;
/** An optional secondary value. */
subscore?: string;
}
/** The object to store. */
export interface WriteStorageObject {
/** The collection to store the object. */
collection?: string;
/** The key for the object within the collection. */
key?: string;
/** The read access permissions for the object. */
permission_read?: number;
/** The write access permissions for the object. */
permission_write?: number;
/** The value of the object. */
value?: object;
/** The version hash of the object to check. Possible values are: ["", "*", "#hash#"]. */
version?: string;
}
/** An object within the storage engine. */
export interface StorageObject {
/** The collection which stores the object. */
collection?: string;
/** The UNIX time when the object was created. */
create_time?: string;
/** The key of the object within the collection. */
key?: string;
/** The read access permissions for the object. */
permission_read?: number;
/** The write access permissions for the object. */
permission_write?: number;
/** The UNIX time when the object was last updated. */
update_time?: string;
/** The user owner of the object. */
user_id?: string;
/** The value of the object. */
value?: object;
/** The version hash of the object. */
version?: string;
}
/** List of storage objects. */
export interface StorageObjectList {
/** The cursor associated with the query a page of results. */
cursor?: string;
/** The list of storage objects. */
objects: Array<StorageObject>;
}
/** Batch of storage objects. */
export interface StorageObjects {
/** The batch of storage objects. */
objects: Array<StorageObject>;
}
/** A message sent on a channel. */
export interface ChannelMessage {
/** The channel this message belongs to. */
channel_id?: string;
/** The code representing a message type or category. */
code?: number;
/** The content payload. */
content?: object;
/** The UNIX time when the message was created. */
create_time?: string;
/** The ID of the group, or an empty string if this message was not sent through a group channel. */
group_id?: string;
/** The unique ID of this message. */
message_id?: string;
/** True if the message was persisted to the channel's history, false otherwise. */
persistent?: boolean;
/** The name of the chat room, or an empty string if this message was not sent through a chat room. */
room_name?: string;
/** Another message ID reference, if any. */
reference_id?: string;
/** Message sender, usually a user ID. */
sender_id?: string;
/** The UNIX time when the message was last updated. */
update_time?: string;
/** The ID of the first DM user, or an empty string if this message was not sent through a DM chat. */
user_id_one?: string;
/** The ID of the second DM user, or an empty string if this message was not sent through a DM chat. */
user_id_two?: string;
/** The username of the message sender, if any. */
username?: string;
}
/** A list of channel messages, usually a result of a list operation. */
export interface ChannelMessageList {
/** Cacheable cursor to list newer messages. Durable and designed to be stored, unlike next/prev cursors. */
cacheable_cursor?: string;
/** A list of messages. */
messages?: Array<ChannelMessage>;
/** The cursor to send when retireving the next page, if any. */
next_cursor?: string;
/** The cursor to send when retrieving the previous page, if any. */
prev_cursor?: string;
}
/** A user in the system. */
export interface User {
/** A URL for an avatar image. */
avatar_url?: string;
/** The UNIX time when the user was created. */
create_time?: string;
/** The display name of the user. */
display_name?: string;
/** Number of related edges to this user. */
edge_count?: number;
/** The Facebook id in the user's account. */
facebook_id?: string;
/** The Facebook Instant Game ID in the user's account. */
facebook_instant_game_id?: string;
/** The Apple Game Center in of the user's account. */
gamecenter_id?: string;
/** The Google id in the user's account. */
google_id?: string;
/** The id of the user's account. */
id?: string;
/** The language expected to be a tag which follows the BCP-47 spec. */
lang_tag?: string;
/** The location set by the user. */
location?: string;
/** Additional information stored as a JSON object. */
metadata?: {};
/** Indicates whether the user is currently online. */
online?: boolean;
/** The Steam id in the user's account. */
steam_id?: string;
/** The timezone set by the user. */
timezone?: string;
/** The UNIX time when the user was last updated. */
update_time?: string;
/** The username of the user's account. */
username?: string;
}
/** A collection of zero or more users. */
export interface Users {
/** The User objects. */
users?: Array<User>;
}
/** A friend of a user. */
export interface Friend {
/** The friend status. */
state?: number;
/** The user object. */
user?: User;
}
/** A collection of zero or more friends of the user. */
export interface Friends {
/** The Friend objects. */
friends?: Array<Friend>;
/** Cursor for the next page of results, if any. */
cursor?: string;
}
/** A friend of a friend. */
export interface FriendOfFriend {
// The user who referred its friend.
referrer?: string;
// User.
user?: User;
}
/** Friends of the user's friends. */
export interface FriendsOfFriends {
// Cursor for the next page of results, if any.
cursor?: string;
// User friends of friends.
friends_of_friends?: Array<FriendOfFriend>;
}
/** A user-role pair representing the user's role in a group. */
export interface GroupUser {
/** The user. */
user?: User;
/** Their role within the group. */
state?: number;
}
/** A list of users belonging to a group along with their role in it. */
export interface GroupUserList {
/** The user-role pairs. */
group_users?: Array<GroupUser>;
/** Cursor for the next page of results, if any. */
cursor?: string;
}
/** A group in the server. */
export interface Group {
/** A URL for an avatar image. */
avatar_url?: string;
/** The UNIX time when the group was created. */
create_time?: string;
/** The id of the user who created the group. */
creator_id?: string;
/** A description for the group. */
description?: string;
/** The current count of all members in the group. */
edge_count?: number;
/** The id of a group. */
id?: string;
/** The language expected to be a tag which follows the BCP-47 spec. */
lang_tag?: string;
/** The maximum number of members allowed. */
max_count?: number;
/** Additional information stored as a JSON object. */
metadata?: {};
/** The unique name of the group. */
name?: string;
/** Anyone can join open groups, otherwise only admins can accept members. */
open?: boolean;
/** The UNIX time when the group was last updated. */
update_time?: string;
}
/** One or more groups returned from a listing operation. */
export interface GroupList {
/** A cursor used to get the next page. */
cursor?: string;
/** One or more groups. */
groups?: Array<Group>;
}
/** A group-role pair representing the user's groups and their role in each. */
export interface UserGroup {
/** The group. */
group?: Group;
/** The user's role within the group. */
state?: number;
}
/** A list of groups belonging to a user along with their role in it. */
export interface UserGroupList {
/** The group-role pairs. */
user_groups?: Array<UserGroup>;
/** Cursor for the next page of results, if any. */
cursor?: string;
}
/** A notification in the server. */
export interface Notification {
/** Category code for this notification. */
code?: number;
/** Content of the notification in JSON. */
content?: {};
/** The UNIX time when the notification was created. */
create_time?: string;
/** ID of the Notification. */
id?: string;
/** True if this notification was persisted to the database. */
persistent?: boolean;
/** ID of the sender, if a user. Otherwise 'null'. */
sender_id?: string;
/** Subject of the notification. */
subject?: string;
}
/** A collection of zero or more notifications. */
export interface NotificationList {
/** Use this cursor to paginate notifications. Cache this to catch up to new notifications. */
cacheable_cursor?: string;
/** Collection of notifications. */
notifications?: Array<Notification>;
}
/* A validated subscription stored by Nakama. */
export interface ValidatedSubscription {
// Whether the subscription is currently active or not.
active?: boolean;
// UNIX Timestamp when the receipt validation was stored in DB.
create_time?: string;
// Whether the purchase was done in production or sandbox environment.
environment?: ApiStoreEnvironment;
// Subscription expiration time. The subscription can still be auto-renewed to extend the expiration time further.
expiry_time?: string;
// Purchase Original transaction ID (we only keep track of the original subscription, not subsequent renewals).
original_transaction_id?: string;
// Purchase Product ID.
product_id?: string;
// Raw provider notification body.
provider_notification?: string;
// Raw provider validation response body.
provider_response?: string;
// UNIX Timestamp when the purchase was done.
purchase_time?: string;
// Subscription refund time. If this time is set, the subscription was refunded.
refund_time?: string;
// The validation provider.
store?: ApiStoreProvider;
// UNIX Timestamp when the receipt validation was updated in DB.
update_time?: string;
// Subscription User ID.
user_id?: string;
}
/** A list of validated subscriptions stored by Nakama. */
export interface SubscriptionList {
// The cursor to send when retrieving the next page, if any.
cursor?: string;
// The cursor to send when retrieving the previous page, if any.
prev_cursor?: string;
// Stored validated subscriptions.
validated_subscriptions?: Array<ValidatedSubscription>;
}
/** A client for Nakama server. */
export class Client {
/** The expired timespan used to check session lifetime. */
public expiredTimespanMs = DEFAULT_EXPIRED_TIMESPAN_MS;
/** The low level API client for Nakama server. */
private readonly apiClient: NakamaApi;
constructor(
readonly serverkey = DEFAULT_SERVER_KEY,
readonly host = DEFAULT_HOST,
readonly port = DEFAULT_PORT,
readonly useSSL = false,
readonly timeout = DEFAULT_TIMEOUT_MS,
readonly autoRefreshSession = true) {
const scheme = (useSSL) ? "https://" : "http://";
const basePath = `${scheme}${host}:${port}`;
this.apiClient = new NakamaApi(serverkey, basePath, timeout);
}
/** Add users to a group, or accept their join requests. */
async addGroupUsers(session: Session, groupId: string, ids?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.addGroupUsers(session.token, groupId, ids).then((response: any) => {
return response !== undefined;
});
}
/** Add friends by ID or username to a user's account. */
async addFriends(session: Session, ids?: Array<string>, usernames?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.addFriends(session.token, ids, usernames).then((response: any) => {
return response !== undefined;
});
}
/** Authenticate a user with an Apple ID against the server. */
async authenticateApple(token: string, create?: boolean, username?: string, vars: Record<string, string> = {}, options: any = {}) {
const request = {
"token": token,
"vars": vars
};
return this.apiClient.authenticateApple(this.serverkey, "", request, create, username, options).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with a custom id against the server. */
authenticateCustom(id: string, create?: boolean, username?: string, vars: Record<string, string> = {}, options: any = {}): Promise<Session> {
const request = {
"id": id,
"vars": vars
};
return this.apiClient.authenticateCustom(this.serverkey, "", request, create, username, options).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with a device id against the server. */
authenticateDevice(id : string, create?: boolean, username?: string, vars? : Record<string, string>): Promise<Session> {
const request = {
"id": id,
"vars": vars
};
return this.apiClient.authenticateDevice(this.serverkey, "", request, create, username).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with an email+password against the server. */
authenticateEmail(email: string, password: string, create?: boolean, username?: string, vars?: Record<string,string>): Promise<Session> {
const request = {
"email": email,
"password": password,
"vars": vars
};
return this.apiClient.authenticateEmail(this.serverkey, "", request, create, username).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with a Facebook Instant Game token against the server. */
authenticateFacebookInstantGame(signedPlayerInfo: string, create?: boolean, username?: string, vars?: Record<string, string>, options: any = {}): Promise<Session> {
const request = {
"signed_player_info": signedPlayerInfo,
"vars": vars
};
return this.apiClient.authenticateFacebookInstantGame(this.serverkey, "",
{signed_player_info: request.signed_player_info, vars: request.vars}, create, username, options).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with a Facebook OAuth token against the server. */
authenticateFacebook(token : string, create?: boolean, username?: string, sync?: boolean, vars? : Record<string, string>, options: any = {}): Promise<Session> {
const request = {
"token": token,
"vars": vars
};
return this.apiClient.authenticateFacebook(this.serverkey, "", request, create, username, sync, options).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Authenticate a user with Google against the server. */
async authenticateGoogle(
token: string,
create?: boolean,
username?: string,
vars?: Record<string, string>,
options: any = {}
): Promise<Session> {
const request: ApiAccountGoogle = {
token,
vars,
};
const apiSession = await this.apiClient.authenticateGoogle(
this.serverkey,
"",
request,
create,
username,
options
);
return new Session(
apiSession.token || "",
apiSession.refresh_token || "",
apiSession.created || false
);
}
/** Authenticate a user with GameCenter against the server. */
async authenticateGameCenter(
bundleId: string,
playerId: string,
publicKeyUrl: string,
salt: string,
signature: string,
timestamp: string,
username?: string,
create?: boolean,
vars?: Record<string, string>,
options: any = {},
): Promise<Session> {
const request: ApiAccountGameCenter = {
bundle_id: bundleId,
player_id: playerId,
public_key_url: publicKeyUrl,
salt,
signature,
timestamp_seconds: timestamp,
vars,
};
const apiSession = await this.apiClient.authenticateGameCenter(
this.serverkey,
"",
request,
create,
username,
options
);
return new Session(
apiSession.token || "",
apiSession.refresh_token || "",
apiSession.created || false
);
}
/** Authenticate a user with Steam against the server. */
async authenticateSteam(token : string, create?: boolean, username?: string, sync?: boolean, vars? : Record<string, string>) : Promise<Session> {
const request = {
"token": token,
"vars": vars,
"sync": sync
};
return this.apiClient.authenticateSteam(this.serverkey, "", request, create, username).then((apiSession : ApiSession) => {
return new Session(apiSession.token || "", apiSession.refresh_token || "", apiSession.created || false);
});
}
/** Ban users from a group. */
async banGroupUsers(session: Session, groupId: string, ids?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.banGroupUsers(session.token, groupId, ids).then((response: any) => {
return response !== undefined;
});
}
/** Block one or more users by ID or username. */
async blockFriends(session: Session, ids?: Array<string>, usernames?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.blockFriends(session.token, ids, usernames).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Create a new group with the current user as the creator and superadmin. */
async createGroup(session: Session, request: ApiCreateGroupRequest): Promise<Group> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.createGroup(session.token, request).then((response: ApiGroup) => {
return Promise.resolve({
avatar_url: response.avatar_url,
create_time: response.create_time,
creator_id: response.creator_id,
description: response.description,
edge_count: response.edge_count? Number(response.edge_count) : 0,
id: response.id,
lang_tag: response.lang_tag,
max_count: response.max_count? Number(response.max_count) : 0,
metadata: response.metadata ? JSON.parse(response.metadata) : undefined,
name: response.name,
open: response.open,
update_time: response.update_time
});
});
}
/** A socket created with the client's configuration. */
createSocket(useSSL = false, verbose: boolean = false, adapter : WebSocketAdapter = new WebSocketAdapterText(), sendTimeoutMs : number = DefaultSocket.DefaultSendTimeoutMs): Socket {
return new DefaultSocket(this.host, this.port, useSSL, verbose, adapter, sendTimeoutMs);
}
/** Delete the current user's account. */
async deleteAccount(session: Session): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.deleteAccount(session.token).then((response: any) => {
return response !== undefined;
});
}
/** Delete one or more users by ID or username. */
async deleteFriends(session: Session, ids?: Array<string>, usernames?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.deleteFriends(session.token, ids, usernames).then((response: any) => {
return response !== undefined;
});
}
/** Delete a group the user is part of and has permissions to delete. */
async deleteGroup(session: Session, groupId: string): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.deleteGroup(session.token, groupId).then((response: any) => {
return response !== undefined;
});
}
/** Delete one or more notifications */
async deleteNotifications(session: Session, ids?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.deleteNotifications(session.token, ids).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Delete one or more storage objects */
async deleteStorageObjects(session: Session, request: ApiDeleteStorageObjectsRequest): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.deleteStorageObjects(session.token, request).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Delete a tournament record. */
async deleteTournamentRecord(session: Session, tournamentId: string): Promise<any> {
return this.apiClient.deleteTournamentRecord(session.token, tournamentId);
}
/** Demote a set of users in a group to the next role down. */
async demoteGroupUsers(session: Session, groupId: string, ids: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.demoteGroupUsers(session.token, groupId, ids).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Submit an event for processing in the server's registered runtime custom events handler. */
async emitEvent(session: Session, request: ApiEvent): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.event(session.token, request).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Fetch the current user's account. */
async getAccount(session: Session): Promise<ApiAccount> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.getAccount(session.token);
}
/** Get subscription by product id. */
async getSubscription(session: Session, productId: string): Promise<ApiValidatedSubscription> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.getSubscription(session.token, productId);
}
/** Import Facebook friends and add them to a user's account. */
async importFacebookFriends(session: Session, request: ApiAccountFacebook): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.importFacebookFriends(session.token, request).then((response: any) => {
return response !== undefined;
});
}
/** Import Steam friends and add them to a user's account. */
async importSteamFriends(session: Session, request: ApiAccountSteam, reset: boolean): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.importSteamFriends(session.token, request, reset).then((response: any) => {
return response !== undefined;
});
}
/** Fetch zero or more users by ID and/or username. */
async getUsers(session: Session, ids?: Array<string>, usernames?: Array<string>, facebookIds?: Array<string>): Promise<Users> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.getUsers(session.token, ids, usernames, facebookIds).then((response: ApiUsers) => {
var result: Users = {
users: []
};
if (response.users == null) {
return Promise.resolve(result);
}
response.users!.forEach(u => {
result.users!.push({
avatar_url: u.avatar_url,
create_time: u.create_time,
display_name: u.display_name,
edge_count: u.edge_count ? Number(u.edge_count) : 0,
facebook_id: u.facebook_id,
gamecenter_id: u.gamecenter_id,
google_id: u.google_id,
id: u.id,
lang_tag: u.lang_tag,
location: u.location,
online: u.online,
steam_id: u.steam_id,
timezone: u.timezone,
update_time: u.update_time,
username: u.username,
metadata: u.metadata ? JSON.parse(u.metadata) : undefined
})
});
return Promise.resolve(result);
});
}
/** Join a group that's open, or send a request to join a group that is closed. */
async joinGroup(session: Session, groupId: string): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.joinGroup(session.token, groupId, {}).then((response: any) => {
return response !== undefined;
});
}
async joinTournament(session: Session, tournamentId: string): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.joinTournament(session.token, tournamentId, {}).then((response: any) => {
return response !== undefined;
});
}
/** Kick users from a group, or decline their join requests. */
async kickGroupUsers(session: Session, groupId: string, ids?: Array<string>): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.kickGroupUsers(session.token, groupId, ids).then((response: any) => {
return Promise.resolve(response != undefined);
});
}
/** Leave a group the user is part of. */
async leaveGroup(session: Session, groupId: string): Promise<boolean> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.leaveGroup(session.token, groupId, {}).then((response: any) => {
return response !== undefined;
});
}
/** List a channel's message history. */
async listChannelMessages(session: Session, channelId: string, limit?: number, forward?: boolean, cursor?: string): Promise<ChannelMessageList> {
if (this.autoRefreshSession && session.refresh_token &&
session.isexpired((Date.now() + this.expiredTimespanMs)/1000)) {
await this.sessionRefresh(session);
}
return this.apiClient.listChannelMessages(session.token, channelId, limit, forward, cursor).then((response: ApiChannelMessageList) => {
var result: ChannelMessageList = {
messages: [],
next_cursor: response.next_cursor,
prev_cursor: response.prev_cursor,
cacheable_cursor: response.cacheable_cursor
};