-
Notifications
You must be signed in to change notification settings - Fork 2
/
wrapper.js
625 lines (536 loc) · 23.2 KB
/
wrapper.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
/**
* To launch, inject this script file from native code at the top of the document
* Format string like this, where strWrapperScript is the contents of this file
* and strHandoff is the json encoded handoff parameters detailed below
* Always be careful to put quotes around your string arguments! *
*
* ";(" + strWrapperScript + ")('" + strHandoff + "');"
*
* To execute wrapper methods, inject js strings like this.
* "IdaMobileAppBrowsing.methodName('string')"
*
* @param strHandoff - JSON encoded handoff dictionary
*/
function wrapper(strHandoff) {
//Initialize web wrapper object, communicates to web JS that we are in mobile browsing mode
window.IdaMobileAppBrowsing = window.IdaMobileAppBrowsing || new WebWrapper(JSON.parse(strHandoff));
var fnStart = function (e) {
document.documentElement.classList.add('idaMobileLoggedOut');
window.IdaMobileAppBrowsing.launchApp();
document.IdaState = "launched";
};
if (document.IdaState) {
console.log("Ida is already " + document.IdaState)
return;
}
if (/complete|interactive|loaded/.test(document.readyState)) {
// In case the document has finished parsing, document's readyState will
// be one of "complete", "interactive" or (non-standard) "loaded".
fnStart();
} else {
// The document is not ready yet, so wait for the DOMContentLoaded event
document.IdaState = "listening";
document.addEventListener('DOMContentLoaded', fnStart, false);
}
/**
* WebWrapper module contains all webview wrapper functionality
*
* @returns WebWrapper
* @constructor
*/
function WebWrapper(opts) {
opts = opts || {};
//Launch ajax debugging if requested
if (opts.debugAjax) {
setTimeout(debugAjax, 5);
}
var _consoleLog = console.log;
var _consoleWarn = console.warn;
var _consoleErr = console.error;
return {
/**
* For debugging, make opts from launch public
*/
launchOpts: opts,
/**
* Communicate oauth token to web JS
*/
token: opts.oauthToken,
/**
* Whether the wrapper app will support deep linking into external apps
*/
deepLinking: !!opts.deepLinking,
/**
* Set/update oauth token
* @param token
* @returns {*}
*/
setToken: function (token) {
if (token) {
document.documentElement.classList.remove('idaMobileLoggedOut');
} else {
document.documentElement.classList.add('idaMobileLoggedOut');
}
return this.token = token
},
defaultAction: opts.defaultAction || "idaMessage",
/**
* Bool test if this is xamarin
*/
isXamarin: function () { return !!window.csharp },
/**
* Bool test if this is the iOS
*/
isIOs: function () { return !!window.webkit && !!window.webkit.messageHandlers[opts.appName] },
/**
* Bool test if this is android
*/
isAndroid: function () { return !!opts.isAndroid },
isLaunched: false,
/**
* Contains custom push menu items, re-add if push menu is refreshed
*/
pushMenuItems: {},
/**
* Method to post string message to native app
*
* Native apps should implement a common interface
* for reacting to messages of particular type
*
* Message types so far (feel free to add, just notify other devs)
*
* alert - pop up a native alert containing message text
* navigate - trigger native app navigation, e.g. "back"
* docready - notifies app when "documentReady" JS event has fired
* log - output message to native console, message could be any type of object
*
* @param type {String}
* @param data
*/
postToNativeApp: function (type, data, retry) {
retry = retry || 0;
var payload = {
type: type || this.defaultAction,
data: data || {}
};
try {
if (this.isXamarin()) {
var strPayload = JSON.stringify(payload);
if (window[type]) {
//Explicitly registered functions
_consoleLog('explicit function', window[type]);
window[type](strPayload);
} else {
//Else post back to default handler
_consoleLog("default action", this.defaultAction);
window.csharp("{'action':'" + this.defaultAction + "','data':'"+window.btoa(strPayload)+"'}");
}
} else if (this.isIOs()) {
window.webkit.messageHandlers[opts.appName].postMessage(payload);
} else if (this.isAndroid()) {
window.callToAndroidFunction.postMessage(type, data);
} else {
_consoleWarn('Native method not found, reposting...');
if (retry < 50) {
setTimeout(this.postToNativeApp.bind(this, type, data, retry+1), 5)
}
}
} catch (e) {
_consoleWarn(e);
}
},
/**
* Perform native-initiated navigation via ajax call for speed
*/
ajaxNavigation: function (url, blnHidePage) {
var $page, callback;
if (blnHidePage) {
$page = $('.page');
$page.hide();
callback = function () {
$page.show();
};
}
$.publish(
'ajax/load',
{
url: url,
callback: callback
}
);
},
/**
* Trigger the displayed data and navigation elements on the page to reload
*
* NOTE this does not reset cached assets, that is handled in IdaNetwork (web JS)
*/
updatePage: function () {
if (!window.iDialogs || !window.IdaNetwork) { return; }
//Refresh sub navigations
if (window.IdaNetwork.getSubNav) {
window.IdaNetwork.getSubNav();
}
var self = this;
this.setRefreshing(true);
setTimeout(function(){
self.setRefreshing(false);
}, 1500)
//Refresh content on the page via ajax
if (window.IdaNetwork.updatePageContent) {
window.IdaNetwork.updatePageContent();
} else {
//Fallback, can be deleted later...
if (window.iDialogs.constructors.Dashboard.dashboardPage()) {
$.publish('module/reload');
} else if (!window.IdaNetwork.confirmNav.blnConfirm) {
window.iDialogs.methods.updateThisPage('');
}
}
},
/**
* Update the server/version and trigger refresh of dom element
*
* @param strServer
* @param strVersion
*/
setServerAndVersion: function (strServer, strVersion) {
opts.version = strVersion;
opts.server = strServer;
this.addVersionInfo();
},
/**
* Opens the push navigation menu (hamburger menu)
*/
showNavigation: function () {
$.publish('mlpushmenu/toggle');
},
/**
* Spin the refresh icon (indicator of updating)
*/
setRefreshing: function (blnOn) {
var $refresh = $('[data-btn-action="location"] .fn-location-services-refresh');
//Small delay because it is kind of weird when the spin stops too fast. would be nice to make it full rotations...
if (blnOn) {
$refresh.addClass('icon-spin');
} else {
setTimeout(function(){
$refresh.removeClass('icon-spin');
}, 500)
}
},
locationUpdate: function (strJson) {
var locationData = JSON.parse(strJson);
$.publish('user/locationChange', locationData);
},
/**
* Adds the wrapper app version and server info to the hamburger menu
*/
addVersionInfo: function () {
var str = "App v" + opts.version + " Server: " + opts.server;
this.$versionNode = this.$versionNode || $('.mobile-wrapper-info');
if(!this.$versionNode.length > 0) {
this.$versionNode = $("<p class='mobile-wrapper-info'>" + str + "</p>");
} else {
this.$versionNode.text(str);
}
$('#mp-footer-end').append(this.$versionNode);
},
/**
* Add an item to the ml push menu (hamburger menu)
* @param name
* @param link
* @param icon
*/
appendPushMenuItem: function (name, link, icon) {
this.pushMenuItems[name] = this.pushMenuItems[name] || $(".ml-link-wrapper[data-app-item='"+name+"']");
if(this.pushMenuItems[name].length === 0) {
this.pushMenuItems[name] = $(
'<li class="ml-link-wrapper" data-app-item="+name+">' +
' <a class="ml-link app-nav-link" href="javascript:void()" data-href="' + link + '">' +
' <i class="icon-' + icon + '"></i>' +
' ' + name +
' </a>' +
'</li>'
);
}
$('#mp-menu').find(
'.mp-scroll > ul > .ml-link-wrapper:last-child'
).after(
this.pushMenuItems[name]
);
},
/**
* If logout screen is visible we hide it and notify the native app
*/
avoidLogoutScreen: function () {
var blnLoginPage = !!document.querySelector('.login-page');
if (blnLoginPage) {
$(document.documentElement).addClass('hide');
this.postToNativeApp(
"logout",
{tokenRefresh: !!this.token}
);
}
},
getWebConfigValue: function(strKey, blnPost) {
var value = null;
try {
if (window.IdaGlobals) {
value = window.IdaGlobals[strKey] || value;
if (window.IdaGlobals.config) {
value = window.IdaGlobals.config[strKey] || value;
}
if (window.IdaGlobals.appInfo) {
value = window.IdaGlobals.appInfo[strKey] || value;
}
}
if (window.iDialogs && window.iDialogs.userInfo) {
value = window.iDialogs.userInfo[strKey] || value;
}
} catch(e) {}
if (blnPost) {
this.postToNativeApp(
"config",
{
payload: [
{
key: strKey,
value: value
}
]
}
);
}
return value;
},
/**
* On document ready logic
*/
launchApp: function () {
var self = this;
//Ensures that login screen doesn't get shown if token renewal error
self.avoidLogoutScreen();
//Append optional css class to the document element
if (opts.css_class) {
$(document.documentElement).addClass(opts.css_class);
}
// Inform native app of document ready and whether we are logged in
this.postToNativeApp('docready');
if (!!window.iDialogs) {
if (window.iDialogs.userInfo.hasRole) {
if (window.iDialogs.userInfo.hasRole('traveling')) {
self.postToNativeApp('enable_location_services');
} else {
self.postToNativeApp('disable_location_services');
}
}
// Checks if user has location tracking privilege
window.iDialogs.userInfo.checkPrivilege(
'location_tracking',
function () {
self.postToNativeApp('start_location_tracking');
},
function () {
console.log('WrapperJS: iDialogs location tracking privilege denied.');
}
);
}
//Add version info to page
if (opts.server && opts.version) {
self.addVersionInfo();
//When navigation menu is refreshed, we need to re-add the version number
$.subscribe('ajax/navRefreshed', function (e, opts) {
if (opts.navElement === 'mp-menu') {
self.addVersionInfo();
if (self.pushMenuItems) {
//Re-append push menu items
$.each(self.pushMenuItems, function (name, _) {
self.appendPushMenuItem(name);
});
}
}
});
}
//Append push menu item for app options if specified
if (opts.app_options instanceof Array) {
opts.app_options.map(function (item) {
self.appendPushMenuItem(
item.name,
item.link,
item.icon
)
});
} else if (opts.app_options) {
this.appendPushMenuItem(
opts.app_options.name,
opts.app_options.link,
opts.app_options.icon
)
}
//If CSS string is provided, put it in the DOM
if (opts.style) {
var style = document.createElement('style');
style.innerHTML = opts.style;
document.head.appendChild(style)
}
//Now that publish is available, notify web JS that app browsing is active
$.publish('idaMobileApp/load', opts.appName);
$.attachHandlers(
{
/**
* Forgot password screen
* notify user in native app to check their email after resetting PW
*/
forgotPasswordBackButton: {
events: 'click',
select: '#backSent',
method: function (e) {
//Show native alert
self.postToNativeApp(
'alert',
{message: "Check your email"}
);
//Navigate back to login screen
self.postToNativeApp(
"navigate",
{navigate: "back"}
);
}
},
/**
* Listener for native logout functionality
*/
logoutNativeApp: {
events: ["tap"],
select: "[href*='/logout']",
method: function (e) {
self.postToNativeApp('logout');
}
},
/**
* General native-app links
*/
nativeAppLink: {
events: ["tap"],
select: ".app-nav-link",
method: function (e) {
e.stopImmediatePropagation();
e.preventDefault();
self.postToNativeApp(
"navigate",
{navigate: this.getAttribute('data-href')}
);
}
},
/**
* Re-run the logout screen check on any ajax load
*/
avoidLogoutScreenOnLoad: {
events: 'ajax/load/complete',
method: function () {
self.avoidLogoutScreen();
}
},
/**
* Make contextmenu action (longpress) act like a tap
*/
touchLongPress: {
events: 'press',
select: '*',
method: function (e) {
e.preventDefault();
$(this).trigger('click');
return false;
}
}
}
);
setTimeout(function () {
self.isLaunched = true;
self.postToNativeApp("loaded");
}, 1);
if (opts.debugConsole !== false) {
/**
* Send console output to native app
* Most of the time console log is just 1 string
* but if not, send everything that was logged
*
* it'd be nice if this weren't so repetitive... oh well
*/
console.log = function () {
var args = Array.prototype.slice.call(arguments, 0),
message;
if (args.length === 1 && typeof arguments[0] === "string") {
message = "Console log - " + arguments[0];
} else {
try {
message = JSON.stringify(args);
} catch (e) {
message = "Couldn't parse logged object."
}
}
window.IdaMobileAppBrowsing.postToNativeApp("log", {message: message});
return _consoleLog.apply(console, arguments);
};
console.warn = function () {
var args = Array.prototype.slice.call(arguments, 0),
message;
if (args.length === 1 && typeof arguments[0] === "string") {
message = "Console warn - " + arguments[0];
} else {
try {
message = JSON.stringify(args);
} catch (e) {
message = "Couldn't parse logged object."
}
}
window.IdaMobileAppBrowsing.postToNativeApp("log", {message: message});
return _consoleWarn.apply(console, arguments);
};
console.error = function () {
var args = Array.prototype.slice.call(arguments, 0),
message;
if (args.length === 1 && typeof arguments[0] === "string") {
message = "Console error - " + arguments[0];
} else {
try {
message = JSON.stringify(args);
} catch (e) {
message = "Couldn't parse logged object."
}
}
window.IdaMobileAppBrowsing.postToNativeApp("log", {message: message});
return _consoleErr.apply(console, arguments);
}
}
}
}
/**
* Utility to communicate the URL of all jQuery ajax calls back to native app
* Toggle on with "debugAjax" option
*/
function debugAjax() {
if (!window.$) {
setTimeout(debugAjax, 5);
return;
}
var ajax = $.ajax;
$.ajax = function () {
var cb = arguments[0].callback || function () {},
time = new Date(),
url = arguments[0].url,
args = Array.prototype.slice.call(arguments);
window.IdaMobileAppBrowsing.postToNativeApp(
"log",
{message: "Ajax url: " + url}
);
var a = ajax.apply($, args);
a.done(function () {
console.log("Elapsed " + ((new Date()) - time) + "ms - " + url);
cb.apply(this, arguments);
});
return a;
}
}
}
}