cordova-elm-template-jumpstart
Version:
Cordova template to jumpstart development using Elm and Webpack
92 lines (85 loc) • 3.02 kB
JavaScript
import deviceReady from "./deviceReady.js";
import Promise from "bluebird";
import { get,noop,toNumber,debounce,isNil } from "lodash";
import LocalForage from "localforage";
const uuidv1 = require('uuid/v1');
const generateUuid = (device) => {
const instance = LocalForage.createInstance({
name: "Device-UUID"
});
return Promise.resolve(
instance.getItem("userId")
).then(existingId => {
const cleanId = (id) => isNil(id) || id == "unknown" ? null : id;
if(cleanId(existingId)) {
return existingId;
} else {
const uuid = cleanId(device.uuid);
const serial = cleanId(device.serial);
return uuid || serial || uuidv1();
}
}).then(
id => instance.setItem("userId", id)
);
};
module.exports = deviceReady.then(device => {
const promises = [];
if(GOOGLE_TRACKING_ID) {
const ga = window.ga;
if(!ga) {
console.error("No Google Analytics attached at window.ga");
return;
}
const writeDim = (idx,val) => {
idx = toNumber(idx); // null and undefined => 0
if(idx > 0) {
ga.addCustomDimension(idx, val)
}
};
ga.startTrackerWithId(GOOGLE_TRACKING_ID);
ga.setAppVersion(VERSION);
ga.setAllowIDFACollection(true);
ga.setAnonymizeIp(false);
ga.setOptOut(false);
if(IS_DEV) { ga.debugMode(); }
if(!device) {
console.error("No device info attached at window.device");
} else {
console.info("Loaded the device data", device);
writeDim(GA_CUSTOM_DIM_CORDOVA_VERSION, device.cordova);
writeDim(GA_CUSTOM_DIM_DEVICE_MODEL, device.model);
writeDim(GA_CUSTOM_DIM_PLATFORM, device.platform);
promises.push(
generateUuid(device).then(uuid => writeDim(GA_CUSTOM_DIM_DEVICE_UUID, uuid))
);
writeDim(GA_CUSTOM_DIM_DEVICE_VERSION, device.version);
writeDim(GA_CUSTOM_DIM_DEVICE_MANUFACTURER, device.manufacturer);
}
const connectivityString = {
[Connection.UNKNOWN]: "Unknown",
[Connection.ETHERNET]: "Ethernet",
[Connection.WIFI]: "WiFi",
[Connection.CELL_2G]: "Cell 2G",
[Connection.CELL_3G]: "Cell 3G",
[Connection.CELL_4G]: "Cell 4G",
[Connection.CELL]: "Cell",
[Connection.NONE]: "None",
};
const writeConnectivity = !GA_CUSTOM_DIM_CONNECTIVITY ? noop : () => {
const connection = get(window, "navigator.connection.type", null);
if(!connection) {
console.error("No connection info attached at window.navigator.connection");
} else {
writeDim(
GA_CUSTOM_DIM_CONNECTIVITY,
connectivityString[connection] || connection
);
}
};
writeConnectivity();
window.setTimeout(writeConnectivity, 100); // Update connectivity setting often
document.addEventListener("offline", writeConnectivity, false); // Update when going online
document.addEventListener("online", writeConnectivity, false); // UPdate when going offline
}
return Promise.all(promises);
}).return(true);