forked from mozilla-b2g/gaia
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DoATAPI.js
1191 lines (982 loc) · 32.3 KB
/
DoATAPI.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
'use strict';
Evme.DoATAPI = new function Evme_DoATAPI() {
var NAME = 'DoATAPI', self = this,
requestRetry = null,
cached = [],
apiKey = '',
deviceId = '',
// number of retries before returning error
NUMBER_OF_RETRIES = 3,
// timeout before retrying a failed request
RETRY_TIMEOUT = {'from': 1000, 'to': 3000},
// timeout before declaring a request as failed
// (if server isn't responding)
MAX_REQUEST_TIME = 20000,
// maximum number of calls to save in the user's cache
MAX_ITEMS_IN_CACHE = 20,
MAX_QUERY_LENGTH = {
'App': 300,
'Search': 128,
'Location': 64
},
CACHE_EXPIRATION_IN_MINUTES = 24 * 60,
STORAGE_KEY_CREDS = 'credentials',
authCookieName = '',
userLat,
userLon,
appVersion,
manualCredentials = null,
manualCampaignStats = null,
requestingSession = false,
permanentStats = null,
requestsQueue = {},
requestsToPerformOnOnline = {},
sessionInitRequest = null,
// here we will save the actual params to pass
savedParamsToPass = {},
// which param to pass from normal requests to stats and logs
PARAM_TO_PASS_BETWEEN_REQUESTS = 'requestId',
PARAM_TO_PASS_BETWEEN_REQUESTS_NAME = 'originatingRequestId',
// client info- saved in cookie and sent to API
clientInfo = {
'lc': navigator.language,
'tz': (new Date().getTimezoneOffset() / -60).toString(),
'kb': ''
},
requestsToCache = {
'Search.apps': true,
'Search.bgimage': true,
'Shortcuts.get': 2 * 24 * 60,
'Shortcuts.suggestions': 2 * 24 * 60
},
requestsThatDontNeedConnection = {
'Search.suggestions': true,
'App.icons': true
},
paramsToCleanFromCacheKey =
['cachedIcons', 'idx', 'feature', 'sid', 'credentials'],
doesntNeedSession = {
'Session.init': true
},
// parameters for getting native app suggestions
paramsForNativeSuggestions = {
'nativeSuggestions': true,
'nativeIconFormat': 64, // same as GridManager.PREFERRED_ICON_SIZE
'nativeIconAsUrl': true,
'_opt': 'app.type'
},
/*
* config of params to pass from requests to reports
* "Search.apps": ["appClick", "returnFromApp"]
*/
paramsToPassBetweenRequests = {
'Search.apps': ['appClick', 'loadMore', 'addToHomeScreen']
};
this.ERROR_CODES = {
'SUCCESS': 1,
'AUTH': -9,
'INVALID_PARAMS': -14,
'TIMEOUT': -19
};
this.init = function init(options) {
apiKey = options.apiKey;
appVersion = options.appVersion || '';
authCookieName = options.authCookieName;
manualCampaignStats = options.manualCampaignStats;
deviceId = options.deviceId;
Evme.Storage.get(STORAGE_KEY_CREDS, function storageGot(value) {
manualCredentials = value;
});
permanentStats = {
screenHeight: window.screen.height,
screenWidth: window.screen.width
};
var mozSettings = navigator.mozSettings;
if (mozSettings) {
// make sure our client info cookie is always
// updated according to phone settings
mozSettings.addObserver('language.current', function onLanguageChange(e) {
self.setClientInfoLocale(e.settingValue);
});
mozSettings.addObserver('time.timezone', function onTimeZoneChange(e) {
self.setClientInfoTimeZone();
});
mozSettings.addObserver('keyboard.current',
function onKeyboardLayoutChange(e) {
self.setKeyboardLanguage(e.settingValue);
});
// get device info
var req = mozSettings.createLock().get('*');
req.onsuccess = function onsuccess() {
var res = req.result;
permanentStats.osVersion = res['deviceinfo.os'] || '';
permanentStats.deviceType = res['deviceinfo.product_model'] || '';
};
}
var Conn = Evme.Utils.Connection;
Conn.addEventListener(Conn.events.MOBILE_CONNECTION_CHANGE,
function onConnChange(data) {
permanentStats.carrierName = data && data.operator || '';
});
self.Session.init(options.callback);
};
this.search = function search(options, callback, noSession) {
!options && (options = {});
var params = {
'query': options.query,
'experienceId': options.experienceId || '',
'typeHint': options.typeHint || '',
'feature': options.feature || '',
'cachedIcons': options.cachedIcons || '',
'exact': !!options.exact,
'spellcheck': !!options.spellcheck,
'suggest': !!options.suggest,
'first': options.first || 0,
'limit': options.limit || 16,
'idx': options.index || '',
'iconFormat': options.iconFormat || 10,
'prevQuery': (options.first === 0) ? options.prevQuery || '' : '',
'_opt': 'app.type'
};
if (params.first) {
Evme.EventHandler.trigger(NAME, 'loadmore', params);
}
if (params.exact) {
for (var key in paramsForNativeSuggestions) {
if (params[key] === undefined) {
params[key] = paramsForNativeSuggestions[key];
}
}
}
return request({
'methodNamespace': 'Search',
'methodName': 'apps',
'params': params,
'callback': callback,
'noSession': noSession
}, options._NOCACHE || false);
};
// icons in cache, to be reported to server
this.CachedIcons = new function CachedIcons() {
var self = this,
newIcons = [];
this.add = function add(icon) {
newIcons.push(icon);
};
this.clear = function clear() {
newIcons = [];
};
this.yank = function yank() {
var result = Evme.Utils.convertIconsToAPIFormat(newIcons);
self.clear();
return result;
};
};
this.suggestions = function suggestions(options, callback) {
!options && (options = {});
var params = {
'query': options.query
};
return request({
'methodNamespace': 'Search',
'methodName': 'suggestions',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
this.icons = function icons(options, callback) {
!options && (options = {});
var params = {
'ids': options.ids,
'iconFormat': options.iconFormat
};
return request({
'methodNamespace': 'App',
'methodName': 'icons',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
this.bgimage = function bgimage(options, callback) {
!options && (options = {});
var params = {
'_checksum': options._checksum || '',
'query': options.query,
'experienceId': options.experienceId || '',
'typeHint': options.typeHint || '',
'feature': options.feature || '',
'exact': !!options.exact,
'width': Math.round(options.width || 320),
'height': Math.round(options.height || 460),
'idx': options.index || '',
'prevQuery': options.prevQuery || ''
};
return request({
'methodNamespace': 'Search',
'methodName': 'bgimage',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
this.getDisambiguations = function getDisambiguations(options, callback) {
!options && (options = {});
var params = {
'query': options.query
};
return request({
'methodNamespace': 'Search',
'methodName': 'disambiguate',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
this.Shortcuts = new function Shortcuts() {
this.get = function get(options, callback) {
!options && (options = {});
var params = {
'queries': options.queries || []
};
return request({
'methodNamespace': 'Shortcuts',
'methodName': 'get',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
this.suggest = function suggest(options, callback) {
!options && (options = {});
var params = {
'existing': JSON.stringify(options.existing || [])
};
return request({
'methodNamespace': 'Shortcuts',
'methodName': 'suggestions',
'params': params,
'callback': callback
});
};
};
this.Logger = new function Logger() {
var self = this,
methodArr = ['error', 'warn', 'info'];
methodArr.forEach(function oggerMethodIteration(method) {
self[method] = function report(options, callback) {
options = addGlobals(options);
options = addSavedParams(options);
return request({
'methodNamespace': 'Logger',
'methodName': method,
'params': options,
'callback': callback
});
};
});
};
this.report = function report(options, callback) {
options = addGlobals(options);
options = addSavedParams(options);
return request({
'methodNamespace': 'Stats',
'methodName': 'report',
'params': options,
'callback': callback
}, options._NOCACHE || false);
};
this.appNativeInfo = function appNativeInfo(options, callback) {
// string together ids like so:
// apiurl/?guids=["guid1","guid2","guid3", ...]
var guids = options.guids || [];
for (var i = 0; i < guids.length; i++) {
if (!guids[i]) {
guids.splice(i, 1);
i--;
}
}
var params = {
'guids': JSON.stringify(guids)
};
return request({
'methodNamespace': 'App',
'methodName': 'nativeInfo',
'params': params,
'callback': callback
}, options._NOCACHE || false);
};
function addGlobals(options) {
var globals = options['globals'] || {};
globals.deviceId = deviceId;
try {
options['globals'] = JSON.stringify(globals);
} catch (ex) {
delete options['globals'];
}
return options;
}
// add the saved params from earlier responses to the event's data
function addSavedParams(options) {
var events = options.data;
if (events) {
try {
events = JSON.parse(events);
} catch (ex) {
events = null;
}
if (events && typeof events === 'object') {
for (var i = 0, e; e = events[i++];) {
var savedValue = savedParamsToPass[e.userEvent];
if (savedValue) {
e[PARAM_TO_PASS_BETWEEN_REQUESTS_NAME] = savedValue;
}
}
options.data = JSON.stringify(events);
}
}
return options;
}
// takes a method's response, and saves data
// according to paramsToPassBetweenRequests
function saveParamFromRequest(method, response) {
var events = paramsToPassBetweenRequests[method],
paramValue = response && response[PARAM_TO_PASS_BETWEEN_REQUESTS];
if (!paramValue || !events) {
return;
}
// this will create a map of userEvents => requestId
// to be added to the actual event request later
for (var i = 0, ev; ev = events[i++];) {
savedParamsToPass[ev] = paramValue;
}
}
this.setLocation = function setLocation(lat, lon) {
userLat = lat;
userLon = lon;
Evme.EventHandler.trigger(NAME, 'setLocation', {
'lat': lat,
'lon': lon
});
};
this.hasLocation = function hasLocation() {
return (userLat && userLon);
};
this.request =
function publicRequest(methodNamespace, methodName, params, callback) {
return request({
'methodNamespace': methodNamespace,
'methodName': methodName,
'params': params,
'callback': callback
}, params._NOCACHE);
};
this.initSession = function initSession(options, callback) {
!options && (options = {});
if (!options.cachedIcons) {
var icons = Evme.IconManager.getKeys();
if (icons) {
icons = Evme.Utils.convertIconsToAPIFormat(icons);
options.cachedIcons = icons;
}
}
var params = {
'id': (self.Session.get() || {}).id,
'deviceId': deviceId,
'cachedIcons': options.cachedIcons,
'stats': {
'userAgent': navigator.userAgent,
'referrer': document.referrer,
'connectionType': Evme.Utils.connection().type || '',
'locale': navigator.language || '',
'GMT': (new Date().getTimezoneOffset() / -60).toString(),
'sessionInitCause': options.cause,
'sessionInitSrc': options.source,
'cookiesEnabled': Evme.Utils.bCookiesEnabled() || false,
'localStorageEnabled': Evme.Utils.bLocalStorageEnabled()
}
};
if (requestingSession) {
return;
}
requestingSession = true;
return request({
'methodNamespace': 'Session',
'methodName': 'init',
'params': params,
'callback': function onSessionInitSuccess(data, url) {
requestingSession = false;
if (data && data.response) {
self.Session.update(data.response.ttl);
// in case the API says it wrote a cookie,
// but it doesn't match the user's
if (data.response.credentials &&
data.response.credentials != self.Session.creds()) {
// send the creds with each request
manualCredentials = data.response.credentials;
// save them in local storage
Evme.Storage.set(STORAGE_KEY_CREDS, manualCredentials);
}
Evme.EventHandler.trigger('DoATAPI', 'sessionInit');
}
callback && callback(data, url);
}
});
};
function reInitSession(initCause) {
if (sessionInitRequest) {
return;
}
sessionInitRequest = self.initSession({
'cause': initCause,
'source': 'DoATAPI.reInitSession'
}, function onInitSession() {
for (var key in requestsQueue) {
request(requestsQueue[key], false, true);
}
requestsQueue = {};
sessionInitRequest = null;
});
}
// the "requestsQueue" will empty after the session has been init'ed
// the "key" prevents from adding multiple requests of the same "type"
// so if someone open 2 folders, only the latest request will go out
function addRequestToSessionQueue(requestOptions) {
var key = requestOptions.methodNamespace + '.' + requestOptions.methodName;
requestsQueue[key] = requestOptions;
}
this.getSessionId = function getSessionId() {
return self.Session.get().id;
};
this.Session = new function Session() {
var self = this,
_key = 'session', _session = null,
DEFAULT_TTL = -1;
this.INIT_CAUSE = {
'EXPIRED': 'session expired',
'NO_CREDS': 'missing credentails',
'ABSENT': 'session absent',
'NOT_IN_CACHE': 'new session',
'AUTH_ERROR': 'API authentication error',
'CACHE_ERROR': 'cache error'
};
this.init = function init(callback) {
Evme.Storage.get(_key, function storageGot(sessionFromCache) {
var createCause;
try {
if (sessionFromCache) {
if (!self.expired(sessionFromCache)) {
_session = sessionFromCache;
} else {
createCause = self.INIT_CAUSE.EXPIRED;
}
} else {
createCause = self.INIT_CAUSE.NOT_IN_CACHE;
}
if (!_session) {
self.create(null, null, createCause);
}
callback && callback();
} catch (ex) {
console.error('evme Session init error: ' + ex.message);
callback && callback();
}
});
};
this.shouldInit = function shouldInit() {
var should = { 'should': false };
if (!_session) {
should = {
'should': true,
'cause': self.INIT_CAUSE.ABSENT
};
} else if (_session.ttl == DEFAULT_TTL) {
should = {
'should': true,
'cause': _session.createCause
};
} else if (self.expired(_session)) {
should = {
'should': true,
'cause': self.INIT_CAUSE.EXPIRED
};
} else if (!self.creds()) {
should = {
'should': true,
'cause': self.INIT_CAUSE.NO_CREDS
};
}
return should;
};
this.get = function get() {
if (!_session) {
self.create(null, null, self.INIT_CAUSE.NOT_IN_CACHE);
}
return _session;
};
this.create = function create(id, ttl, cause) {
_session = {
'id': id || self.generateId(),
'ttl': ttl || DEFAULT_TTL,
'createCause': cause
};
save();
};
this.update = function update(ttl) {
if (!ttl) {
return;
}
_session['ttl'] = ttl;
save();
};
this.generateId = function generateId() {
return Evme.Utils.uuid();
};
this.creds = function creds() {
return Evme.Utils.Cookies.get(authCookieName) ||
manualCredentials || null;
};
this.expired = function expired(sessionToTest) {
!sessionToTest && (sessionToTest = _session);
var timeNow = (new Date()).getTime();
var expiration = sessionToTest.timeWritten + sessionToTest.ttl * 1000;
return (timeNow >= expiration);
};
function save() {
_session['timeWritten'] = (new Date()).getTime();
Evme.Storage.set(_key, _session);
}
};
function addRequestToPerformOnline(request) {
requestsToPerformOnOnline[request.getKey()] = request;
}
this.cancelQueue = function cancelQueue() {
for (var key in requestsToPerformOnOnline) {
requestsToPerformOnOnline[key].abort();
}
requestsToPerformOnOnline = {};
};
this.backOnline = function backOnline() {
for (var key in requestsToPerformOnOnline) {
requestsToPerformOnOnline[key].request();
}
requestsToPerformOnOnline = {};
};
this.setClientInfoLocale = function setClientInfoLocale(newLocale) {
clientInfo.lc = newLocale || navigator.language || '';
};
this.setClientInfoTimeZone = function setClientInfoTimeZone(newTimeZone) {
clientInfo.tz = newTimeZone ||
(new Date().getTimezoneOffset() / -60).toString();
};
this.setKeyboardLanguage = function setKeyboardLanguage(newKeyboardLanguage) {
clientInfo.kb = newKeyboardLanguage || '';
};
// go over the clientInfo object and construct a param from it
// clientInfo=key=value,key=value,...
this.getClientInfo = function getClientInfo() {
var value = [];
for (var key in clientInfo) {
value.push(key + '=' + clientInfo[key]);
}
value = value.join(',');
return value;
};
function request(options, ignoreCache, dontRetryIfNoSession) {
var methodNamespace = options.methodNamespace,
methodName = options.methodName,
params = options.params || {},
callback = options.callback,
noSession = options.noSession,
useCache = requestsToCache[methodNamespace + '.' + methodName],
cacheKey = '',
shouldInit = Evme.DoATAPI.Session.shouldInit(),
_request;
// truncate query
var nsQueryLength = MAX_QUERY_LENGTH[methodNamespace];
if (nsQueryLength && 'query' in params &&
params.query.length > nsQueryLength) {
params.query = params.query.substr(0, nsQueryLength);
}
// init the session (and THEN make the request)
// if the session expired/non-existent
if (shouldInit.should &&
!doesntNeedSession[methodNamespace + '.' + methodName]) {
addRequestToSessionQueue(options);
reInitSession(shouldInit.cause);
Evme.EventHandler.trigger(NAME, 'cantSendRequest', {
'method': methodNamespace + '/' + methodName,
'queue': requestsToPerformOnOnline
});
return false;
}
// the following params will be added to the cache key
if (userLat && userLon && typeof params['latlon'] == 'undefined') {
params['latlon'] = userLat + ',' + userLon;
}
params['clientInfo'] = self.getClientInfo();
if (useCache) {
cacheKey = getCacheKey(methodNamespace, methodName, params);
if (!ignoreCache) {
Evme.Storage.get(cacheKey, function storageGot(responseFromCache) {
if (responseFromCache) {
saveParamFromRequest(methodNamespace +
'.' + methodName, responseFromCache);
callback && window.setTimeout(function() {
responseFromCache && (responseFromCache._cache = true);
callback(responseFromCache);
}, 10);
} else {
actualRequest();
}
});
// since we're taking the response from the cache,
// we can't return a request now however, we don't know if there will
// be a value in the cache or not so we return an object that,
// if a request is created later on, could abort it
return {
abort: function abort() {
_request && _request.abort();
}
};
}
}
function actualRequest() {
// the following params WILL NOT BE ADDED TO THE CACHE KEY
params['apiKey'] = apiKey;
params['v'] = appVersion;
params['native'] = true;
params['platform.os'] = 'firefox-os';
// report server about new cached icons
if (methodNamespace === 'Search' && methodName === 'apps') {
params['cachedIcons'] = self.CachedIcons.yank();
}
if (manualCredentials) {
params['credentials'] = manualCredentials;
}
if (manualCampaignStats) {
for (var k in manualCampaignStats) {
params[k] = manualCampaignStats[k];
}
}
if (!noSession) {
params['sid'] = (self.Session.get() || {}).id || '';
}
params.stats = Evme.Utils.aug(params.stats, permanentStats);
/* ---------------- */
_request = new Evme.Request();
_request.init({
'methodNamespace': methodNamespace,
'methodName': methodName,
'params': params,
'originalOptions': options,
'callback': callback,
'requestTimeout': MAX_REQUEST_TIME,
'retries': NUMBER_OF_RETRIES,
'retryCheck': shouldRetry,
'timeoutBetweenRetries': RETRY_TIMEOUT,
'request': cbRequest,
'error': cbError,
'success': cbSuccess,
'clientError': cbClientError,
'onAbort': cbRequestAbort,
'cacheKey': cacheKey,
'cacheTTL': (typeof useCache == 'number') ?
useCache : CACHE_EXPIRATION_IN_MINUTES
});
if (requestsThatDontNeedConnection[methodNamespace + '.' + methodName]) {
_request.request();
} else {
Evme.Utils.isOnline(function isOnlineCallback(isOnline) {
if (isOnline) {
_request.request();
} else {
addRequestToPerformOnline(_request);
Evme.EventHandler.trigger(NAME, 'cantSendRequest', {
'method': methodNamespace + '/' + methodName,
'request': _request,
'queue': requestsToPerformOnOnline
});
}
});
}
return _request;
}
return actualRequest();
}
function shouldRetry(data) {
// If the parameters sent are incorrect, retrying won't help
return data.errorCode !== self.ERROR_CODES.INVALID_PARAMS;
}
function getCacheKey(methodNamespace, methodName, params) {
var sOptions = cacheCleanUpParams(params);
return (methodNamespace + '.' + methodName + '.' + sOptions).toLowerCase();
}
this.insertToCache = function insertToCache(cacheKey, data, cacheTTL) {
if (!data || !data.response) { return false; }
// don't cache images that aren't ready (~)
if (cacheKey.indexOf('search.bgimage') !== -1) {
if (data.response && data.response.image.data == '~') {
return false;
}
}
// don't cache errors
if (data.errorCode != self.ERROR_CODES.SUCCESS) {
return false;
}
// this causes data to be a copy of the original.
// without this, any changes to the data object will affect the original
// object (that's sent to the API callbacks)
try {
data = Evme.Utils.cloneObject(data);
} catch (ex) {
return false;
}
// clear the icons from the Apps response (to save space)
// NOTE we don't remove an icon without a revision- cause that's an
// external icon and is not cached on the server
if (cacheKey.indexOf('search.apps') !== -1 &&
data.response.apps &&
data.response.apps.length) {
for (var i = 0, l = data.response.apps.length; i < l; i++) {
if (data.response.apps[i].revision) {
data.response.apps[i].icon = null;
}
}
}
// IndexDB stores in seconds and the cacheTTL is in minutes,
// so we multiply by 60 to conver it to seconds
Evme.Storage.set(cacheKey, data, cacheTTL * 60);
Evme.Storage.get('itemsCached', function storageGot(itemsCached) {
itemsCached = itemsCached || [];
if (itemsCached.length == 1 && itemsCached[0] == '') {
itemsCached = [];
}
itemsCached.push(cacheKey);
if (itemsCached.length > MAX_ITEMS_IN_CACHE) {
var itemToRemove = itemsCached[0];
itemsCached.splice(0, 1);
Evme.Storage.remove(itemToRemove);
}
Evme.Storage.set('itemsCached', itemsCached, null);
});
return true;
};
this.removeFromCache = function removeFromCache(cacheKey) {
Evme.Storage.remove(cacheKey);
};
function cacheCleanUpParams(params) {
var retParams = [];
for (var param in params) {
if (paramsToCleanFromCacheKey.indexOf(param) == -1) {
retParams.push(param + ':' + params[param]);
}
}
retParams.sort();
return retParams.join(',');
}
this.getDeviceId = function getDeviceId() {
return deviceId;
};
function cbRequest(methodNamespace, method,
params, retryNumber, completeURL) {
Evme.EventHandler.trigger(NAME, 'request', {
'method': methodNamespace + '/' + method,
'params': params,
'retryNumber': retryNumber,
'url': completeURL
});
}
function cbRequestAbort(methodNamespace, method, params, retryNumber) {
if (sessionInitRequest) {
sessionInitRequest.abort();
requestingSession = false;
sessionInitRequest = null;
}
Evme.EventHandler.trigger(NAME, 'abort', {
'method': methodNamespace + '/' + method,
'params': params,
'retryNumber': retryNumber
});
}
function cbSuccess(methodNamespace, method, url, params, retryNumber,
data, requestDuration) {
saveParamFromRequest(methodNamespace + '.' + method, data);
Evme.EventHandler.trigger(NAME, 'success', {
'method': methodNamespace + '/' + method,
'params': params,
'retryNumber': retryNumber,
'url': url,
'response': data,
'requestDuration': requestDuration
});
}
function cbClientError(methodNamespace, method, url, params, data, ex) {
Evme.EventHandler.trigger(NAME, 'clientError', {
'method': methodNamespace + '/' + method,
'params': params,
'url': url,
'response': data,
'exception': ex
});
}
function cbError(methodNamespace, method, url, params, retryNumber, data,
callback, originalOptions) {
Evme.EventHandler.trigger(NAME, 'error', {
'method': methodNamespace + '/' + method,
'params': params,
'retryNumber': retryNumber,
'url': url,
'response': data,
'callback': callback
});
// if it's an authentication error
// return false so the request won't automatically retry
// and do a sessionInit, and retry at the end of it
if ((data &&
data.errorCode == Evme.DoATAPI.ERROR_CODES.AUTH && !manualCredentials) ||
(methodNamespace == 'Session' && method == 'init')) {