-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathairconsole-1.9.0.js
1596 lines (1473 loc) · 59.3 KB
/
airconsole-1.9.0.js
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
/**
* AirConsole.
* @copyright 2024 by N-Dream AG, Switzerland. All rights reserved.
* @version 1.9.0
*
* IMPORTANT:
* @see http://developers.airconsole.com/ for API documentation
*
* This file is grouped into the following chapters:
* - Constants: Constants you should use
* - Connectivity: Device Ids, connects and disconnects
* - Messaging: Sending messages between devices
* - Device States: Setting data for a device that is readable for all devices
* - Profile data: User profile data, including nicknames and profile pictures
* - Active players: Setting a couple of devices as active players for a game
* - Controller Inputs: Special device inputs like device motion
* - Ads: Showing ads and handling their events
* - Premium: Handling premium users
* - Navigation: Changing games and opening external links
* - User Interface: Changing orientation
* - Persistent Data: Storing data across sessions
* - High Scores: Storing and retrieving high scores
* - Environment Events: Events triggered by the real world
*
* If your prefer an event driven api with .on() .off() and .dispatch()
* interface instead of sending messages,
* @see http://github.com/AirConsole/airconsole-events/
*
*/
/**
* Your gateway object to AirConsole.
* There are getter and setter functions for all properties.
* Do not access properties of this object directly.
* @constructor
* @param {AirConsole~Config} opts - Constructor config, see bellow.
* @return {AirConsoleObject} The AirConsole object.
*/
function AirConsole(opts) {
this.init_(opts);
}
/**
* The configuration for the AirConsole constructor.
* @typedef {object} AirConsole~Config
* @property {string} orientation - AirConsole.ORIENTATION_PORTRAIT or
* AirConsole.ORIENTATION_LANDSCAPE.
* @property {boolean|undefined} synchronize_time - If set to true, you can
* call getServerTime() to get the time on the game server.
* Default is false.
* @property {boolean|undefined} setup_document - Sets up the document so
* nothing is selectable, zoom is fixed to 1 and scrolling is
* disabled (iOS 8 clients drop out of fullscreen when scrolling).
* Default: true
* @property {number|undefined} device_motion - If set, onDeviceMotion gets
* called every "device_motion" milliseconds with data from the
* accelerometer and the gyroscope. Only for controllers.
* @property {boolean} translation - If an AirConsole translation file should
* be loaded.
* @property {boolean} [silence_inactive_players] - If set, newly joining devices will be
* prompted to wait while an active game is going on.<br />
* To start a game round, call setActivePlayers(X) with X larger than 0 eg 1,2,3,...<br />
* To finish a game round, call setActivePlayers(0).<br />
* Default: true, unless the game uses the automatically upgrading API version.<br />
* See {@link https://developers.airconsole.com/#!/guides/player_silencing Player Silencing Guide} for details.<br />
* Added in 1.9.0
*/
/** ------------------------------------------------------------------------ *
* @chapter CONSTANTS *
* ------------------------------------------------------------------------- */
/**
* The device ID of the game screen.
* @constant {number}
*/
AirConsole.SCREEN = 0;
/**
* The portrait orientation.
* @constant {string}
*/
AirConsole.ORIENTATION_PORTRAIT = "portrait";
/**
* The landscape orientation.
* @constant {string}
*/
AirConsole.ORIENTATION_LANDSCAPE = "landscape";
/** ------------------------------------------------------------------------ *
* @chapter CONNECTIVITY *
* @see http://developers.airconsole.com/#!/guides/pong *
* ------------------------------------------------------------------------- */
/**
* Gets called when the game console is ready.
* This event also fires onConnect for all devices that already are
* connected and have loaded your game.
* This event also fires onCustomDeviceStateChange for all devices that are
* connected, have loaded your game and have set a custom Device State.
* @abstract
* @param {string} code - The AirConsole join code.
*/
AirConsole.prototype.onReady = function(code) {};
/**
* Gets called when a device has connected and loaded the game.
* @abstract
* @param {number} device_id - the device ID that loaded the game.
*/
AirConsole.prototype.onConnect = function(device_id) {};
/**
* Gets called when a device has left the game.
* @abstract
* @param {number} device_id - the device ID that left the game.
*/
AirConsole.prototype.onDisconnect = function(device_id) {};
/**
* Returns the device_id of this device.
* Every device in an AirConsole session has a device_id.
* The screen always has device_id 0. You can use the AirConsole.SCREEN
* constant instead of 0.
* All controllers also get a device_id. You can NOT assume that the device_ids
* of controllers are consecutive or that they start at 1.
*
* DO NOT HARDCODE CONTROLLER DEVICE IDS!
*
* If you want to have a logic with "players numbers" (Player 0, Player 1,
* Player 2, Player 3) use the setActivePlayers helper function! You can
* hardcode player numbers, but not device_ids.
*
* Within an AirConsole session, devices keep the same device_id when they
* disconnect and reconnect. Different controllers will never get the same
* device_id in a session. Every device_id remains reserved for the device that
* originally got it.
*
* @see http:// developers.airconsole.com/#/guides/device_ids_and_states
*
* @return {number}
*/
AirConsole.prototype.getDeviceId = function() {
return this.device_id;
};
/**
* Returns the device ID of the master controller.
* Premium devices are prioritzed.
* @return {number|undefined}
*/
AirConsole.prototype.getMasterControllerDeviceId = function() {
var premium_device_ids = this.getPremiumDeviceIds();
if (premium_device_ids.length) {
return premium_device_ids[0];
}
return this.getControllerDeviceIds()[0];
};
/**
* Returns all controller device ids that have loaded your game.
* @return {Array}
*/
AirConsole.prototype.getControllerDeviceIds = function() {
var result = [];
var game_url = this.getGameUrl_(this.getLocationUrl_());
for (var i = AirConsole.SCREEN + 1; i < this.devices.length; ++i) {
if (this.devices[i] &&
this.getGameUrl_(this.devices[i].location) == game_url) {
result.push(i);
}
}
return result;
};
/**
* Returns the current time of the game server.
* This allows you to have a synchronized clock: You can send the server
* time in a message to know exactly at what point something happened on a
* device. This function can only be called if the AirConsole was instantiated
* with the "synchronize_time" opts set to true and after onReady was called.
* @return {number} Timestamp in milliseconds.
*/
AirConsole.prototype.getServerTime = function() {
if (this.server_time_offset === false) {
throw "AirConsole constructor was not called with " +
"{synchronize_time: true}";
}
return new Date().getTime() + this.server_time_offset;
};
/**
* Queries, if new devices are currently silenced.
* @returns {boolean} True, if new devices that are not players are silenced.
* @since 1.9.0
*/
AirConsole.prototype.arePlayersSilenced = function () {
if(this.devices[AirConsole.SCREEN] === undefined) {
return false;
}
var playersSilenced = this.devices[AirConsole.SCREEN].hasOwnProperty("silencePlayers") ? this.devices[AirConsole.SCREEN]["silencePlayers"] : false;
return (!!this.silence_inactive_players || playersSilenced)
&& (this.devices[AirConsole.SCREEN]["players"] !== undefined && this.devices[AirConsole.SCREEN]["players"].length > 0);
}
/**
* Dictionary of silenced update messages queued during a running game session.
* @private
* @since 1.9.0
*/
AirConsole.prototype.silencedUpdatesQueue_ = {};
/** ------------------------------------------------------------------------ *
* @chapter MESSAGING *
* @see http://developers.airconsole.com/#!/guides/pong *
* ------------------------------------------------------------------------- */
/**
* Sends a message to another device.
* @param device_id {number|undefined} - The device ID to send the message to.
* If "device_id" is undefined, the
* message is sent to all devices (except
* this one).
* @param data
*/
AirConsole.prototype.message = function (device_id, data) {
if (this.device_id !== undefined && !this.deviceIsSilenced_(device_id)) {
AirConsole.postMessage_({ action: "message", to: device_id, data: data });
}
}
/**
* Sends a message to all connected devices.
* @param data
*/
AirConsole.prototype.broadcast = function(data) {
this.message(undefined, data);
};
/**
* Gets called when a message is received from another device
* that called message() or broadcast().
* If you dont want to parse messages yourself and prefer an event driven
* approach, @see http://github.com/AirConsole/airconsole-events/
* @abstract
* @param {number} device_id - The device ID that sent the message.
* @param {serializable} data - The data that was sent.
*/
AirConsole.prototype.onMessage = function(device_id, data) {};
/** ------------------------------------------------------------------------ *
* @chapter DEVICE STATES *
* @see http://developers.airconsole.com/#!/guides/device_ids_and_states *
* ------------------------------------------------------------------------- */
/**
* Gets the custom DeviceState of a device.
* @param {number|undefined} device_id - The device ID of which you want the
* custom state. Default is this device.
* @return {Object|undefined} The custom data previously set by the device.
*/
AirConsole.prototype.getCustomDeviceState = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data && this.getGameUrl_(this.getLocationUrl_()) ==
this.getGameUrl_(device_data.location)) {
return device_data["custom"];
}
};
/**
* Sets the custom DeviceState of this device.
* @param {Object} data - The custom data to set.
*/
AirConsole.prototype.setCustomDeviceState = function(data) {
if (this.device_id !== undefined) {
this.devices[this.device_id]["custom"] = data;
this.set_("custom", data);
}
};
/**
* Sets a property in the custom DeviceState of this device.
* @param {String} key - The property name.
* @param {mixed} value - The property value.
*/
AirConsole.prototype.setCustomDeviceStateProperty = function(key, value) {
if (this.device_id !== undefined) {
var state = this.getCustomDeviceState();
if (state === undefined) {
state = {};
} else if (typeof state !== "object") {
throw "Custom DeviceState needs to be of type object";
}
state[key] = value;
this.setCustomDeviceState(state);
}
};
/**
* @typedef {Object} ImmersiveLightOption
* @property {number} r - The red value of the light. Format: integer between 0 and 255.
* @property {number} g - The green value of the light. Format: integer between 0 and 255.
* @property {number} b - The blue value of the light. Format: integer between 0 and 255.
*/
/**
* @typedef {Object} ImmersiveOption
* @property {ImmersiveLightOption} [light] - Light state inside the car.
* @property {any} [experiment] - Experimental payload for experimental APIs
* */
/**
* Sets the immersive state of the AirConsole game based on the provided options.<br />
* At least one property is required for the immersive state to be set.
*
* @param {ImmersiveOption} immersiveState - The immersive state to send.
*/
AirConsole.prototype.setImmersiveState = function (immersiveState) {
if (this.device_id !== AirConsole.SCREEN) {
throw 'Only the screen can set the immersive state.';
}
if (immersiveState === undefined || typeof immersiveState !== 'object' || Object.keys(immersiveState).length === 0) {
return;
}
if (immersiveState.light === undefined && immersiveState.experiment === undefined) {
return;
}
this.set_('immersive', immersiveState);
};
/**
* Gets called when a device updates it's custom DeviceState
* by calling setCustomDeviceState or setCustomDeviceStateProperty.
* Make sure you understand the power of device states:
* @see http://developers.airconsole.com/#/guides/device_ids_and_states
* @abstract
* @param {number} device_id - the device ID that changed its custom
* DeviceState.
* @param {Object} custom_data - The custom DeviceState data value
*/
AirConsole.prototype.onCustomDeviceStateChange = function(device_id,
custom_data) {};
/**
* Gets called when a device joins/leaves a game session or updates its
* DeviceState (custom DeviceState, profile pic, nickname, internal state).
* This is function is also called every time onConnect, onDisconnect or
* onCustomDeviceStateChange, onDeviceProfileChange is called.
* It's like their root function.
* @abstract
* @param {number} device_id - the device_id that changed its DeviceState.
* @param user_data {AirConsole~DeviceState} - the data of that device.
* If undefined, the device has left.
*/
AirConsole.prototype.onDeviceStateChange = function(device_id, device_data) {};
/** ------------------------------------------------------------------------ *
* @chapter PROFILE *
* ------------------------------------------------------------------------- */
/**
* Returns the globally unique id of a device.
* @param {number|undefined} device_id - The device id for which you want the
* uid. Default is this device.
* @return {string|undefined}
*/
AirConsole.prototype.getUID = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data) {
return device_data.uid;
}
};
/**
* Returns the nickname of a user.
* @param {number|undefined} device_id - The device id for which you want the
* nickname. Default is this device.
* Screens don't have nicknames.
* @return {string|undefined}
*/
AirConsole.prototype.getNickname = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data) {
return device_data.nickname || ("Guest " + device_id);
}
};
/**
* Returns the url to a profile picture of the user.
* @param {number|string|undefined} device_id_or_uid - The device id or uid for
* which you want the
* profile picture.
* Default is the current
* user.
* Screens don't have
* profile pictures.
* @param {number|undefined} size - The size of in pixels of the picture.
* Default is 64.
* @return {string|undefined}
*/
AirConsole.prototype.getProfilePicture = function(device_id_or_uid, size) {
if (device_id_or_uid === undefined) {
device_id_or_uid = this.device_id;
} else if (typeof device_id_or_uid == "string") {
return "https://www.airconsole.com/api/profile-picture?uid=" +
device_id_or_uid + "&size=" + (size||64);
}
var device_data = this.devices[device_id_or_uid];
if (device_data) {
var url = "https://www.airconsole.com/api/profile-picture?uid=" +
device_data.uid + "&size=" + (size||64);
if (device_data.picture) {
url += "&v=" + device_data.picture;
}
return url;
}
};
/**
* Gets called when a device updates it's profile pic, nickname or email.
* @abstract
* @param {number} device_id - The device_id that changed its profile.
*/
AirConsole.prototype.onDeviceProfileChange = function(device_id) {};
/**
* Returns true if a user is logged in.
* @param {number|undefined} device_id - The device_id of the user.
* Default is this device.
* @returns {boolean}
*/
AirConsole.prototype.isUserLoggedIn = function(device_id) {
if (device_id == undefined) {
device_id = this.device_id;
}
var data = this.devices[device_id];
if (data) {
return data.auth;
}
};
/**
* Requests the email address of this device and calls onEmailAddress iff the
* request was granted. For privacy reasons, you need to whitelist your
* game in order to receive the email address of the user. To whitelist your
* game, contact [email protected]. For development purposes, localhost
* is always allowed.
*/
AirConsole.prototype.requestEmailAddress = function() {
this.set_("email", true);
};
/**
* Gets called if the request of requestEmailAddress() was granted.
* For privacy reasons, you need to whitelist your game in order to receive
* the email address of the user. To whitelist your game, contact
* [email protected]. For development purposes, localhost is always
* allowed.
* @abstract
* @param {string|undefined} email_address - The email address of the user if
* it was set.
*/
AirConsole.prototype.onEmailAddress = function(email_address) {};
/**
* Lets the user change his nickname, profile picture and email address.
* If you need a real nickname of the user, use this function.
* onDeviceProfileChange will be called if the user logs in.
*/
AirConsole.prototype.editProfile = function() {
this.set_("login", true);
};
/** ------------------------------------------------------------------------ *
* @chapter ACTIVE PLAYERS *
* @see http://developers.airconsole.com/#!/guides/device_ids_and_states *
* ------------------------------------------------------------------------- */
/**
* Takes all currently connected controllers and assigns them a player number.<br />
* Can only be called by the screen. You don't have to use this helper
* function, but this mechanism is very convenient if you want to know which
* device is the first player, the second player, the third player ...<br />
* The assigned player numbers always start with 0 and are consecutive.
* You can hardcode player numbers, but not device_ids.<br />
* Once the screen has called setActivePlayers you can get the device_id of
* the first player by calling convertPlayerNumberToDeviceId(0), the device_id
* of the second player by calling convertPlayerNumberToDeviceId(1), ...<br />
* You can also convert device_ids to player numbers by calling
* convertDeviceIdToPlayerNumber(device_id). You can get all device_ids that
* are active players by calling getActivePlayerDeviceIds().<br />
* The screen can call this function every time a game round starts.<br />
* When using {@link https://developers.airconsole.com/#!/guides/player_silencing Player Silencing}, the screen needs to call this every time a game round starts or finishes.<br />
* Calling it with max_players of 1 or more signals the start of the game round while calling it with max_players 0 signals the end of the game round.
* @param {number} max_players - The maximum number of controllers that should
* get a player number assigned.
*/
AirConsole.prototype.setActivePlayers = function(max_players) {
if (this.getDeviceId() !== AirConsole.SCREEN) {
throw "Only the AirConsole.SCREEN can set the active players!";
}
this.device_id_to_player_cache = undefined;
var players = this.getControllerDeviceIds();
if (max_players !== undefined) {
players = players.slice(0, Math.min(players.length, max_players));
}
this.devices[AirConsole.SCREEN]["players"] = players;
this.set_("players", players);
if (max_players === 0) {
for (var key in this.silencedUpdatesQueue_) {
if (this.silencedUpdatesQueue_.hasOwnProperty(key)) {
var events = this.silencedUpdatesQueue_[key];
for (var i = 0; i < events.length; i++) {
this.onPostMessage_(events[i]);
}
}
}
this.silencedUpdatesQueue_ = {};
}
};
/**
* Gets called when the screen sets the active players by calling
* setActivePlayers().
* @abstract
* @param {number|undefined} player_number - The player number of this device.
* Can be undefined if this device
* is not part of the active players.
*/
AirConsole.prototype.onActivePlayersChange = function(player_number) {};
/**
* Returns an array of device_ids of the active players previously set by the
* screen by calling setActivePlayers. The first device_id in the array is the
* first player, the second device_id in the array is the second player, ...
* @returns {Array}
*/
AirConsole.prototype.getActivePlayerDeviceIds = function() {
return this.devices[AirConsole.SCREEN]["players"] || [];
};
/**
* Returns the device_id of a player, if the player is part of the active
* players previously set by the screen by calling setActivePlayers. If fewer
* players are in the game than the passed in player_number or the active
* players have not been set by the screen, this function returns undefined.
* @param player_number
* @returns {number|undefined}
*/
AirConsole.prototype.convertPlayerNumberToDeviceId = function(player_number) {
return this.getActivePlayerDeviceIds()[player_number];
};
/**
* Returns the player number for a device_id, if the device_id is part of the
* active players previously set by the screen by calling setActivePlayers.
* Player numbers are zero based and are consecutive. If the device_id is not
* part of the active players, this function returns undefined.
* @param device_id
* @returns {number|undefined}
*/
AirConsole.prototype.convertDeviceIdToPlayerNumber = function(device_id) {
if (!this.devices[AirConsole.SCREEN] ||
!this.devices[AirConsole.SCREEN]["players"]) {
return;
}
if (!this.device_id_to_player_cache) {
this.device_id_to_player_cache = {};
var players = this.devices[AirConsole.SCREEN]["players"];
for (var i = 0; i < players.length; ++i) {
this.device_id_to_player_cache[players[i]] = i;
}
}
return this.device_id_to_player_cache[device_id];
};
/** ------------------------------------------------------------------------ *
* @chapter CONTROLLER INPUTS *
* ------------------------------------------------------------------------- */
/**
* Gets called every X milliseconds with device motion data iff the
* AirConsole was instantiated with the "device_motion" opts set to the
* interval in milliseconds. Only works for controllers.
* Note: Some browsers do not allow games to access accelerometer and gyroscope
* in an iframe (your game). So use this method if you need gyroscope
* or accelerometer data.
* @abstract
* @param {object} data - data.x, data.y, data.z for accelerometer
* data.alpha, data.beta, data.gamma for gyroscope
*/
AirConsole.prototype.onDeviceMotion = function(data) {};
/**
* Vibrates the device for a specific amount of time. Only works for controllers.
* Note: iOS ignores the specified time and vibrates for a pre-set amount of time.
* @param {Number} time - Milliseconds to vibrate the device
*/
AirConsole.prototype.vibrate = function(time) {
this.set_("vibrate", time);
};
/** ------------------------------------------------------------------------ *
* @chapter ADS *
* ------------------------------------------------------------------------- */
/**
* Requests that AirConsole shows a multiscreen advertisment.
* Can only be called by the AirConsole.SCREEN.
* onAdShow is called on all connected devices if an advertisement
* is shown (in this event please mute all sounds).
* onAdComplete is called on all connected devices when the
* advertisement is complete or no advertisement was shown.
*/
AirConsole.prototype.showAd = function() {
if (this.device_id != AirConsole.SCREEN) {
throw "Only the AirConsole.SCREEN can call showAd!";
}
this.set_("ad", true);
};
/**
* Gets called if a fullscreen advertisement is shown on this screen.
* In case this event gets called, please mute all sounds.
* @abstract
*/
AirConsole.prototype.onAdShow = function() {};
/**
* Gets called when an advertisement is finished or no advertisement was shown.
* @abstract
* @param {boolean} ad_was_shown - True iff an ad was shown and onAdShow was
* called.
*/
AirConsole.prototype.onAdComplete = function(ad_was_shown) {};
/** ------------------------------------------------------------------------ *
* @chapter PREMIUM *
* ------------------------------------------------------------------------- */
/**
* Returns true if the device is premium
* @param {number} device_id - The device_id that should be checked.
* Only controllers can be premium.
* Default is this device.
* @return {boolean|undefined} Returns true or false for a valid device_id and
* undefined if the device_id is not valid.
*
*/
AirConsole.prototype.isPremium = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data && device_id != AirConsole.SCREEN) {
return !!device_data.premium;
}
};
/**
* Returns all device ids that are premium.
* @return {Array<number>}
*/
AirConsole.prototype.getPremiumDeviceIds = function() {
var premium = [];
for (var i = 1; i < this.devices.length; ++i) {
if (this.isPremium(i)) {
premium.push(i);
}
}
return premium;
};
/**
* Offers the user to become a premium member.
* Can only be called from controllers.
* If you call getPremium in development mode, the device becomes premium
* immediately.
*/
AirConsole.prototype.getPremium = function() {
this.set_("premium", true);
};
/**
* Gets called when a device becomes premium or when a premium device connects.
* @abstract
* @param {number} device_id - The device id of the premium device.
*/
AirConsole.prototype.onPremium = function(device_id) {};
/** ------------------------------------------------------------------------ *
* @chapter NAVIGATION *
* ------------------------------------------------------------------------- */
/**
* Request that all devices return to the AirConsole store.
*/
AirConsole.prototype.navigateHome = function() {
this.set_("home", true);
};
/**
* Request that all devices load a game by url or game id.
* @param {string} url - The base url of the game to navigate to
* (excluding screen.html or controller.html).
* Instead of a url you may also pass a game id.
* You can also navigate relatively to your current
* game directory: To navigate to a subdirectory,
* pass "./DIRECTORY_NAME". To navigate to a parent
* directory pass "..".
* @param {object} parameters - You can pass parameters to the game that gets
* loaded. Any jsonizable object is fine.
* The parameters will be appended to the url
* using a url hash.
*/
AirConsole.prototype.navigateTo = function(url, parameters) {
if (url.indexOf(".") == 0) {
var current_location = this.getLocationUrl_();
var full_path = current_location.split("#")[0].split("/");
full_path.pop();
var relative = url.split("/");
for (var i = 0; i < relative.length; ++i) {
if (relative[i] == "..") {
full_path.pop();
} else if (relative[i] != "." && relative[i] != "") {
full_path.push(relative[i]);
}
}
url = full_path.join("/") + "/";
}
if (parameters) {
url += "#" + encodeURIComponent(JSON.stringify(parameters));
}
this.set_("home", url);
};
/**
* Get the parameters in the loaded game that were passed to navigateTo.
* @returns {*}
*/
AirConsole.prototype.getNavigateParameters = function() {
if (this.navigate_parameters_cache_) {
return this.navigate_parameters_cache_;
}
if (document.location.hash.length > 1) {
var result = JSON.parse(decodeURIComponent(
document.location.hash.substr(1)));
this.navigate_parameters_cache_ = result;
return result;
}
};
/**
* Opens url in external (default-system) browser. Call this method instead of
* calling window.open. In-App it will open the system's default browser.
* Because of Safari iOS you can only use it with the onclick handler:
* <div onclick="airconsole.openExternalUrl('my-url.com');">Open browser</div>
* OR in JS with assigning element.onclick.
* @param {string} url - The url to open
*/
AirConsole.prototype.openExternalUrl = function(url) {
var data = this.devices[this.device_id];
if (data.client && data.client.pass_external_url === true) {
this.set_("pass_external_url", url);
} else {
window.open(url);
}
};
/** ------------------------------------------------------------------------ *
* @chapter USER INTERFACE *
* ------------------------------------------------------------------------- */
/**
* Sets the device orientation.
* @param {string} orientation - AirConsole.ORIENTATION_PORTRAIT or
* AirConsole.ORIENTATION_LANDSCAPE.
*/
AirConsole.prototype.setOrientation = function(orientation) {
this.set_("orientation", orientation);
};
/** ------------------------------------------------------------------------ *
* @chapter PERSISTENT DATA *
* ------------------------------------------------------------------------- */
/**
* Requests persistent data from the servers.
* @param {Array<String>} uids - The uids for which you would like to request the persistent data.
* For controllers, the default is the uid of this device.
* Screens must provide a valid array of uids.
* @version 1.9.0 - uids is no longer optional for requests from the screen
*/
AirConsole.prototype.requestPersistentData = function (uids) {
if (this.device_id === AirConsole.SCREEN) {
if (!uids) {
throw new Error("A valid array of uids must be provided on the screen");
} else if (uids.length < 1) {
throw new Error("At least one valid uid must be provided on the screen");
}
} else {
uids = uids || [];
uids.push(this.getUID());
}
this.set_("persistentrequest", { uids: uids });
};
/**
* Gets called when persistent data was loaded from requestPersistentData().
* @abstract
* @param {Object} data - An object mapping uids to all key value pairs.
*/
AirConsole.prototype.onPersistentDataLoaded = function(data) {};
/**
* Stores a key-value pair persistently on the AirConsole servers.
* Storage is per game. Total storage can not exceed 1 MB per game and uid.
* Storage is public, not secure and anyone can request and tamper with it.
* Do not store sensitive data.
* @param {String} key - The key of the data entry.
* @param {mixed} value - The value of the data entry.
* @param {String} uid - The uid for which the data should be stored.
* For controllers, the default is the uid of this device.
* Screens must provide a valid uid.
* @version 1.9.0 - uid is no longer optional for requests from the screen
*/
AirConsole.prototype.storePersistentData = function (key, value, uid) {
if (this.device_id === AirConsole.SCREEN) {
if (!uid) {
throw new Error("A valid uid must be provided on the screen");
}
} else {
uid = this.getUID();
}
this.set_("persistentstore", { key: key, value: value, uid: uid });
};
/**
* Gets called when persistent data was stored from storePersistentData().
* @abstract
* @param {String} uid - The uid for which the data was stored.
*/
AirConsole.prototype.onPersistentDataStored = function(uid) {};
/** ------------------------------------------------------------------------ *
* @chapter HIGH SCORES *
* @see http://developers.airconsole.com/#!/guides/highscore *
* ------------------------------------------------------------------------- */
/**
* Stores a high score of the current user on the AirConsole servers.
* High Scores are public, not secure and anyone can request and tamper with
* them. Do not store sensitive data. Only updates the high score if it was a
* higher or same score. Calls onHighScoreStored when the request is done.
* We highly recommend to read the High Score guide (developers.airconsole.com)
* @param {String} level_name - The name of the level the user was playing.
* This should be a human readable string because
* it appears in the high score sharing image.
* You can also just pass an empty string.
* @param {String} level_version - The version of the level the user was
* playing. This is for your internal use.
* @param {number} score - The score the user has achieved
* @param {String|Array<String>|undefined} uid - The UIDs of the users that
* achieved the high score.
* Can be a single uid or an
* array of uids. Default is the
* uid of this device.
* @param {mixed|undefined} data - Custom high score data (e.g. can be used to
* implement Ghost modes or include data to
* verify that it is not a fake high score).
* @param {String|undefined} score_string - A short human readable
* representation of the score.
* (e.g. "4 points in 3s").
* Defaults to "X points" where x is
* the score converted to an integer.
*/
AirConsole.prototype.storeHighScore = function(level_name, level_version,
score, uid, data,
score_string) {
if (isNaN(score) || typeof score != "number") {
throw "Score needs to be a number and not NaN!"
}
if (!uid) {
uid = this.getUID();
}
if (uid.constructor == Array) {
uid = uid.join("|");
}
this.set_("highscore",
{
"uid": uid,
"level_name": level_name,
"level_version": level_version,
"score": score,
"data": data,
"score_string": score_string
});
};
/**
* Gets called when a high score was successfully stored.
* We highly recommend to read the High Score guide (developers.airconsole.com)
* @param {AirConsole~HighScore|null} high_score - The stored high score if
* it is a new best for the
* user or else null.
* Ranks include "world",
* "country", "region", "city"
* if a high score is passed.
*/
AirConsole.prototype.onHighScoreStored = function(high_score) {};
/**
* Requests high score data of players (including global high scores and
* friends). Will call onHighScores when data was received.
* We highly recommend to read the High Score guide (developers.airconsole.com)
* @param {String} level_name - The name of the level
* @param {String} level_version - The version of the level
* @param {Array<String>|undefined} uids - An array of UIDs of the users that
* should be included in the result.
* Default is all connected controllers
* @param {Array<String>|undefined} ranks - An array of high score rank types.
* High score rank types can include
* data from across the world, only a
* specific area or a users friends.
* Valid array entries are "world",
* "country", "region", "city",
* "friends", "partner". <br />
* Default is ["world"].
* @param {number|undefined} total - Amount of high scores to return per rank
* type. Default is 8.
* @param {number|undefined} top - Amount of top high scores to return per rank
* type. top is part of total. Default is 5.
*/
AirConsole.prototype.requestHighScores = function(level_name, level_version, uids, ranks, total, top) {
if (!ranks) {
ranks = ["world"];
}
if (!uids) {
uids = [];
var device_ids = this.getControllerDeviceIds();
for (var i = 0; i < device_ids.length; ++i) {
uids.push(this.getUID(device_ids[i]));
}
}
if (total == undefined) {
total = 8;
}
if (top == undefined) {
top = 5;
}
this.set_("highscores",
{
"level_name": level_name,
"level_version": level_version,
"uids": uids,
"ranks": ranks,
"total": total,
"top": top
});
};
/**
* Gets called when high scores are returned after calling requestHighScores.
* We highly recommend to read the High Score guide (developers.airconsole.com)
* @param {Array<AirConsole~HighScore>} high_scores - The high scores.
*/
AirConsole.prototype.onHighScores = function(high_scores) {};
/**
* DeviceState contains information about a device in this session.
* Use the helper methods getUID, getNickname, getProfilePicture and
* getCustomDeviceState to access this data.
* @typedef {object} AirConsole~DeviceState
* @property {string} uid - The globally unique ID of the user.
* @property {string|undefined} custom - Custom device data that this API can set.