$=jQuery; (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else { // Browser globals. factory(jQuery); } }(function ($) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } function converted(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { return config.json ? JSON.parse(s) : s; } catch(er) {} } var config = $.oc = function (key, value, options) { // write if (value !== undefined) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ config.raw ? key : encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // read var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); var result = key ? undefined : {}; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = decode(parts.join('=')); if (key && key === name) { result = converted(cookie); break; } if (!key) { result[name] = converted(cookie); } } return result; }; config.defaults = {}; $.roc = function (key, options) { if ($.oc(key) !== undefined) { // Must not alter options, thus extending a fresh object... $.oc(key, '', $.extend({}, options, { expires: -1 })); return true; } return false; }; })); /* Exemple : { "api_key": "1234....", instance: "myinstance", features: ["webpush"], webpush: { vapid_public_key: "1234", service_worker_url: "./serviceworker.js", auto_register: true prompt_message : "Pour ne rien rater de nos offres, inscrivez vous aux notifications!" } } */ function Omnisense(config) { this.VERSION = "2.0.3"; this.BASE_URL = "https://"+config.instance+".app.omnisense.io/api/v1"; if(config==null) { config = {}; } this.api_key = config.api_key; this.email = null; this.trid = null; this.wdid = null; this.domain = null; this.state = null; this.serviceWorkerRegistration = null; this.shouldCallUserUpdate = false; this.shouldRequestNotificationSubscription = false; var defaults = { api_key: null, instance: null, features: [], webpush: { vapid_public_key: null, service_worker_url: "/omnisenseServiceWorker.js", service_worker_scope: "/", auto_register: false, icon_url: "https://omnisense-common.s3.amazonaws.com/sdk/js/v2.0/bell.png", confirm_btn: "Accepter", later_btn: "Plus tard", primary_color: "#4aacdf", prompt_wait_time: 7 } }; config.webpush = $.extend({}, defaults.webpush, config.webpush || {}); this.config = $.extend({}, defaults, config || {}); if(this.config.features.indexOf("webpush") != -1) { $("").attr({ rel: "stylesheet", type: "text/css", href: "https://omnisense-common.s3.amazonaws.com/sdk/js/v2.0/OmnisenseSDK.css?1511885844" }).appendTo("head"); } this.timer = null; this.from = "website"; this.eventSendType = "immediate"; // queue or immediate this.events = []; var self = this; this.setEmail = function(_email) { this.email = _email; }; this.setOrigin = function(_from) { this.from = _from; }; this.setEventSendType = function(_type) { this.eventSendType = _type; }; this.trackEvent = function(identifier, segments, callback) { this.events.push({ "identifier": identifier, "segments": segments, "callback": callback }); if(this.eventSendType=="immediate" || callback!=null) { this.flushEvents(); } }; this.flushEvents = function() { if(this.email!=null || this.trid!=null) { $.each(this.events, function(index, value) { data = { "user_event": { "identifier": value["identifier"], "segments": value["segments"] } } data.api_key = self.api_key; if(self.email!=null && self.email.length>0) { data.email = self.email; } if(self.trid!=null && self.trid.length>0) { data.trid = self.trid; } if(self.wdid!=null && self.wdid.length>0) { data.wdid = self.wdid; } $.ajax({ url: self.BASE_URL+"/user_event", type: "GET", contentType: 'application/json', dataType: 'jsonp', data: data, success: function (res) { if(value.callback!=null) { value.callback(); } }, complete: function (done) { } }); }); this.events = []; } }; this.trackSession = function(endOfSession) { if(this.state=="focused") { var lastCallMs = $.oc("o_st"); var lastCallDiff = 30; if(lastCallMs!=null) { var lastCallTime = new Date(parseInt(lastCallMs)); var now = new Date(); lastCallDiff = (now-lastCallTime)/1000; } if(lastCallDiff>=30) { $.oc("o_st", (new Date()).getTime(), { expires: 1, path: "/", domain: self.domain }); if(this.email!=null || this.trid!=null) { data = { "api_key": this.api_key, "from": this.from, "session_end": endOfSession } if(this.email!=null && this.email.length>0) { data.email = this.email; } if(this.trid!=null && this.trid.length>0) { data.trid = this.trid; } if(self.wdid!=null && self.wdid.length>0) { data.wdid = self.wdid; } $.ajax({ url: this.BASE_URL+"/user_session", type: "GET", contentType: 'application/json', dataType: 'jsonp', data: data, success: function (res) { }, complete: function (done) { if (done.status == 200 && self.eventSendType=="queue") { self.flushEvents(); } if(self.state=="focused") self.timer = setTimeout(function(){self.trackSession(false); }, 30000); } }); } } else { //Wait until now - lastCall = 30s //console.log("wait "+(30 - parseInt(lastCallDiff))+"s before sending session"); clearTimeout(self.timer); self.timer = setTimeout(function(){self.trackSession(false); }, (30 - parseInt(lastCallDiff))*1000); } } }; this.updateUser = function(user, metadata, additionalData) { if(this.email!=null) { if(user==null) { user = {"email": this.email}; } else { $.extend(user,{"email": this.email}); } } data = { "api_key": this.api_key, "wd": true }; if(user!=null) { $.extend(data,{"user": user }); } if(metadata!=null) { $.extend(data,{"metadata": metadata }); } if(this.trid!=null) { $.extend(data,{"trid": this.trid }); } if(this.wdid!=null) { $.extend(data,{"wdid": this.wdid }); } if(additionalData!=null) { $.extend(data,additionalData); } $.ajax({ url: this.BASE_URL+"/subscriber", type: "POST", contentType: 'application/json', data: JSON.stringify(data), success: function (response) { if(response!=null && response.trid!=null) { var ts = (self.trid==null); var wdidWasNull = (self.wdid==null); var pushSubscriber = false; self.trid = response.trid; if(response.wdid!=null) { self.wdid = response.wdid; pushSubscriber = (response.web_device!=null ? response.web_device.push_subscriber : true); $.oc("wdid", response.wdid, { expires: 365, path: "/", domain: self.domain }); $.oc("o_webpush_checked_at", (new Date()).getTime(), { expires: 365, path: "/" }); } $.oc("trid", response.trid, { expires: 365, path: "/", domain: self.domain }); if(ts && document.hasFocus()) { self.trackSession(false); } if( self.isWebpushConfigured() && self.isPushApiSupported() && self.isPushNotificationPermissionGranted()) { if(self.serviceWorkerRegistration!=null) { self.serviceWorkerRegistration.pushManager.getSubscription() .then(function(subscription){ if(subscription==null || !pushSubscriber) { self.registerForPushNotifications(); } else if((ts || wdidWasNull || !pushSubscriber)) { self._unsubscribe_resubscribe(); } }); } } } } }); } this.subscribeNotifications = function(subscription) { subscription = subscription.toJSON(); this.updateUser(null, null, { webpush_registration: { endpoint: subscription.endpoint, auth: subscription.keys.auth, p256dh: subscription.keys.p256dh } }); } this.start = function() { if (navigator.serviceWorker && this.config.features.indexOf("webpush")!=-1) { navigator.serviceWorker.register(this.config.webpush.service_worker_url, { scope: this.config.webpush.service_worker_scope }).then( function(serviceWorkerRegistration) { self.serviceWorkerRegistration = serviceWorkerRegistration; if(self.config.webpush.auto_register && !self.isPushNotificationPermissionGranted()) { self.displayWebpushPrompt(); //self.registerForPushNotifications(); } }); } this.state = (document.hasFocus() ? "focused" : "blurred"); $(window).focus(function() { self.state = "focused"; self.trackSession(false); }); $(window).blur(function() { self.state = "blurred"; clearTimeout(self.timer); }); /*$(window).on('beforeunload ',function() { self.trackSession(true); clearTimeout(self.timer); });*/ if(this.trid==null || this.shouldCallUserUpdate || (this.config.features.indexOf("webpush")!=-1 && (this.wdid==null || this.shouldCheckPushSubscription() ) )) { this.updateUser(null); } else { this.trackSession(false); } }; this.displayWebpushPrompt = function() { if( this.isWebpushConfigured() && this.shouldDisplayPrompt() && this.isPushApiSupported() && !this.isPushNotificationPermissionDenied() && !this.isPushNotificationPermissionGranted() ) { var prompt = $("