-
Notifications
You must be signed in to change notification settings - Fork 716
/
leaderboardstools.ts
956 lines (861 loc) · 32.9 KB
/
leaderboardstools.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
/// <reference path="sha256.d.ts" />
// TODO EBO Replace runtimeScene to instanceContainer.
namespace gdjs {
const logger = new gdjs.Logger('Leaderboards');
export namespace evtTools {
export namespace leaderboards {
let _hasPlayerJustClosedLeaderboardView = false;
let _preferSendConnectedPlayerScore = true;
gdjs.registerRuntimeScenePostEventsCallback(() => {
// Set it back to false for the next frame.
_hasPlayerJustClosedLeaderboardView = false;
});
/**
* Returns true if the player has just closed the leaderboard view.
*/
export const hasPlayerJustClosedLeaderboardView = () =>
_hasPlayerJustClosedLeaderboardView;
const computeDigest = (payload: string): string => {
const shaObj = new jsSHA('SHA-256', 'TEXT', { encoding: 'UTF8' });
shaObj.update(payload);
return shaObj.getHash('B64');
};
const leaderboardHostBaseUrl = 'https://gd.games';
// const leaderboardHostBaseUrl = 'http://localhost:4000';
type PublicLeaderboardEntry = {
id: string;
claimSecret?: string;
};
/**
* Hold the state of the save of a score for a leaderboard.
*/
class ScoreSavingState {
lastScoreSavingStartedAt: number | null = null;
lastScoreSavingSucceededAt: number | null = null;
/** The promise that will be resolved when the score saving is done (successfully or not). */
lastSavingPromise: Promise<void> | null = null;
// Score that is being saved:
private _currentlySavingScore: number | null = null;
private _currentlySavingPlayerName: string | null = null;
private _currentlySavingPlayerId: string | null = null;
// Last score saved with success:
private _lastSavedScore: number | null = null;
private _lastSavedPlayerName: string | null = null;
private _lastSavedPlayerId: string | null = null;
/** The id of the entry in the leaderboard, for the last score saved with success. */
lastSavedLeaderboardEntry: PublicLeaderboardEntry | null = null;
/** Last error that happened when saving the score (useful if `hasScoreSavingErrored` is true). */
lastSaveError: string | null = null;
/** `true` if the last save has finished and succeeded. */
hasScoreBeenSaved: boolean = false;
/** `true` if the last save has finished and failed (check `lastSaveError` then). */
hasScoreSavingErrored: boolean = false;
isSaving(): boolean {
return (
!!this.lastSavingPromise &&
!this.hasScoreBeenSaved &&
!this.hasScoreSavingErrored
);
}
private _isSameAsLastScore({
playerName,
playerId,
score,
}: {
playerName?: string;
playerId?: string;
score: number;
}): boolean {
return (
((!!playerName && this._lastSavedPlayerName === playerName) ||
(!!playerId && this._lastSavedPlayerId === playerId)) &&
this._lastSavedScore === score
);
}
private _isAlreadySavingThisScore({
playerName,
playerId,
score,
}: {
playerName?: string;
playerId?: string;
score: number;
}): boolean {
if (!this.isSaving()) return false;
return (
((!!playerName && this._currentlySavingPlayerName === playerName) ||
(!!playerId && this._currentlySavingPlayerId === playerId)) &&
this._currentlySavingScore === score
);
}
private _isTooSoonToSaveAnotherScore(): boolean {
return (
!!this.lastScoreSavingStartedAt &&
Date.now() - this.lastScoreSavingStartedAt < 500
);
}
startSaving({
playerName,
playerId,
score,
}: {
playerName?: string;
playerId?: string;
score: number;
}): {
closeSaving: (leaderboardEntry: PublicLeaderboardEntry) => void;
closeSavingWithError(errorCode: string);
} {
if (this._isAlreadySavingThisScore({ playerName, playerId, score })) {
logger.warn(
'There is already a request to save with this player name and this score. Ignoring this one.'
);
throw new Error('Ignoring this saving request.');
}
if (this._isSameAsLastScore({ playerName, playerId, score })) {
logger.warn(
'The player and score to be sent are the same as previous one. Ignoring this one.'
);
this._setError('SAME_AS_PREVIOUS');
throw new Error('Ignoring this saving request.');
}
if (this._isTooSoonToSaveAnotherScore()) {
logger.warn(
'Last entry was sent too little time ago. Ignoring this one.'
);
this._setError('TOO_FAST');
// Set the starting time to cancel all the following attempts that
// are started too early after this one.
this.lastScoreSavingStartedAt = Date.now();
throw new Error('Ignoring this saving request.');
}
let resolveSavingPromise: () => void;
const savingPromise = new Promise<void>((resolve) => {
resolveSavingPromise = resolve;
});
this.lastScoreSavingStartedAt = Date.now();
this.lastSavingPromise = savingPromise;
this.hasScoreBeenSaved = false;
this.hasScoreSavingErrored = false;
this._currentlySavingScore = score;
if (playerName) this._currentlySavingPlayerName = playerName;
if (playerId) this._currentlySavingPlayerId = playerId;
return {
closeSaving: (leaderboardEntry) => {
if (savingPromise !== this.lastSavingPromise) {
logger.info(
'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'
);
// Still finish the promise that can be waited upon:
resolveSavingPromise();
return;
}
this.lastScoreSavingSucceededAt = Date.now();
this._lastSavedScore = this._currentlySavingScore;
this._lastSavedPlayerName = this._currentlySavingPlayerName;
this._lastSavedPlayerId = this._currentlySavingPlayerId;
this.lastSavedLeaderboardEntry = leaderboardEntry;
this.hasScoreBeenSaved = true;
resolveSavingPromise();
},
closeSavingWithError: (errorCode) => {
if (savingPromise !== this.lastSavingPromise) {
logger.info(
'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'
);
// Still finish the promise that can be waited upon:
resolveSavingPromise();
return;
}
this._setError(errorCode);
resolveSavingPromise();
},
};
}
private _setError(errorCode: string): void {
this.lastSaveError = errorCode;
this.hasScoreBeenSaved = false;
this.hasScoreSavingErrored = true;
}
}
let _scoreSavingStateByLeaderboard: {
[leaderboardId: string]: ScoreSavingState;
} = {};
// Leaderboard display
let _requestedLeaderboardId: string | null;
let _leaderboardViewIframe: HTMLIFrameElement | null = null;
let _leaderboardViewIframeErrored: boolean = false;
let _leaderboardViewIframeLoading: boolean = false;
let _leaderboardViewIframeLoaded: boolean = false;
let _errorTimeoutId: NodeJS.Timeout | null = null;
let _leaderboardMessageListener:
| ((event: MessageEvent) => void)
| null = null;
const _loaderContainer: HTMLDivElement = document.createElement('div');
_loaderContainer.style.backgroundColor = '#000000';
_loaderContainer.style.display = 'flex';
_loaderContainer.style.height = '100%';
_loaderContainer.style.width = '100%';
_loaderContainer.style.justifyContent = 'center';
_loaderContainer.style.alignItems = 'center';
_loaderContainer.style.position = 'relative';
_loaderContainer.style.zIndex = '2';
const _loader = document.createElement('img');
_loader.setAttribute('width', '50px');
_loader.setAttribute(
'src',
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCI+CjxjaXJjbGUgb3BhY2l0eT0nMC4yNScgY3g9IjEyIiBjeT0iMTIiIHI9IjEwIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iNCI+PC9jaXJjbGU+CjxwYXRoIG9wYWNpdHk9JzAuNzUnIGZpbGw9IiNGRkZGRkYiIGQ9Ik00IDEyYTggOCAwIDAxOC04VjBDNS4zNzMgMCAwIDUuMzczIDAgMTJoNHptMiA1LjI5MUE3Ljk2MiA3Ljk2MiAwIDAxNCAxMkgwYzAgMy4wNDIgMS4xMzUgNS44MjQgMyA3LjkzOGwzLTIuNjQ3eiI+PC9wYXRoPgo8L3N2Zz4='
);
try {
_loader.animate(
[{ transform: 'rotate(0deg)' }, { transform: 'rotate(359deg)' }],
{
duration: 3000,
iterations: Infinity,
}
);
} catch {
logger.warn('Animation not supported, loader will be fixed.');
}
_loaderContainer.appendChild(_loader);
/** Get the saving state of the leaderboard who had the last update (successful or started). */
const getLastScoreSavingState = function ({
hasSucceeded,
}: {
hasSucceeded: boolean;
}): ScoreSavingState | null {
const getDateField = (scoreSavingState: ScoreSavingState) =>
hasSucceeded
? scoreSavingState.lastScoreSavingSucceededAt
: scoreSavingState.lastScoreSavingStartedAt;
const scoreSavingStates = Object.values(
_scoreSavingStateByLeaderboard
).filter((scoreSavingState) => !!getDateField(scoreSavingState));
if (scoreSavingStates.length === 0) return null;
let lastScoreSavingState = scoreSavingStates[0];
scoreSavingStates.forEach((scoreSavingState) => {
const currentItemDate = getDateField(scoreSavingState);
const lastItemDate = getDateField(lastScoreSavingState);
if (
currentItemDate &&
lastItemDate &&
currentItemDate > lastItemDate
) {
lastScoreSavingState = scoreSavingState;
}
});
return lastScoreSavingState;
};
const saveScore = async function ({
leaderboardId,
playerName,
authenticatedPlayerData,
score,
runtimeScene,
}: {
leaderboardId: string;
playerName?: string | null;
authenticatedPlayerData?: { playerId: string; playerToken: string };
score: number;
runtimeScene: gdjs.RuntimeScene;
}): Promise<PublicLeaderboardEntry> {
const rootApi = runtimeScene
.getGame()
.isUsingGDevelopDevelopmentEnvironment()
? 'https://api-dev.gdevelop.io'
: 'https://api.gdevelop.io';
const baseUrl = `${rootApi}/play`;
const game = runtimeScene.getGame();
const payloadObject = {
score: score,
sessionId: game.getSessionId(),
clientPlayerId: game.getPlayerId(),
location:
typeof window !== 'undefined' && (window as any).location
? (window as any).location.href
: '',
};
const headers = {
'Content-Type': 'application/json',
};
let leaderboardEntryCreationUrl = `${baseUrl}/game/${gdjs.projectData.properties.projectUuid}/leaderboard/${leaderboardId}/entry`;
if (authenticatedPlayerData) {
headers[
'Authorization'
] = `player-game-token ${authenticatedPlayerData.playerToken}`;
leaderboardEntryCreationUrl += `?playerId=${authenticatedPlayerData.playerId}`;
} else {
// In case playerName is empty, the backend will generate a random name.
payloadObject['playerName'] = formatPlayerName(playerName);
}
const payload = JSON.stringify(payloadObject);
headers['Digest'] = computeDigest(payload);
try {
const response = await fetch(leaderboardEntryCreationUrl, {
body: payload,
method: 'POST',
headers: headers,
});
if (!response.ok) {
const errorCode = response.status.toString();
logger.error(
'Server responded with an error:',
errorCode,
response.statusText
);
throw errorCode;
}
try {
const leaderboardEntry = await response.json();
return leaderboardEntry;
} catch (error) {
logger.warn(
'An error occurred when reading response but score has been saved:',
error
);
const errorCode = 'SAVED_ENTRY_CANT_BE_READ';
throw errorCode;
}
} catch (error) {
logger.error('Error while submitting a leaderboard score:', error);
const errorCode = 'REQUEST_NOT_SENT';
throw errorCode;
}
};
export const setPreferSendConnectedPlayerScore = (
runtimeScene: gdjs.RuntimeScene,
enable: boolean
) => {
_preferSendConnectedPlayerScore = enable;
};
export const savePlayerScore = (
runtimeScene: gdjs.RuntimeScene,
leaderboardId: string,
score: float,
playerName: string
) => {
if (
_preferSendConnectedPlayerScore &&
gdjs.playerAuthentication.isAuthenticated()
) {
return saveConnectedPlayerScore(runtimeScene, leaderboardId, score);
}
return new gdjs.PromiseTask(
(async () => {
const scoreSavingState = (_scoreSavingStateByLeaderboard[
leaderboardId
] =
_scoreSavingStateByLeaderboard[leaderboardId] ||
new ScoreSavingState());
try {
const {
closeSaving,
closeSavingWithError,
} = scoreSavingState.startSaving({ playerName, score });
try {
const leaderboardEntry = await saveScore({
leaderboardId,
playerName,
score,
runtimeScene,
});
closeSaving(leaderboardEntry);
} catch (errorCode) {
closeSavingWithError(errorCode);
}
} catch {
// Do nothing: saving was rejected for a reason already logged.
}
})()
);
};
export const saveConnectedPlayerScore = (
runtimeScene: gdjs.RuntimeScene,
leaderboardId: string,
score: float
) =>
new gdjs.PromiseTask(
(async () => {
const playerId = gdjs.playerAuthentication.getUserId();
const playerToken = gdjs.playerAuthentication.getUserToken();
if (!playerId || !playerToken) {
logger.warn(
'Cannot save a score for a connected player if the player is not connected.'
);
return;
}
const scoreSavingState = (_scoreSavingStateByLeaderboard[
leaderboardId
] =
_scoreSavingStateByLeaderboard[leaderboardId] ||
new ScoreSavingState());
try {
const {
closeSaving,
closeSavingWithError,
} = scoreSavingState.startSaving({ playerId, score });
try {
const leaderboardEntryId = await saveScore({
leaderboardId,
authenticatedPlayerData: { playerId, playerToken },
score,
runtimeScene,
});
closeSaving(leaderboardEntryId);
} catch (errorCode) {
closeSavingWithError(errorCode);
}
} catch {
// Do nothing: saving was rejected for a reason already logged.
}
})()
);
export const isSaving = function (leaderboardId?: string): boolean {
if (leaderboardId) {
return _scoreSavingStateByLeaderboard[leaderboardId]
? _scoreSavingStateByLeaderboard[leaderboardId].isSaving()
: false;
}
const lastScoreSavingState = getLastScoreSavingState({
hasSucceeded: false,
});
return lastScoreSavingState ? lastScoreSavingState.isSaving() : false;
};
export const hasBeenSaved = function (leaderboardId?: string): boolean {
if (leaderboardId) {
return _scoreSavingStateByLeaderboard[leaderboardId]
? _scoreSavingStateByLeaderboard[leaderboardId].hasScoreBeenSaved
: false;
}
const lastScoreSavingState = getLastScoreSavingState({
hasSucceeded: true,
});
return lastScoreSavingState
? lastScoreSavingState.hasScoreBeenSaved
: false;
};
export const hasSavingErrored = function (
leaderboardId?: string
): boolean {
if (leaderboardId) {
return _scoreSavingStateByLeaderboard[leaderboardId]
? _scoreSavingStateByLeaderboard[leaderboardId]
.hasScoreSavingErrored
: false;
}
const lastScoreSavingState = getLastScoreSavingState({
hasSucceeded: false,
});
return lastScoreSavingState
? lastScoreSavingState.hasScoreSavingErrored
: false;
};
export const getLastSaveError = function (
leaderboardId?: string
): string | null {
if (leaderboardId) {
return _scoreSavingStateByLeaderboard[leaderboardId]
? _scoreSavingStateByLeaderboard[leaderboardId].lastSaveError
: 'NO_DATA_ERROR';
}
const lastScoreSavingState = getLastScoreSavingState({
hasSucceeded: false,
});
return lastScoreSavingState
? lastScoreSavingState.lastSaveError
: 'NO_DATA_ERROR';
};
export const formatPlayerName = function (
rawName?: string | null
): string {
if (
!rawName ||
typeof rawName !== 'string' ||
(typeof rawName === 'string' && rawName.length === 0)
) {
return '';
}
return rawName
.trim()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/\s/g, '_')
.replace(/[^\w|-]/g, '')
.slice(0, 30);
};
const checkLeaderboardAvailability = function (
url: string
): Promise<boolean> {
return fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
}).then(
(response) => {
if (!response.ok) {
logger.error(
`Error while fetching leaderboard view, server returned: ${response.status} ${response.statusText}`
);
return false;
}
return true;
},
(err) => {
logger.error('Error while fetching leaderboard view:', err);
return false;
}
);
};
const receiveMessageFromLeaderboardView = function (
runtimeScene: gdjs.RuntimeScene,
displayLoader: boolean,
event: MessageEvent
) {
const messageId =
typeof event.data === 'string' ? event.data : event.data.id;
switch (messageId) {
case 'playerAuthenticated':
gdjs.playerAuthentication.login({
runtimeScene,
userId: event.data.userId,
username: event.data.username,
userToken: event.data.userToken,
});
break;
case 'openPlayerAuthentication':
gdjs.playerAuthentication
.openAuthenticationWindow(runtimeScene)
.promise.then(({ status }) => {
if (
!_leaderboardViewIframe ||
!_leaderboardViewIframe.contentWindow
) {
logger.warn(
'Unable to transmit the new login status to the leaderboard view.'
);
return;
}
if (status === 'errored') {
_leaderboardViewIframe.contentWindow.postMessage(
{
id: 'onPlayerAuthenticationErrored',
},
leaderboardHostBaseUrl
);
return;
}
const playerId = gdjs.playerAuthentication.getUserId();
const playerToken = gdjs.playerAuthentication.getUserToken();
if (status === 'dismissed' || !playerId || !playerToken) {
_leaderboardViewIframe.contentWindow.postMessage(
{
id: 'onPlayerAuthenticationDismissed',
},
leaderboardHostBaseUrl
);
return;
}
_leaderboardViewIframe.contentWindow.postMessage(
{
id: 'onPlayerAuthenticated',
playerId,
playerUsername: gdjs.playerAuthentication.getUsername(),
playerToken: playerToken,
},
leaderboardHostBaseUrl
);
});
break;
case 'closeLeaderboardView':
_hasPlayerJustClosedLeaderboardView = true;
closeLeaderboardView(runtimeScene);
break;
case 'leaderboardViewLoaded':
if (displayLoader) {
if (_errorTimeoutId) clearTimeout(_errorTimeoutId);
displayLoaderInLeaderboardView(false, runtimeScene, {
callOnErrorIfDomElementContainerMissing: false,
});
}
if (!_leaderboardViewIframe) {
handleErrorDisplayingLeaderboard(
runtimeScene,
"The leaderboard view couldn't be found. Doing nothing."
);
return;
}
_leaderboardViewIframe.style.opacity = '1';
_leaderboardViewIframeLoaded = true;
_leaderboardViewIframeLoading = false;
break;
}
};
const handleErrorDisplayingLeaderboard = function (
runtimeScene: gdjs.RuntimeScene,
message: string
) {
logger.error(message);
_leaderboardViewIframeErrored = true;
_leaderboardViewIframeLoading = false;
closeLeaderboardView(runtimeScene);
};
const resetLeaderboardDisplayErrorTimeout = (
runtimeScene: gdjs.RuntimeScene
) => {
if (_errorTimeoutId) clearTimeout(_errorTimeoutId);
_errorTimeoutId = setTimeout(() => {
if (!_leaderboardViewIframeLoaded) {
handleErrorDisplayingLeaderboard(
runtimeScene,
'Leaderboard page did not send message in time. Closing leaderboard view.'
);
}
}, 15000);
};
const displayLoaderInLeaderboardView = function (
yesOrNo: boolean,
runtimeScene: gdjs.RuntimeScene,
options: { callOnErrorIfDomElementContainerMissing: boolean }
): boolean {
const domElementContainer = runtimeScene
.getGame()
.getRenderer()
.getDomElementContainer();
if (!domElementContainer) {
if (options.callOnErrorIfDomElementContainerMissing) {
handleErrorDisplayingLeaderboard(
runtimeScene,
"The div element covering the game couldn't be found, the leaderboard cannot be displayed."
);
}
return false;
}
if (yesOrNo) {
if (
domElementContainer.children &&
domElementContainer.children.length > 0
) {
domElementContainer.insertBefore(
_loaderContainer,
domElementContainer.children[0]
);
} else {
domElementContainer.appendChild(_loaderContainer);
}
if (_leaderboardViewIframe) {
_leaderboardViewIframe.style.opacity = '0';
}
} else {
try {
domElementContainer.removeChild(_loaderContainer);
if (_leaderboardViewIframe) {
_leaderboardViewIframe.style.opacity = '1';
}
} catch {}
}
return true;
};
const computeLeaderboardDisplayingIframe = function (
url: string
): HTMLIFrameElement {
const iframe = document.createElement('iframe');
iframe.src = url;
iframe.id = 'leaderboard-view';
iframe.style.position = 'absolute';
// To trigger iframe loading and be able to listen to its events, use `opacity: 0` instead of `visibility: hidden` or `display: none`
iframe.style.opacity = '0';
iframe.style.pointerEvents = 'all';
iframe.style.backgroundColor = '#FFFFFF';
iframe.style.top = '0px';
iframe.style.height = '100%';
iframe.style.left = '0px';
iframe.style.width = '100%';
iframe.style.border = 'none';
return iframe;
};
export const displayLeaderboard = async function (
runtimeScene: gdjs.RuntimeScene,
leaderboardId: string,
displayLoader: boolean
) {
// First ensure we're not trying to display multiple times the same leaderboard (in which case
// we "de-duplicate" the request to display it).
if (leaderboardId === _requestedLeaderboardId) {
if (_leaderboardViewIframeLoading) {
logger.warn(
`Already loading the view for the requested loader (${leaderboardId}), ignoring.`
);
return;
}
if (_leaderboardViewIframeLoaded) {
logger.warn(
`Already loaded the view for the requested loader (${leaderboardId}), ignoring.`
);
return;
}
}
// We are now assured we want to display a new (or different) leaderboard: start loading it.
_requestedLeaderboardId = leaderboardId;
_leaderboardViewIframeErrored = false;
_leaderboardViewIframeLoaded = false;
_leaderboardViewIframeLoading = true;
if (displayLoader) {
displayLoaderInLeaderboardView(true, runtimeScene, {
callOnErrorIfDomElementContainerMissing: true,
});
}
// If a save is being done for this leaderboard, wait for it to end so that the `lastSavedLeaderboardEntry`
// can be saved and then used to show the player score.
const scoreSavingState = _scoreSavingStateByLeaderboard[leaderboardId];
if (scoreSavingState && scoreSavingState.lastSavingPromise) {
await scoreSavingState.lastSavingPromise;
}
const lastSavedLeaderboardEntry = scoreSavingState
? scoreSavingState.lastSavedLeaderboardEntry
: null;
const gameId = gdjs.projectData.properties.projectUuid;
const isDev = runtimeScene
.getGame()
.isUsingGDevelopDevelopmentEnvironment();
const searchParams = new URLSearchParams();
searchParams.set('inGameEmbedded', 'true');
if (isDev) searchParams.set('dev', 'true');
if (lastSavedLeaderboardEntry) {
searchParams.set(
'playerLeaderboardEntryId',
lastSavedLeaderboardEntry.id
);
if (lastSavedLeaderboardEntry.claimSecret) {
searchParams.set(
'playerLeaderboardEntryClaimSecret',
lastSavedLeaderboardEntry.claimSecret
);
}
}
const playerId = gdjs.playerAuthentication.getUserId();
const playerToken = gdjs.playerAuthentication.getUserToken();
if (playerId && playerToken) {
searchParams.set('playerId', playerId);
searchParams.set('playerToken', playerToken);
searchParams.set(
'playerUsername',
gdjs.playerAuthentication.getUsername()
);
}
const targetUrl = `${leaderboardHostBaseUrl}/games/${gameId}/leaderboard/${leaderboardId}?${searchParams}`;
try {
const isAvailable = await checkLeaderboardAvailability(targetUrl);
if (leaderboardId !== _requestedLeaderboardId) {
logger.warn(
`Received a response for leaderboard ${leaderboardId} though the last leaderboard requested is ${_requestedLeaderboardId}, ignoring this response.`
);
return;
}
if (!isAvailable) {
handleErrorDisplayingLeaderboard(
runtimeScene,
'Leaderboard data could not be fetched. Closing leaderboard view if there is one.'
);
return;
}
if (_leaderboardViewIframe) {
resetLeaderboardDisplayErrorTimeout(runtimeScene);
if (displayLoader) {
displayLoaderInLeaderboardView(true, runtimeScene, {
callOnErrorIfDomElementContainerMissing: false,
});
}
_leaderboardViewIframe.src = targetUrl;
} else {
const domElementContainer = runtimeScene
.getGame()
.getRenderer()
.getDomElementContainer();
if (!domElementContainer) {
handleErrorDisplayingLeaderboard(
runtimeScene,
"The div element covering the game couldn't be found, the leaderboard cannot be displayed."
);
return;
}
resetLeaderboardDisplayErrorTimeout(runtimeScene);
_leaderboardViewIframe = computeLeaderboardDisplayingIframe(
targetUrl
);
if (typeof window !== 'undefined') {
_leaderboardMessageListener = (event: MessageEvent) => {
receiveMessageFromLeaderboardView(
runtimeScene,
displayLoader,
event
);
};
(window as any).addEventListener(
'message',
_leaderboardMessageListener,
true
);
}
domElementContainer.appendChild(_leaderboardViewIframe);
}
} catch (err) {
logger.error(err);
handleErrorDisplayingLeaderboard(
runtimeScene,
'An error occurred when fetching leaderboard data. Closing leaderboard view if there is one.'
);
}
};
export const isLeaderboardViewErrored = function (): boolean {
return _leaderboardViewIframeErrored;
};
export const isLeaderboardViewLoaded = function (): boolean {
return _leaderboardViewIframeLoaded;
};
export const isLeaderboardViewLoading = function (): boolean {
return _leaderboardViewIframeLoading;
};
export const closeLeaderboardView = function (
runtimeScene: gdjs.RuntimeScene
) {
try {
displayLoaderInLeaderboardView(false, runtimeScene, {
callOnErrorIfDomElementContainerMissing: false,
});
if (!_leaderboardViewIframe) {
logger.info(
"The iframe displaying the current leaderboard couldn't be found, the leaderboard view must be already closed."
);
return;
}
const domElementContainer = runtimeScene
.getGame()
.getRenderer()
.getDomElementContainer();
if (!domElementContainer) {
logger.info(
"The div element covering the game couldn't be found, the leaderboard view must be already closed."
);
return;
}
if (typeof window !== 'undefined') {
(window as any).removeEventListener(
'message',
_leaderboardMessageListener,
true
);
_leaderboardMessageListener = null;
}
domElementContainer.removeChild(_leaderboardViewIframe);
_leaderboardViewIframe = null;
} finally {
// Don't reset the loading flag (the view of another leaderboard might be loading)
// or the error flag (we want to persist the error flag even after the view is closed),
// but reset the flag indicating the view is loaded (if it was).
_leaderboardViewIframeLoaded = false;
const gameCanvas = runtimeScene.getGame().getRenderer().getCanvas();
if (gameCanvas) gameCanvas.focus();
}
};
}
}
}