Created
November 23, 2015 19:48
-
-
Save yagop/90827ad09c99498ee224 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// superagent.min.js v1.2.0, https://github.com/visionmedia/superagent | |
!function(b){if("object"==typeof exports&&"undefined"!=typeof module){module.exports=b()}else{if("function"==typeof define&&define.amd){define([],b)}else{var a;"undefined"!=typeof window?a=window:"undefined"!=typeof global?a=global:"undefined"!=typeof self&&(a=self),a.superagent=b()}}}(function(){var d,b,a;return(function c(f,k,h){function g(q,n){if(!k[q]){if(!f[q]){var m=typeof require=="function"&&require;if(!n&&m){return m(q,!0)}if(e){return e(q,!0)}var p=new Error("Cannot find module '"+q+"'");throw p.code="MODULE_NOT_FOUND",p}var i=k[q]={exports:{}};f[q][0].call(i.exports,function(l){var o=f[q][1][l];return g(o?o:l)},i,i.exports,c,f,k,h)}return k[q].exports}var e=typeof require=="function"&&require;for(var j=0;j<h.length;j++){g(h[j])}return g})({1:[function(g,h,f){h.exports=i;function i(j){if(j){return e(j)}}function e(k){for(var j in i.prototype){k[j]=i.prototype[j]}return k}i.prototype.on=i.prototype.addEventListener=function(k,j){this._callbacks=this._callbacks||{};(this._callbacks[k]=this._callbacks[k]||[]).push(j);return this};i.prototype.once=function(m,l){var k=this;this._callbacks=this._callbacks||{};function j(){k.off(m,j);l.apply(this,arguments)}j.fn=l;this.on(m,j);return this};i.prototype.off=i.prototype.removeListener=i.prototype.removeAllListeners=i.prototype.removeEventListener=function(n,l){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var m=this._callbacks[n];if(!m){return this}if(1==arguments.length){delete this._callbacks[n];return this}var j;for(var k=0;k<m.length;k++){j=m[k];if(j===l||j.fn===l){m.splice(k,1);break}}return this};i.prototype.emit=function(n){this._callbacks=this._callbacks||{};var k=[].slice.call(arguments,1),m=this._callbacks[n];if(m){m=m.slice(0);for(var l=0,j=m.length;l<j;++l){m[l].apply(this,k)}}return this};i.prototype.listeners=function(j){this._callbacks=this._callbacks||{};return this._callbacks[j]||[]};i.prototype.hasListeners=function(j){return !!this.listeners(j).length}},{}],2:[function(f,g,e){g.exports=function(j,l,k){var i=0;var h=j.length;var m=arguments.length==3?k:j[i++];while(i<h){m=l.call(null,m,j[i],++i,j)}return m}},{}],3:[function(l,f,v){var o=l("emitter");var n=l("reduce");var r="undefined"==typeof window?(this||self):window;function i(){}function p(w){var x={}.toString.call(w);switch(x){case"[object File]":case"[object Blob]":case"[object FormData]":return true;default:return false}}h.getXHR=function(){if(r.XMLHttpRequest&&(!r.location||"file:"!=r.location.protocol||!r.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(w){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(w){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(w){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(w){}}return false};var t="".trim?function(w){return w.trim()}:function(w){return w.replace(/(^\s*|\s*$)/g,"")};function m(w){return w===Object(w)}function q(y){if(!m(y)){return y}var x=[];for(var w in y){if(null!=y[w]){x.push(encodeURIComponent(w)+"="+encodeURIComponent(y[w]))}}return x.join("&")}h.serializeObject=q;function k(C){var A={};var y=C.split("&");var z;var B;for(var x=0,w=y.length;x<w;++x){B=y[x];z=B.split("=");A[decodeURIComponent(z[0])]=decodeURIComponent(z[1])}return A}h.parseString=k;h.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"};h.serialize={"application/x-www-form-urlencoded":q,"application/json":JSON.stringify};h.parse={"application/x-www-form-urlencoded":k,"application/json":JSON.parse};function g(B){var D=B.split(/\r?\n/);var y={};var A;var E;var C;var w;D.pop();for(var x=0,z=D.length;x<z;++x){E=D[x];A=E.indexOf(":");C=E.slice(0,A).toLowerCase();w=t(E.slice(A+1));y[C]=w}return y}function j(w){return w.split(/ *; */).shift()}function u(w){return n(w.split(/ *; */),function(z,B){var y=B.split(/ *= */),x=y.shift(),A=y.shift();if(x&&A){z[x]=A}return z},{})}function e(x,w){w=w||{};this.req=x;this.xhr=this.req.xhr;this.text=((this.req.method!="HEAD"&&(this.xhr.responseType===""||this.xhr.responseType==="text"))||typeof this.xhr.responseType==="undefined")?this.xhr.responseText:null;this.statusText=this.req.xhr.statusText;this.setStatusProperties(this.xhr.status);this.header=this.headers=g(this.xhr.getAllResponseHeaders());this.header["content-type"]=this.xhr.getResponseHeader("content-type");this.setHeaderProperties(this.header);this.body=this.req.method!="HEAD"?this.parseBody(this.text?this.text:this.xhr.response):null}e.prototype.get=function(w){return this.header[w.toLowerCase()]};e.prototype.setHeaderProperties=function(z){var x=this.header["content-type"]||"";this.type=j(x);var y=u(x);for(var w in y){this[w]=y[w]}};e.prototype.parseBody=function(x){var w=h.parse[this.type];return w&&x&&(x.length||x instanceof Object)?w(x):null};e.prototype.setStatusProperties=function(w){if(w===1223){w=204}var x=w/100|0;this.status=w;this.statusType=x;this.info=1==x;this.ok=2==x;this.clientError=4==x;this.serverError=5==x;this.error=(4==x||5==x)?this.toError():false;this.accepted=202==w;this.noContent=204==w;this.badRequest=400==w;this.unauthorized=401==w;this.notAcceptable=406==w;this.notFound=404==w;this.forbidden=403==w};e.prototype.toError=function(){var y=this.req;var A=y.method;var w=y.url;var z="cannot "+A+" "+w+" ("+this.status+")";var x=new Error(z);x.status=this.status;x.method=A;x.url=w;return x};h.Response=e;function s(y,x){var w=this;o.call(this);this._query=this._query||[];this.method=y;this.url=x;this.header={};this._header={};this.on("end",function(){var A=null;var z=null;try{z=new e(w)}catch(C){A=new Error("Parser is unable to parse the response");A.parse=true;A.original=C;return w.callback(A)}w.emit("response",z);if(A){return w.callback(A,z)}if(z.status>=200&&z.status<300){return w.callback(A,z)}var B=new Error(z.statusText||"Unsuccessful HTTP response");B.original=A;B.response=z;B.status=z.status;w.callback(A||B,z)})}o(s.prototype);s.prototype.use=function(w){w(this);return this};s.prototype.timeout=function(w){this._timeout=w;return this};s.prototype.clearTimeout=function(){this._timeout=0;clearTimeout(this._timer);return this};s.prototype.abort=function(){if(this.aborted){return}this.aborted=true;this.xhr.abort();this.clearTimeout();this.emit("abort");return this};s.prototype.set=function(x,y){if(m(x)){for(var w in x){this.set(w,x[w])}return this}this._header[x.toLowerCase()]=y;this.header[x]=y;return this};s.prototype.unset=function(w){delete this._header[w.toLowerCase()];delete this.header[w];return this};s.prototype.getHeader=function(w){return this._header[w.toLowerCase()]};s.prototype.type=function(w){this.set("Content-Type",h.types[w]||w);return this};s.prototype.accept=function(w){this.set("Accept",h.types[w]||w);return this};s.prototype.auth=function(w,x){var y=btoa(w+":"+x);this.set("Authorization","Basic "+y);return this};s.prototype.query=function(w){if("string"!=typeof w){w=q(w)}if(w){this._query.push(w)}return this};s.prototype.field=function(w,x){if(!this._formData){this._formData=new r.FormData()}this._formData.append(w,x);return this};s.prototype.attach=function(y,x,w){if(!this._formData){this._formData=new r.FormData()}this._formData.append(y,x,w);return this};s.prototype.send=function(y){var z=m(y);var x=this.getHeader("Content-Type");if(z&&m(this._data)){for(var w in y){this._data[w]=y[w]}}else{if("string"==typeof y){if(!x){this.type("form")}x=this.getHeader("Content-Type");if("application/x-www-form-urlencoded"==x){this._data=this._data?this._data+"&"+y:y}else{this._data=(this._data||"")+y}}else{this._data=y}}if(!z||p(y)){return this}if(!x){this.type("json")}return this};s.prototype.callback=function(y,w){var x=this._callback;this.clearTimeout();x(y,w)};s.prototype.crossDomainError=function(){var w=new Error("Origin is not allowed by Access-Control-Allow-Origin");w.crossDomain=true;this.callback(w)};s.prototype.timeoutError=function(){var x=this._timeout;var w=new Error("timeout of "+x+"ms exceeded");w.timeout=x;this.callback(w)};s.prototype.withCredentials=function(){this._withCredentials=true;return this};s.prototype.end=function(A){var E=this;var D=this.xhr=h.getXHR();var y=this._query.join("&");var z=this._timeout;var w=this._formData||this._data;this._callback=A||i;D.onreadystatechange=function(){if(4!=D.readyState){return}var G;try{G=D.status}catch(H){G=0}if(0==G){if(E.timedout){return E.timeoutError()}if(E.aborted){return}return E.crossDomainError()}E.emit("end")};var C=function(G){if(G.total>0){G.percent=G.loaded/G.total*100}E.emit("progress",G)};if(this.hasListeners("progress")){D.onprogress=C}try{if(D.upload&&this.hasListeners("progress")){D.upload.onprogress=C}}catch(x){}if(z&&!this._timer){this._timer=setTimeout(function(){E.timedout=true;E.abort()},z)}if(y){y=h.serializeObject(y);this.url+=~this.url.indexOf("?")?"&"+y:"?"+y}D.open(this.method,this.url,true);if(this._withCredentials){D.withCredentials=true}if("GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof w&&!p(w)){var F=h.serialize[this.getHeader("Content-Type")];if(F){w=F(w)}}for(var B in this.header){if(null==this.header[B]){continue}D.setRequestHeader(B,this.header[B])}this.emit("request",this);D.send(w);return this};h.Request=s;function h(x,w){if("function"==typeof w){return new s("GET",x).end(w)}if(1==arguments.length){return new s("GET",x)}return new s(x,w)}h.get=function(w,z,x){var y=h("GET",w);if("function"==typeof z){x=z,z=null}if(z){y.query(z)}if(x){y.end(x)}return y};h.head=function(w,z,x){var y=h("HEAD",w);if("function"==typeof z){x=z,z=null}if(z){y.send(z)}if(x){y.end(x)}return y};h.del=function(w,x){var y=h("DELETE",w);if(x){y.end(x)}return y};h.patch=function(w,z,x){var y=h("PATCH",w);if("function"==typeof z){x=z,z=null}if(z){y.send(z)}if(x){y.end(x)}return y};h.post=function(w,z,x){var y=h("POST",w);if("function"==typeof z){x=z,z=null}if(z){y.send(z)}if(x){y.end(x)}return y};h.put=function(w,z,x){var y=h("PUT",w);if("function"==typeof z){x=z,z=null}if(z){y.send(z)}if(x){y.end(x)}return y};f.exports=h},{emitter:1,reduce:2}]},{},[3])(3)}); | |
window.battlefront = window.battlefront || {}; | |
window.battlefront.nucleusUrl = "https://accounts.ea.com"; | |
window.gaEventQueue = window.gaEventQueue || []; | |
// Initialize misc values and functions (language, logging, etc) | |
(function (battlefront) { | |
/*** Language handling ***/ | |
// List of supported languages, and mapping from language to locale | |
var languageMapping = { | |
"de": "de_DE", | |
"en": "en_US", | |
"es": "es_ES", | |
"mx": "es_MX", // TODO: Verify that the key mx is correct here | |
"fr": "fr_FR", | |
"it": "it_IT", | |
"ja": "ja_JP", | |
"pl": "pl_PL", | |
"pt": "pt_BR", | |
"ru": "ru_RU", | |
"zh": "zh_TW" | |
}; | |
var availableLanguages = {}; | |
Object.keys(languageMapping).forEach(function (key) { | |
availableLanguages[languageMapping[key]] = true; | |
}); | |
battlefront.languageMapping = languageMapping; | |
battlefront.availableLanguages = availableLanguages; | |
battlefront.gameLanguageMapping = { | |
"de-de": "de_DE", | |
"en-us": "en_US", | |
"es-es": "es_ES", | |
"es-mx": "es_MX", | |
"es-us": "es_MX", | |
"fr-fr": "fr_FR", | |
"it-it": "it_IT", | |
"ja-jp": "ja_JP", | |
"pl-pl": "pl_PL", | |
"pt-pt": "pt_BR", | |
"pt-br": "pt_BR", | |
"ru-ru": "ru_RU", | |
"zh-cn": "zh_TW" | |
}; | |
battlefront.getUserLocale = function () { | |
var locale = battlefront.locale; | |
if (locale) { | |
// Default to en_US if language isn't available | |
if (battlefront.availableLanguages[locale]) { | |
return locale; | |
} else { | |
return "en_US"; | |
} | |
} | |
var browserLang = navigator.language || navigator.userLanguage; | |
// Strip browser language to just language, to map to supported languages and get the right locale | |
browserLang = browserLang.toLowerCase(); | |
var langCode = browserLang.substr(0, 2); | |
return battlefront.gameLanguageMapping[browserLang] || battlefront.languageMapping[langCode] || "en_US"; | |
}; | |
/*** Logging ***/ | |
battlefront.log = function () { | |
if (localStorage && localStorage.getItem("logEnabled")) { | |
console.log.apply(console, arguments); | |
} | |
}; | |
battlefront.debug = function () { | |
if (localStorage && localStorage.getItem("debugEnabled")) { | |
console.debug.apply(console, arguments); | |
} | |
}; | |
battlefront.error = function () { | |
console.error.apply(console, arguments); | |
}; | |
/*** Misc functions ***/ | |
battlefront.isTabletSized = function () { | |
return window.innerWidth >= 600 && window.innerHeight >= 600; | |
}; | |
battlefront.getDeviceInfo = function () { | |
var uuid; | |
var deviceOs = null; | |
var deviceType = null; | |
if (typeof device !== "undefined") { | |
uuid = device.uuid; | |
deviceOs = device.platform; | |
deviceType = battlefront.isTabletSized() ? "tablet" : "phone"; | |
} else if (typeof localStorage !== "undefined") { | |
// Default uuid to some id for easier bundle overrides on iOS browsers | |
if (localStorage.getItem("uuid") === null) { | |
localStorage.setItem("uuid", "uuid-" + Date.now() + "-" + parseInt(Math.random() * 10)); | |
} | |
uuid = localStorage.getItem("uuid"); | |
} | |
return {uuid: uuid, deviceOs: deviceOs, deviceType: deviceType}; | |
}; | |
// Specify which bundle to load (app and mobile web should load mobile bundle) | |
battlefront.bundle = document.location.href.indexOf("starwars/battlefront/companion") > -1 ? "mobile" : "desktop"; | |
battlefront.showErrorPage = function () { | |
// TODO: Translate? | |
var errorHeader = "Application error"; | |
var errorRow1 = "Application couldn't be loaded correctly."; | |
var errorRow2 = "Please try again."; | |
var errorButton = "Try again"; | |
document.getElementById("react-root").innerHTML = | |
"<div id='error-container'>" + | |
"<div class='error-content'>" + | |
"<div>" + | |
"<header class='error-header'>" + errorHeader + "</header>" + | |
"<p class='error-description'>" + | |
"<span>" + errorRow1 + "</span><br />" + | |
"<span>" + errorRow2 + "</span>" + | |
"</p>" + | |
"<a class='error-button' onClick='document.location.reload();'>" + errorButton + "</a>" + | |
"</div>" + | |
"</div>" + | |
"</div>"; | |
}; | |
})(window.battlefront); | |
// Set up GatewayClient | |
(function (battlefront) { | |
function createCookie(name, value, days) { | |
var expires = ""; | |
if (days) { | |
var date = new Date(); | |
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); | |
expires = "; expires=" + date.toGMTString(); | |
} | |
document.cookie = name + "=" + value + expires + "; path=/"; | |
} | |
function readCookie(name) { | |
var nameEQ = name + "="; | |
var ca = document.cookie.split(';'); | |
for (var i = 0; i < ca.length; i++) { | |
var c = ca[i]; | |
while (c.charAt(0) == ' ') c = c.substring(1, c.length); | |
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); | |
} | |
return null; | |
} | |
function eraseCookie(name) { | |
createCookie(name, "", -1); | |
} | |
var GatewayClient = { | |
sessionId: null, | |
// Mutex | |
_backOff: {}, | |
_backOffTimeout: 1000 * 60, // One minute | |
_debug: false, | |
_gatewayProtocol: "", | |
_gatewayHost: "", | |
setGatewayUrl: function (host) { | |
// Remove protocol from host name (if such exists) | |
this._gatewayHost = host.replace("http://", "").replace("https://", ""); | |
// Use protocol depending on prod/dev environment | |
this._gatewayProtocol = host.indexOf(":8080") === -1 ? "https" : "http"; | |
}, | |
getGatewayUrl: function () { | |
return this._gatewayProtocol + "://" + this._gatewayHost; | |
}, | |
getSSO: function () { | |
// This must be synced with backend! | |
return "http://" + this._gatewayHost + "/sso?uri=" + document.location.href; | |
}, | |
setSessionId: function (sessionId) { | |
createCookie("gatewaySessionId", sessionId); | |
// Cookies doesn't seem to work on Android. Fallback to localStorage | |
localStorage && localStorage.setItem("gatewaySessionId", sessionId); | |
this.sessionId = sessionId; | |
}, | |
isLoggedIn: function () { | |
if (this.sessionId != null) { | |
return true; | |
} | |
var gatewaySessionId = readCookie("gatewaySessionId"); | |
if (gatewaySessionId != null) { | |
battlefront.debug("Using session id from cookie: " + gatewaySessionId); | |
this.sessionId = gatewaySessionId; | |
return true; | |
} | |
if (localStorage) { | |
gatewaySessionId = localStorage.getItem("gatewaySessionId"); | |
if (gatewaySessionId != null) { | |
battlefront.debug("Using session id from localStorage: " + gatewaySessionId); | |
this.sessionId = gatewaySessionId; | |
return true; | |
} | |
} | |
return false; | |
}, | |
cleanSessionId: function () { | |
this.sessionId = null; | |
localStorage.removeItem("gatewaySessionId"); | |
eraseCookie("gatewaySessionId"); | |
}, | |
logout: function (reason, redirectTo) { | |
if (!this.isLoggedIn()) { | |
return; | |
} | |
var self = this; | |
battlefront.log("Logging out due to: ", reason); | |
var onLogout = function () { | |
self.cleanSessionId(); | |
document.location.href = redirectTo || (document.location.origin + document.location.pathname); | |
}; | |
// Logout from backends | |
this.jsonRpc("Root.logout", {mobileClientId: localStorage.getItem("mobileClientId")}, onLogout, onLogout); | |
localStorage.removeItem("mobileClientId") | |
}, | |
createUUID: function () { | |
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { | |
var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8; | |
return v.toString(16); | |
}); | |
}, | |
_getRequestId: function (methodName, params) { | |
params = params || {}; | |
// Make sure keys are sorted in the same way each request | |
var keys = Object.keys(params).sort(function (a, b) { | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}); | |
var values = keys.map(function (key) { | |
return params[key]; | |
}); | |
// Is this obscure enough? | |
var separator = "&!&"; | |
return methodName + separator + values.join(separator); | |
}, | |
jsonRpc: function (methodName, params, callback, errback) { | |
var requestId = this._getRequestId(methodName, params); | |
// Request in progress? | |
if (this._backOff[requestId]) { | |
if (this._debug) { | |
battlefront.debug("Request in progress, backing off", requestId); | |
} | |
return; | |
} | |
this._backOff[requestId] = true; | |
var data = { | |
jsonrpc: "2.0", | |
method: methodName, | |
params: params, | |
id: GatewayClient.createUUID() | |
}; | |
var req = superagent.post(this.getGatewayUrl() + "/jsonrpc/whiteshark/pc/api?" + methodName); | |
if (GatewayClient.sessionId !== null) { | |
req.set("X-GatewaySession", GatewayClient.sessionId); | |
} | |
req.type("json").timeout(20000).send(data) | |
.end(function (err, response) { | |
if (err || response.error || response.body.error) { | |
var theError; | |
if (response && response.body && response.body.error) { | |
console.error("Failed", methodName, "with", params, ":", response.body.error.message); | |
theError = response.body.error; | |
if (theError.message.indexOf("se.uprise.whiteshark.gateway.services.InvalidTokenException") !== -1) { | |
GatewayClient.logout("InvalidTokenException"); | |
} | |
} else if (err) { | |
theError = err; | |
} else { | |
theError = response.error; | |
} | |
if (errback) { | |
errback(theError); | |
} | |
} else if (callback) { | |
callback(response.body.result); | |
} | |
// Request finished successfully | |
delete GatewayClient._backOff[requestId]; | |
}); | |
} | |
}; | |
// Default gateway url to current host | |
GatewayClient.setGatewayUrl(document.location.host); | |
battlefront.client = GatewayClient; | |
})(window.battlefront); | |
// Set up app initialization functions | |
(function (battlefront) { | |
var getProjectId = function () { | |
var projectIds = { | |
Android: 312357, | |
iOS: 312356, | |
Web: 312275 | |
}; | |
if (typeof device !== "undefined") { | |
switch (device.platform.toLowerCase()) { | |
case 'android': | |
return projectIds.Android; | |
case 'ios': | |
return projectIds.iOS; | |
} | |
} | |
return projectIds.Web; | |
}; | |
var getNextTelemetrySequenceNr = function () { | |
var sequence = parseInt(sessionStorage.getItem('nextTelemetrySequenceNr')) || 1; | |
sessionStorage.setItem('nextTelemetrySequenceNr', sequence + 1); | |
return sequence; | |
}; | |
var sendRiverEvent = function (endpoint) { | |
var params = { | |
projectId: getProjectId(), | |
clientTimestamp: (new Date()).getTime(), | |
sequence: getNextTelemetrySequenceNr(), | |
uuid: (typeof device !== "undefined") ? device.uuid : localStorage.getItem("uuid"), | |
gameSessionId: 0 | |
}; | |
battlefront.client.jsonRpc(endpoint, params, function (response) {}); | |
}; | |
var trackSuccessfulLogin = function (user) { | |
sendRiverEvent('Analytics.sendLoginEvent'); | |
window.gaEventQueue.push([ | |
"Companion", "User", "Login" | |
]); | |
}; | |
var trackFailedLogin = function () { | |
sendRiverEvent('Guest.sendLoginFailedEvent'); | |
window.gaEventQueue.push([ | |
"Companion", "User", "Failed Login" | |
]); | |
}; | |
var getLanguage = function (hasSetLanguage, backendLanguage, phoneLanguage) { | |
if (hasSetLanguage && backendLanguage) { | |
return backendLanguage; | |
} else { | |
return phoneLanguage; | |
} | |
}; | |
var loadApp = function (loginError) { | |
var deviceInfo = battlefront.getDeviceInfo(); | |
var uuid = deviceInfo.uuid; | |
var deviceOs = deviceInfo.deviceOs; | |
var deviceType = deviceInfo.deviceType; | |
var method = "Guest.initAppGuest"; | |
if (battlefront.client.isLoggedIn()) { | |
method = "Root.initAppLoggedIn"; | |
} | |
battlefront.debug("loadApp: Using method " + method + " since " + battlefront.client.isLoggedIn()); | |
if (loginError) { | |
trackFailedLogin(); | |
} | |
var params = { | |
uuid: uuid, | |
deviceOs: deviceOs, | |
deviceType: deviceType, | |
bundle: battlefront.bundle, | |
locale: battlefront.locale | |
}; | |
battlefront.client.jsonRpc(method, params, function (data) { | |
if (data == "INVALID_TOKEN") { | |
return battlefront.client.logout("Invalid token when doing " + method); | |
} | |
battlefront.debug("Initialized app with", data); | |
battlefront.uuid = uuid; | |
battlefront.bundleBaseURL = data.bundle_base; | |
battlefront.locale = getLanguage(data.has_set_language, data.locale, battlefront.phoneLanguage); | |
battlefront.acceptedTerms = data.accepted_terms; | |
battlefront.seenNpx = data.seen_npx; | |
battlefront.myUser = data.user; | |
battlefront.push = data.beaconpush; | |
battlefront.usageSharing = data.usageSharing; | |
battlefront.crashReports = data.crashReports; | |
battlefront.notices = data.notices; | |
battlefront.disableBaseCommand = window.cordova && data.disableBaseCommandInNativeApp; | |
battlefront.loginError = loginError; | |
battlefront.storeId = data.storeId; | |
var useDebugBundle = data.useDebugBundle; | |
battlefront.presence = {}; | |
if (data.presence && data.user) { | |
battlefront.presence[data.user && data.user.firstPartyId] = data.presence; | |
} | |
battlefront.shouldChooseProfile = data.hasOwnProperty("choose_persona") && data.choose_persona; | |
if (window.trackJs) { | |
window.trackJs.configure({ | |
// Use gateway URL as userId for easy filtering in TrackJS | |
userId: battlefront.client.getGatewayUrl(), | |
sessionId: localStorage && localStorage.getItem("gatewaySessionId") || "", | |
// TODO: We might want to specify which backend version as well | |
version: battlefront.bundleBaseURL + "/" + battlefront.getUserLocale() + "." + battlefront.bundle + ".js" | |
}); | |
} | |
var colors = "background: #111; color: #ffc715"; | |
battlefront.log("%c +------------------------ Environment ------------------------+ ", colors); | |
battlefront.log("UUID :", uuid); | |
battlefront.log("Bundle folder :", battlefront.bundleBaseURL); | |
battlefront.log("Backend URL :", battlefront.client.getGatewayUrl()); | |
battlefront.log("%c +-------------------------------------------------------------+ ", colors); | |
loadBundle("dependencies", useDebugBundle); | |
registerMobileClient(battlefront.client.getGatewayUrl(), data.user); | |
if (battlefront.client.isLoggedIn() && data.hasOwnProperty('user')) { | |
trackSuccessfulLogin(data.user); | |
} | |
// Needed by cordova which is started before above data is loaded and initialized | |
localStorage.setItem('crashReports', battlefront.crashReports); | |
}, function (err) { | |
console.error("Gateway Error: ", err); | |
if (err.message.indexOf("no valid session") !== -1) { | |
battlefront.client.logout("No valid session when doing " + method); | |
} else { | |
if (battlefront.initAppErrorHandler) { | |
battlefront.initAppErrorHandler("init_app_failed"); | |
} else { | |
battlefront.showErrorPage(); | |
} | |
} | |
}); | |
}; | |
/** | |
* Checks if user is logged in and loads appropriate bundle depending on device and locale | |
* | |
* Login flow works as follows: | |
* | |
* 1. Check if remember me token is available, as a side-effect this also renews the token | |
* | | |
* |--> 2. Logged in, load app | |
* | | |
* |--> 3. Else, show login page | |
* | | |
* |--> 4. On successful login, load app | |
* | |
* @param backend - Used for backend overrides, only used by mobile app | |
*/ | |
var initApp = function (backend) { | |
if (backend) { | |
battlefront.client.setGatewayUrl(backend); | |
} | |
var loginError = window.localStorage && localStorage.getItem("loginError"); | |
// Error state where login error occured | |
if (loginError) { | |
loginError = JSON.parse(loginError); | |
localStorage.removeItem("loginError"); | |
if (loginError.code === "GATE_ERROR") { | |
superagent.get(window.battlefront.nucleusUrl + "/connect/clearsid").withCredentials().end(function () { | |
loadApp(loginError); | |
}); | |
} else { | |
loadApp(loginError); | |
} | |
return; | |
} | |
// Clean state where we just load the app | |
if (battlefront.client.isLoggedIn()) { | |
loadApp(); | |
return; | |
} | |
var url = battlefront.nucleusUrl + | |
"/connect/auth?client_id=whiteshark-2016-companion&response_type=code" + | |
"&prompt=none&redirect_uri=nucleus:rest"; | |
superagent.get(url).withCredentials() | |
.end(function (err, res) { | |
if (err) { | |
console.error("Calling nucleus backend failed. CORS whitelisting problems?", err); | |
// Show login form | |
loadApp(); | |
} else { | |
var code; | |
try { | |
code = JSON.parse(res.text).code; | |
} catch (e) { | |
// TODO: Remove this when nucleus response is figured out properly | |
battlefront.log("Could not decode JSON from server", e, res); | |
} | |
if (code) { | |
// We are logged in with remember me | |
battlefront.client.jsonRpc("Guest.loginFromAuthCode", {code: code, redirectUri: "nucleus:rest"}, | |
function success (session) { | |
battlefront.debug("loginFromAuthCode response:", session); | |
battlefront.client.setSessionId(session.sessionId); | |
loadApp(); | |
}, | |
function error (response) { | |
battlefront.debug("loginFromAuthCode failed:", response); | |
var error; | |
// If we encounter a gate error code - redirect if desktop, else set app loginError | |
if (response.code === -32723) { | |
error = {code: "GATE_ERROR"}; | |
} | |
loadApp(error); | |
} | |
); | |
} else { | |
// Not logged in via SSO, show login form | |
loadApp(); | |
} | |
} | |
}); | |
}; | |
var initPromo = function (backend) { | |
if (backend) { | |
battlefront.client.setGatewayUrl(backend); | |
} | |
var params = { | |
uuid: window.localStorage && localStorage.getItem("uuid") | |
}; | |
battlefront.client.jsonRpc("Guest.initPromo", params, function (data) { | |
battlefront.bundleBaseURL = data.bundle_base; | |
battlefront.bundle = "game"; | |
battlefront.promoParams = {}; | |
var useDebugBundle = data.useDebugBundle; | |
// Map get parameters to a key value object in state | |
var parts = window.location.search.substr(1).split("&"); | |
parts.forEach(function (part) { | |
var keyValue = part.split("="); | |
battlefront.promoParams[keyValue[0]] = keyValue[1]; | |
}); | |
battlefront.locale = battlefront.gameLanguageMapping[battlefront.promoParams["locale"]]; | |
loadBundle("dependencies-base", useDebugBundle); | |
}); | |
}; | |
var loadBundle = function (dependencyName, useDebugBundle) { | |
var bundleName = battlefront.bundle; | |
var userLocale = battlefront.getUserLocale(); | |
var bundlePrefix = (userLocale === "en_US" && useDebugBundle ? "debug." : ""); | |
var jsBundle = bundlePrefix + userLocale + "." + bundleName + ".js"; | |
var bundleBaseURL = battlefront.bundleBaseURL; | |
battlefront.debug("Loading bundle " + jsBundle + " from "+ bundleBaseURL); | |
// Load dependencies | |
var dependencyScript = document.createElement("script"); | |
dependencyScript.onload = function () { | |
// Load specified bundle, either CSS first or JS first | |
if (bundleBaseURL.indexOf("8000") === -1) { | |
loadBundleSpecificCSS(bundleBaseURL, bundlePrefix, bundleName); | |
loadBundleSpecificJS(bundleBaseURL, jsBundle); | |
} else { | |
loadBundleSpecificJS(bundleBaseURL, jsBundle); | |
loadBundleSpecificCSS(bundleBaseURL, bundlePrefix, bundleName); | |
} | |
}; | |
dependencyScript.onerror = function () { | |
console.error("Could not load bundle"); | |
// App exposes error callback | |
if (window.battlefront.initAppErrorHandler) { | |
window.battlefront.initAppErrorHandler("bundle_load_error"); | |
} else { | |
console.error("Could not load bundles from " + bundleBaseURL); | |
} | |
}; | |
dependencyScript.src = bundleBaseURL + "/" + dependencyName + ".js"; | |
battlefront.debug("loadBundle: Loading dependencies: " + dependencyScript.src); | |
document.head.appendChild(dependencyScript); | |
}; | |
var loadBundleSpecificJS = function (bundleBaseURL, jsBundle) { | |
var script = document.createElement("script"); | |
script.src = bundleBaseURL + "/" + jsBundle; | |
battlefront.log("loadBundle: script src set to: " + script.src); | |
document.head.appendChild(script); | |
}; | |
var loadBundleSpecificCSS = function (bundleBaseURL, bundlePrefix, bundleName) { | |
var styleEl = document.createElement("link"); | |
styleEl.href = bundleBaseURL + "/" + bundlePrefix + "style." + bundleName + ".css"; | |
styleEl.rel = "stylesheet"; | |
document.head.appendChild(styleEl); | |
}; | |
var registerMobileClient = function (backend, user) { | |
var mobilePushId = localStorage.getItem("mobilePushId"); | |
if (!mobilePushId) { | |
battlefront.log("registerMobileClient: no mobilePushId"); | |
return; | |
} | |
if (!user) { | |
battlefront.log("No user - aborting"); | |
return; | |
} | |
battlefront.log("Register Mobile, backend: " + backend + " user: " + user.nucleusId); | |
if (typeof device === "undefined") { | |
battlefront.log("'device' is undefined - aborting"); | |
return; | |
} | |
var data = { | |
pushId: mobilePushId, | |
clientId: localStorage.getItem("mobileClientId"), | |
deviceOs: device.platform, | |
deviceType: battlefront.isTabletSized() ? "tablet" : "phone", | |
deviceLang: battlefront.getUserLocale(), | |
nucleusId: user.nucleusId, | |
deviceTz: 0, | |
badgesEnabled: false, | |
soundsEnabled: false, | |
pushEnabled: true, | |
synergyId: 0 | |
}; | |
var doRegister = function (data) { | |
battlefront.client.jsonRpc("Root.registerMobileDevice", data, function (data) { | |
localStorage.setItem("mobileClientId", data.clientId); | |
}); | |
}; | |
if (window.nimble) { | |
nimble.getSynergyId( | |
function(synergyId){ | |
data.synergyId = synergyId; | |
doRegister(data); | |
}, | |
function(){ | |
doRegister(data); | |
} | |
); | |
} else { | |
doRegister(data); | |
} | |
}; | |
(function (i, s, o, g, r, a, m) { | |
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { | |
(i[r].q = i[r].q || []).push(arguments) | |
}, i[r].l = 1 * new Date(); a = s.createElement(o), | |
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) | |
})(window, document, 'script', 'http://www.google-analytics.com/analytics.js', 'ga'); | |
battlefront.initApp = initApp; | |
battlefront.initPromo = initPromo; | |
})(window.battlefront); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment