-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnewgroundsio.js
2890 lines (2506 loc) · 113 KB
/
newgroundsio.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
/* Generated Tue, 12 Jul 2016 15:21:59 -0400 */
/**
* @license
* Copyright (c) 2015 Newgrounds Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* start namespaces.js */
if (typeof(Newgrounds) == 'undefined') {
/**
* Newgrounds namespace
* @namespace
*/
Newgrounds = {};
}
/**
* Newgrounds.io namespace
* @memberof Newgrounds
* @type {object}
* @version 1.0
* @namespace Newgrounds.io
*/
Newgrounds.io = {
/**
* @property {string} GATEWAY_URI - The script all commands get posted to
*/
GATEWAY_URI: 'https://newgrounds.io/gateway_v3.php'
};
/**
* Newgrounds.io.events namespace
* @memberof Newgrounds.io
* @type {object}
* @namespace Newgrounds.io.events
*/
Newgrounds.io.events = {};
/**
* Newgrounds.io.call_validators namespace
* @memberof Newgrounds.io
* @type {object}
* @namespace Newgrounds.io.call_validators
*/
Newgrounds.io.call_validators = {};
/**
* Newgrounds.io.model namespace
* @memberof Newgrounds.io
* @type {object}
* @namespace Newgrounds.io.model
*/
Newgrounds.io.model = {
/* Used to enforce strict typing */
checkStrictValue: function(classname, property, value, type, model, array_type, array_model) {
if (type == 'mixed') return true;
if (value === null || typeof(value) == 'undefined') return true;
if (type && value.constructor === type) return true;
if (type == Boolean && value.constructor === Number) return true;
if (model && value.constructor === Newgrounds.io.model[model]) return true;
if (value.constructor === Array && (array_type || array_model)) {
for (var i=0; i<value.length; i++) {
this.checkStrictValue(classname, property, value[i], array_type, array_model, null, null);
}
return true;
}
if (classname) throw new Error("Illegal '"+property+"' value set in model "+classname);
return false;
}
}
/* end namespaces.js */
/* start events.js */
/**
* Contains data output by the Newgrounds.io server for use in event listeners
* @constructor
* @memberof Newgrounds.io.events
* @param {string} type - The name of the event, typically the component name.
* @param {Newgrounds.io.model.call} call - The call object that was posted to the server.
* @param {(object|object[])} data - The results from the server.
* @property {string} type - The name of the event, typically the component name.
* @property {boolean} success - Will be true if the call was successful.
* @property {Newgrounds.io.model.call} call - The call object that was posted to the server.
* @property {(object|object[])} data - The results from the server.
* @property {boolean} preventDefault - If set to true, event will not perform default behaviour (if any).
*/
Newgrounds.io.events.OutputEvent = function(type, call, data) {
this.type = type;
this.call = call;
this.data = data;
this.success = data && typeof(data['success'] != 'undefined') ? (data.success ? true:false) : false;
this.preventDefault = false;
}
Newgrounds.io.events.OutputEvent.prototype.constructor = Newgrounds.io.events.OutputEvent;
/**
* Contains data used when working with sessions
* @constructor
* @memberof Newgrounds.io.events
* @param {string} type - The name of the event, typically a Newgrounds.io.events.SessionEvent constant.
* @property {string} type - The name of the event, typically the component name.
* @property {Newgrounds.io.model.user} user - The user associated with the session (if any).
* @property {string} passport_url - A URL where the user can sign in securely.
*/
Newgrounds.io.events.SessionEvent = function(type) {
this.type = type;
this.user = null;
this.passport_url = null;
}
/**
* @constant
* @type {string}
*/
Newgrounds.io.events.SessionEvent.USER_LOADED = 'user-loaded';
/**
* @constant
* @type {string}
*/
Newgrounds.io.events.SessionEvent.SESSION_EXPIRED = 'session-expired';
/**
* @constant
* @type {string}
*/
Newgrounds.io.events.SessionEvent.REQUEST_LOGIN = 'request-login';
Newgrounds.io.events.SessionEvent.prototype.constructor = Newgrounds.io.events.SessionEvent;
/**
* Class for listening to and dispatching events.
* @constructor
* @memberof Newgrounds.io.events
*/
Newgrounds.io.events.EventDispatcher = function() {};
Newgrounds.io.events.EventDispatcher.prototype = {
_event_listeners: {},
/**
* Adds a listener function to the specified event.
* @instance
* @memberof Newgrounds.io.events.EventDispatcher
* @function addEventListener
* @param {string} type - The event name to listen for.
* @param {function} listener - A function to call when the event is triggered.
*/
addEventListener: function(type, listener) {
if (type.constructor !== String) throw new Error('Event names must be a string format.');
if (listener.constructor !== Function) throw new Error('Event listeners must be functions.');
if (typeof(this._event_listeners[type]) == 'undefined') this._event_listeners[type] = [];
this._event_listeners[type].push(listener);
},
/**
* Removes a listener function from the specified event.
* @instance
* @memberof Newgrounds.io.events.EventDispatcher
* @function removeEventListener
* @param {string} type - The event name you want to remove a listener from.
* @param {function} listener - The listener function you want to remove.
* @return {boolean} Returns true if a matching listener was removed.
*/
removeEventListener: function(type, listener) {
if (typeof(this._event_listeners[type]) == 'undefined') return;
var index=-1;
for(i=0; i<this._event_listeners[type].length; i++) {
if (this._event_listeners[type][i] === listener) {
index = i;
break;
}
}
if (index >= 0) {
this._event_listeners[type].splice(index,1);
return true;
}
return false;
},
/**
* Removes ALL listener functions from the specified event.
* @instance
* @memberof Newgrounds.io.events.EventDispatcher
* @function removeAllEventListeners
* @param {string} type - The event name you want to remove listeners from.
* @return {number} The number of listeners that were removed.
*/
removeAllEventListeners: function(type) {
if (typeof(this._event_listeners[type]) == 'undefined') return 0;
var removed = this._event_listeners[type].length;
this._event_listeners[type] = [];
return removed;
},
/**
* Dispatches an event to any listener functions.
* @instance
* @memberof Newgrounds.io.events.EventDispatcher
* @function dispatchEvent
* @param event - The event to dispatch.
* @return {boolean}
*/
dispatchEvent: function(event) {
var valid = false;
var listener;
for(var e in Newgrounds.io.events) {
if(event.constructor === Newgrounds.io.events[e]) {
valid = true;
break;
}
}
if (!valid) throw new Error('Unsupported event object');
if (typeof(this._event_listeners[event.type]) == 'undefined') return false;
for(var i=0; i<this._event_listeners[event.type].length; i++) {
listener = this._event_listeners[event.type][i];
if (listener(event) === false || event.preventDefault) return true;
}
return true;
}
};
Newgrounds.io.events.EventDispatcher.prototype.constructor = Newgrounds.io.events.EventDispatcher;
/* end events.js */
/* start core.js */
/**
* Handles making calls and processing results to the Newgrounds.io server
* @constructor
* @memberof Newgrounds.io
* @property {boolean} debug - Set to true to operate in debug mode
* @property {string} app_id - Your unique app ID (found in the 'API Tools' section of your Newgrounds.com project).
* @property {Newgrounds.io.model.user} user - A user associated with an active session id. Use getSessionLoader to load.
* @property {string} session_id - A user session id (acquire with App.startSession call).
* @param {string} [app_id] - Your unique app ID (found in the 'API Tools' section of your Newgrounds.com project).
* @param {string} [aes_key] - Your AES-128 encryption key (in Base64 format).
*/
Newgrounds.io.core = function(app_id, aes_key) {
var _app_id;
var _session_id;
var _user;
var _debug;
var ngio = this;
var _aes_key;
var _urlhelper = new Newgrounds.io.urlHelper();
if (_urlhelper.getRequestQueryParam("ngio_session_id")) {
_session_id = _urlhelper.getRequestQueryParam("ngio_session_id");
}
Object.defineProperty(this, 'app_id', {
get: function() {
return _app_id;
}
});
Object.defineProperty(this, 'user', {
get: function() {
return this.getCurrentUser();
}
});
Object.defineProperty(this, 'session_id', {
set: function(id) {
if (id && typeof(id) != 'string') throw new Error("'session_id' must be a string value.");
_session_id = id ? id : null;
},
get: function() {
return _session_id ? _session_id : null;
}
});
Object.defineProperty(this, 'debug', {
set: function(debug) {
_debug = debug ? true:false;
},
get: function() {
return _debug;
}
});
if (!app_id) throw new Error("Missing required 'app_id' in Newgrounds.io.core constructor");
if (typeof(app_id) != 'string') throw new Error("'app_id' must be a string value in Newgrounds.io.core constructor");
_app_id = app_id;
if (aes_key) _aes_key = CryptoJS.enc.Base64.parse(aes_key);
else console.warn("You did not set an encryption key. Some calls may not work without this.");
var _session_storage_key = "Newgrounds-io-app_session-"+(_app_id.split(":").join("-"));
function checkLocalStorage() {
if (typeof(localStorage) != 'undefined' && localStorage && localStorage.getItem.constructor == Function) return true;
console.warn('localStorage unavailable. Are you running from a web server?');
return false;
}
function getStoredSession() {
if (!checkLocalStorage()) return null;
var id = localStorage.getItem(_session_storage_key);
return id ? id : null;
}
function setStoredSession(id) {
if (!checkLocalStorage()) return null;
localStorage.setItem(_session_storage_key, id);
}
function clearStoredSession() {
if (!checkLocalStorage()) return null;
localStorage.removeItem(_session_storage_key);
}
if (!_session_id && getStoredSession()) _session_id = getStoredSession();
this.addEventListener('App.endSession', function(e) {
ngio.session_id = null;
clearStoredSession();
});
this.addEventListener('App.startSession', function(e) {
if (e.success) ngio.session_id = e.data.session.id;
});
this.addEventListener('App.checkSession', function(e) {
if (e.success) {
if (e.data.session.expired) {
clearStoredSession();
this.session_id = null;
} else if (e.data.session.remember) {
setStoredSession(e.data.session.id);
}
} else {
this.session_id = null;
clearStoredSession();
}
});
this._encryptCall = function(call_model) {
if (!call_model || !call_model.constructor == Newgrounds.io.model.call_model) throw new Error("Attempted to encrypt a non 'call' object");
var iv = CryptoJS.lib.WordArray.random(16);
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(call_model.toObject()), _aes_key, { iv: iv });
var output = CryptoJS.enc.Base64.stringify(iv.concat(encrypted.ciphertext));
call_model.secure = output;
call_model.parameters = null;
return call_model;
};
}
Newgrounds.io.core.prototype = {
_session_loader: null,
_call_queue: [],
_event_listeners: {},
/**
* Adds a listener function to the specified event.
* @instance
* @memberof Newgrounds.io.core
* @function addEventListener
* @param {string} type - The event to listen for. Typically a component name like 'Gateway.getVersion'.
* @param {function} listener - A function to call when the event is triggered.
*/
addEventListener: Newgrounds.io.events.EventDispatcher.prototype.addEventListener,
/**
* Removes a listener function from the specified event.
* @instance
* @memberof Newgrounds.io.core
* @function removeEventListener
* @param {string} type - The event you want to remove a listener from. Typically a component name like 'Gateway.getVersion'.
* @param {function} listener - The listener function you want to remove.
* @return {boolean} Returns true if a matching listener was removed.
*/
removeEventListener: Newgrounds.io.events.EventDispatcher.prototype.removeEventListener,
/**
* Removes ALL listener functions from the specified event.
* @instance
* @memberof Newgrounds.io.core
* @function removeAllEventListeners
* @param {string} type - The event you want to remove listeners from.
* @return {number} The number of listeners that were removed.
*/
removeAllEventListeners: Newgrounds.io.events.EventDispatcher.prototype.removeAllEventListeners,
/**
* Dispatches an event to any listener functions.
* @instance
* @memberof Newgrounds.io.core
* @function dispatchEvent
* @param {Newgrounds.io.events.OutputEvent} event - The event to dispatch.
* @return {boolean}
*/
dispatchEvent: Newgrounds.io.events.EventDispatcher.prototype.dispatchEvent,
/**
* Gets an initialized Newgrounds.io.SessionLoader instance.
* @instance
* @memberof Newgrounds.io.core
* @function getSessionLoader
* @return {Newgrounds.io.SessionLoader}
*/
getSessionLoader: function() {
if (this._session_loader == null) this._session_loader = new Newgrounds.io.SessionLoader(this);
return this._session_loader;
},
/**
* Gets the current active session, if any.
* @instance
* @memberof Newgrounds.io.core
* @function getSession
* @return {Newgrounds.io.model.session}
*/
getSession: function() {
return this.getSessionLoader().session;
},
/**
* Gets the current logged in user, if available.
* @instance
* @memberof Newgrounds.io.core
* @function getCurrentUser
* @return {Newgrounds.io.model.user}
*/
getCurrentUser: function() {
var sl = this.getSessionLoader();
if (sl.session) return sl.session.user;
return null;
},
/**
* Gets the last login error (if any).
* @instance
* @memberof Newgrounds.io.core
* @function getLoginError
* @return {Newgrounds.io.model.error}
*/
getLoginError: function() {
return this.getSessionLoader().last_error;
},
/**
* Gets an active session. If one does not already exist, one will be created.
* @instance
* @memberof Newgrounds.io.core
* @function getValidSession
* @param {Newgrounds.io.SessionLoader~onStatusUpdate} [callback] - An optional callback function.
* @param {object} [context] - The context under which to call the callback. Optional.
*/
getValidSession: function(callback, context) {
this.getSessionLoader().getValidSession(callback, context);
},
/**
* Loads Newgrounds Passport and waits for the user to log in, or cancel their login.
* @instance
* @memberof Newgrounds.io.core
* @function requestLogin
* @param {function} [on_logged_in] - A function that will execute when the user is logged in
* @param {function} [on_login_failed] - A function that will execute if the login fails
* @param {function} [on_login_cancelled] - A function that will execute if the user cancels the login.
* @param {object} [context] - The context under which the callbacks will be called. Optional.
*/
requestLogin: function(on_logged_in, on_login_failed, on_login_cancelled, context) {
if (!on_logged_in || on_logged_in.constructor !== Function) throw ("Missing required callback for 'on_logged_in'.");
if (!on_login_failed || on_login_failed.constructor !== Function) throw ("Missing required callback for 'on_login_failed'.");
var io = this;
var loader = this.getSessionLoader();
var login_interval;
function end_request() {
if (login_interval) clearInterval(login_interval);
io.removeEventListener("cancelLoginRequest", cancel_request);
loader.closePassport();
}
function cancel_request() {
on_login_cancelled && on_login_cancelled.constructor === Function ? on_login_cancelled.call(context) : on_login_failed.call(context);
end_request();
}
io.addEventListener("cancelLoginRequest", cancel_request);
if (io.getCurrentUser()) {
on_logged_in.call(context);
} else {
loader.loadPassport();
login_interval = setInterval(function(){
loader.checkSession(function(session) {
if (!session || session.expired) {
if (loader.last_error.code == 111) {
cancel_request();
} else {
end_request();
on_login_failed.call(context);
}
} else if (session.user) {
end_request();
on_logged_in.call(context);
}
});
}, 3000);
}
},
/**
* Cancels any pending login request created via requestLogin()
* @instance
* @memberof Newgrounds.io.core
* @function cancelLoginRequest
*/
cancelLoginRequest: function() {
event = new Newgrounds.io.events.OutputEvent("cancelLoginRequest",null,null);
this.dispatchEvent(event);
},
/**
* Ends any active user session and logs the user out of Newgrounds Passport.
* @instance
* @memberof Newgrounds.io.core
* @function logOut
* @param {Newgrounds.io.SessionLoader~onStatusUpdate} [callback] - An optional callback function.
* @param {object} [context] - The context under which to call the callback. Optional.
*/
logOut: function(callback, context) {
this.getSessionLoader().endSession(callback, context);
},
/**
* Adds a component call to the queue. Will be executed later with executeCall.
* @instance
* @memberof Newgrounds.io.core
* @function queueComponent
* @param {string} component - The component to call, ie 'Gateway.ping'
* @param {(object|object[])} [parameters] - Parameters being passed to the component. You may also pass multiple parameters objects in an array to execute the component multiple times.
* @param {Newgrounds.io.core~onCallResult} [callback] - A function that will execute when this call has executed.
* @param {object} [context] - The context under which the callback will be executed. Optional.
*/
queueComponent: function(component, parameters, callback, context) {
if (parameters && parameters.constructor === Function && !callback) {
callback = parameters;
parameters = null;
}
var call_model = new Newgrounds.io.model.call(this);
call_model.component = component;
if (typeof(parameters) != 'undefined') call_model.parameters = parameters;
this._validateCall(call_model);
this._call_queue.push([call_model,callback,context]);
},
/**
* Executes any queued calls and resets the queue.
* @instance
* @memberof Newgrounds.io.core
* @function executeQueue
*/
executeQueue: function() {
var calls = [];
var callbacks = [];
var contexts = [];
for(var i=0; i<this._call_queue.length; i++) {
calls.push(this._call_queue[i][0]);
callbacks.push(this._call_queue[i][1]);
contexts.push(this._call_queue[i][2]);
}
this._doCall(calls, callbacks, contexts);
this._call_queue = [];
},
/**
* Executes a call to a single component.
* @instance
* @memberof Newgrounds.io.core
* @function callComponent
* @param {string} component - The component to call, ie 'Gateway.ping'
* @param {(object|object[])} [parameters] - Parameters being passed to the component. You may also pass multiple parameters objects in an array to execute the component multiple times.
* @param {Newgrounds.io.core~onCallResult} [callback] - A function that will execute when this call has executed.
* @param {object} [context] - The context under which the callback will be executed. Optional.
*/
callComponent: function(component, parameters, callback, context) {
if (parameters.constructor === Function && !callback) {
callback = parameters;
parameters = null;
}
var call_model = new Newgrounds.io.model.call(this);
call_model.component = component;
if (typeof(parameters) != 'undefined') call_model.parameters = parameters;
this._validateCall(call_model);
this._doCall(call_model, callback, context);
},
_doCallback: function(call_model, callback, o_return, context) {
var i, x_return, x_callback, x_call, x_context;
// generic catch-all error
var o_error = {success:false,error:{code:0,message:"Unexpected Server Response"}};
if (typeof(o_return) == 'undefined') o_return = null;
// if we sent an array of calls, we'll need to check for an array of callbacks
if (call_model.constructor === Array && callback && callback.constructor === Array) {
for(i=0; i<call_model.length; i++) {
x_return = (!o_return || typeof(o_return[i]) == 'undefined') ? o_error : o_return[i];
x_callback = typeof(callback[i]) == 'undefined' ? null:callback[i];
this._doCallback(call_model[i], x_callback, x_return, context[i]);
}
return;
}
if (o_return && typeof(o_return['data']) != 'undefined') {
var data;
if (o_return.data.constructor === Array) {
data = [];
for(i=0; i<o_return.data.length; i++) {
data.push(this._formatResults(o_return.component, o_return.data[i]))
}
} else {
data = this._formatResults(o_return.component, o_return.data);
}
o_return.data = data;
}
var o_data;
if (o_return) {
if (typeof(o_return['data']) != 'undefined') {
o_data = o_return.data;
} else {
console.warn("Received empty data from '"+call_model.component+"'.");
o_data = null;
}
} else {
o_data = o_error;
}
var event;
if (o_data.constructor === Array) {
for(i=0; i<o_data.length; i++) {
event = new Newgrounds.io.events.OutputEvent(call_model.component, call_model[i], o_data[i]);
this.dispatchEvent(event);
}
} else {
event = new Newgrounds.io.events.OutputEvent(call_model.component, call_model, o_data);
this.dispatchEvent(event);
}
// if we get here we found an actual callback function
if (callback && callback.constructor === Function) {
callback.call(context, o_data);
}
},
_formatResults: function(component, result_object) {
var model, i, j, models, model_name, validator = null;
if (typeof(result_object.success) != 'undefined' && result_object.success) {
validator = Newgrounds.io.call_validators.getValidator(component);
}
if (!validator) return result_object;
var formats = validator.returns;
for(i in formats) {
if (typeof(result_object[i]) == 'undefined' && result_object.success !== false) {
console.warn("Newgrounds.io server failed to return expected '"+i+"' in '"+component+"' data.");
continue;
}
if (typeof(formats[i]['array']) != 'undefined') {
if (typeof(formats[i]['array']['object']) != 'undefined') {
model_name = formats[i]['array']['object'];
} else {
model_name = formats[i]['array'];
}
if (typeof(Newgrounds.io.model[model_name]) == 'undefined') {
console.warn("Received unsupported model '"+model_name+"' from '"+component+"'.");
continue;
}
if (result_object[i].constructor !== Array) {
console.warn("Expected array<"+model_name+"> value for '"+i+"' in '"+component+"' data, got "+typeof(result_object[i]));
continue;
}
models = [];
for(j=0; j<result_object[i].length; j++) {
model = new Newgrounds.io.model[model_name](this);
model.fromObject(result_object[i][j]);
models.push(model);
}
result_object[i] = models;
} else if (typeof(formats[i]['object']) != 'undefined' && result_object[i]) {
model_name = formats[i]['object'];
if (typeof(Newgrounds.io.model[model_name]) == 'undefined') {
console.warn("Received unsupported model '"+model_name+"' from '"+component+"'.");
continue;
}
model = new Newgrounds.io.model[model_name](this);
model.fromObject(result_object[i]);
result_object[i] = model;
}
}
return result_object;
},
_doCall: function(call_model, callback, context) {
if (!this.app_id) throw new Error('Attempted to call Newgrounds.io server without setting an app_id in Newgrounds.io.core instance.');
var call_object;
var is_redirect = false;
var io=this;
function checkRedirect(model) {
var validator = Newgrounds.io.call_validators.getValidator(model.component);
if (validator.hasOwnProperty('redirect') && validator.redirect) {
var parameters = model.parameters;
if (!parameters || !parameters.hasOwnProperty('redirect') || parameters.redirect) {
return true;
}
}
return false;
}
if (call_model.constructor === Array) {
call_object = [];
for(i=0; i<call_model.length; i++) {
if (checkRedirect(call_model[i])) {
throw new Error("Loader components can not be called in an array without a redirect=false parameter.");
}
call_object.push(call_model[i].toObject());
}
} else {
call_object = call_model.toObject();
is_redirect = checkRedirect(call_model);
}
var input = {
app_id:this.app_id,
session_id:this.session_id,
call: call_object
};
if (this.debug) input.debug = 1;
if (is_redirect) {
var result = {
success: true,
app_id: this.app_id,
result: {
component: call_model.component,
data: { success: true }
}
};
var _form = document.createElement("form");
_form.action = Newgrounds.io.GATEWAY_URI;
_form.target = "_blank";
_form.method = "POST";
var _form_input = document.createElement("input");
_form_input.type="hidden";
_form_input.name="input";
_form.appendChild(_form_input);
document.body.appendChild(_form);
_form_input.value = JSON.stringify(input);
_form.submit();
document.body.removeChild(_form);
} else {
var xhr = new XMLHttpRequest();
var output;
var error = null
var ngio = this;
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
var o_return;
try { o_return = (JSON.parse(xhr.responseText)).result; } catch(e) {}
ngio._doCallback(call_model, callback, o_return, context);
}
};
var formData = new FormData();
// jhax is a hack to get around JS frameworks that add a toJSON method to Array (wich breaks the native implementation).
var jhax = typeof(Array.prototype.toJSON) != 'undefined' ? Array.prototype.toJSON : null;
if (jhax) delete Array.prototype.toJSON;
formData.append('input', JSON.stringify(input));
if (jhax) Array.prototype.toJSON = jhax;
xhr.open('POST', Newgrounds.io.GATEWAY_URI, true);
xhr.send(formData);
}
},
_doValidateCall: function(component,parameters) {
var i, c, param, rules;
var validator = Newgrounds.io.call_validators.getValidator(component);
if (!validator) throw new Error("'"+component+"' is not a valid server component.");
if (validator.require_session && !this.session_id) throw new Error("'"+component+"' requires a session id");
if (validator.import && validator.import.length > 0) {
for(i=0; i<validator.import.length; i++) {
c = validator.import[i].split(".");
this._doValidateCall(c[0],c[1],parameters);
}
}
var param_value;
for(param in validator.params) {
rules = validator.params[param];
param_value = parameters && typeof(parameters[param]) != 'undefined' ? parameters[param] : null;
if (!param_value && rules.extract_from && rules.extract_from.alias) param_value = parameters[rules.extract_from.alias];
if (param_value === null) {
if (rules.required) throw new Error("Missing required parameter for '"+component+"': "+param);
continue;
}
if (rules.extract_from && param_value.constructor === Newgrounds.io.model[rules.extract_from.object]) {
param_value = param_value[rules.extract_from.property];
}
if (!Newgrounds.io.model.checkStrictValue(null, param, param_value, rules.type, null, null, null)) throw new Error("Illegal value for '"+param+"' parameter of '"+component+"': "+param_value);
}
},
_validateCall: function(call_model) {
var i;
if (call_model.constructor === Array) {
var c = [];
for(i=0; i<call_model.length; i++) {
c.push(this._validateCall(call_model[i]));
}
return c;
} else if (call_model.constructor !== Newgrounds.io.model.call) {
throw new Error("Unexpected 'call_model' value. Expected Newgrounds.io.model.call instance.");
}
var component = call_model.component;
var parameters = call_model.parameters;
var echo = call_model.echo;
if (parameters && parameters.constructor === Array) {
for(i=0; i<parameters.length; i++) {
this._doValidateCall(component, parameters[i]);
}
} else {
this._doValidateCall(component, parameters);
}
var call_object = {component: call_model.component};
var validator = Newgrounds.io.call_validators.getValidator(call_model.component);
if (typeof(parameters) != 'undefined') {
if (validator.secure) {
var secure = this._encryptCall(call_model);
call_object.secure = secure.secure;
} else {
call_object.parameters = parameters;
}
}
if (typeof(echo) != 'undefined') call_object.echo = echo;
return call_object;
}
}
Newgrounds.io.core.prototype.constructor = Newgrounds.io.core;
Newgrounds.io.core.instance_id = 0;
Newgrounds.io.core.getNextInstanceID = function() {
Newgrounds.io.core.instance_id++;
return Newgrounds.io.core.instance_id;
};
/**
* Callback used by Newgrounds.io.core.callComponent and Newgrounds.io.core.queueComponent
* @callback Newgrounds.io.core~onCallResult
* @param {object} data - The results of the call.
*/
/**
* Used to get query string parameters from any url hosting this script (specifically to look for a session id on newgrounds hosted games)
**/
Newgrounds.io.urlHelper = function() {
var uri = window.location.href;
var requestParams = {};
var query = uri.split("?").pop();
if (query) {
var pairs = query.split("&");
var key_value;
for(var i=0; i<pairs.length; i++) {
key_value = pairs[i].split("=");
requestParams[key_value[0]] = key_value[1];
}
}
/**
* Gets the value (if any) of a query string parameter in the current url.
* @instance
* @memberof Newgrounds.io.urlHelper
* @function getRequestQueryParam
* @param {string} param_name - The name of the query parameter you want to look up
* @param [default_value] - A value to return if there is no matching query parameter.
*/
this.getRequestQueryParam = function(param_name, default_value) {
if (typeof(default_value) == 'undefined') default_value = null;
return typeof(requestParams[param_name]) == 'undefined' ? default_value : requestParams[param_name];
};
}
/* end core.js *//**
* Contains all the information needed to execute an API component.
* @name Newgrounds.io.model.call
* @constructor
* @memberof Newgrounds.io.model
* @property {string} component - The name of the component you want to call, ie 'App.connect'.
* @property {object} echo - An optional value that will be returned, verbatim, in the #result object.
* @property {(object|object[])} parameters - An object of parameters you want to pass to the component.
* @property {string} secure - A an encrypted #call object or array of #call objects.
* @param {Newgrounds.io.core} [ngio] - A Newgrounds.io.core instance associated with the model object.
* @param {object} [from_object] - A literal object used to populate this model's properties.
*/
Newgrounds.io.model.call = function(ngio, from_object) {
/* private vars */
var _component, _echo, _parameters, _secure;
this.__property_names = ["component","echo","parameters","secure"];
this.__classname = "Newgrounds.io.model.call";
this.__ngio = ngio;
var _component;
Object.defineProperty(this, 'component', {
get: function() { return typeof(_component) == 'undefined' ? null : _component; },
set: function(__vv__) {
Newgrounds.io.model.checkStrictValue(this.__classname, 'component', __vv__, String, null, null, null);
_component = __vv__;
}
});