From 1ce1455ce29c0c33a1b5d44a8964ce16259fe568 Mon Sep 17 00:00:00 2001
From: Cotes Chung <11371340+cotes2020@users.noreply.github.com>
Date: Wed, 1 Apr 2020 20:33:49 +0800
Subject: [PATCH] Improved the PV fetching experience.
---
_config.yml | 12 +--
_includes/head.html | 9 +-
_layouts/home.html | 2 +-
_layouts/post.html | 2 +-
assets/data/proxy.json | 6 --
assets/data/pv-data.json | 13 +++
assets/data/search.json | 1 +
assets/js/_src/pageviews.js | 146 +++++++++++++++++++++++++++-----
assets/js/dist/pageviews.min.js | 2 +-
9 files changed, 155 insertions(+), 38 deletions(-)
delete mode 100644 assets/data/proxy.json
create mode 100644 assets/data/pv-data.json
diff --git a/_config.yml b/_config.yml
index 4f3a0cd..ee674b9 100644
--- a/_config.yml
+++ b/_config.yml
@@ -55,12 +55,14 @@ google_analytics:
# Fill with your Google Analytics ID
id: ''
# The Google Analytics pageviews switch.
- # DO NOT enable it unless you know how to deploy the Google Analytics superProxy.
- pv: false
- # superProxy baseURL and URL, only valid when `google_analytics.pv` is set to 'true'
- proxy_baseurl: ''
- proxy_url: ''
+ pv:
+ # DO NOT enable it unless you know how to deploy the Google Analytics superProxy.
+ enabled: false
+ # the next options only valid when `google_analytics.pv` is enabled.
+ proxy_url: ''
+ proxy_endpoint: ''
+ cache: false # pv data local cache, good for the users from GFW area.
disqus:
comments: false # boolean type, the global switch for posts comments.
diff --git a/_includes/head.html b/_includes/head.html
index 9943f18..35ee55f 100644
--- a/_includes/head.html
+++ b/_includes/head.html
@@ -34,9 +34,9 @@
- {% if site.google_analytics.proxy_baseurl and site.google_analytics.pv %}
-
-
+ {% if site.google_analytics.pv.proxy_url and site.google_analytics.pv.enabled %}
+
+
{% endif %}
{% endif %}
@@ -122,7 +122,8 @@
{% if page.layout == 'home' or page.layout == 'post' %}
- {% if site.google_analytics.pv %}
+ {% if site.google_analytics.pv.enabled %}
+
{% endif %}
diff --git a/_layouts/home.html b/_layouts/home.html
index 38d76e3..ea69a62 100644
--- a/_layouts/home.html
+++ b/_layouts/home.html
@@ -28,7 +28,7 @@ layout: page
{{ post.date | date_to_xmlschema }}
- {% if site.google_analytics.pv %}
+ {% if site.google_analytics.pv.enabled %}
diff --git a/_layouts/post.html b/_layouts/post.html
index 45a1041..4247531 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -31,7 +31,7 @@ layout: default
- {% if site.google_analytics.pv %}
+ {% if site.google_analytics.pv.enabled %}
views
diff --git a/assets/data/proxy.json b/assets/data/proxy.json
deleted file mode 100644
index 58c185f..0000000
--- a/assets/data/proxy.json
+++ /dev/null
@@ -1,6 +0,0 @@
----
----
-
-{
- "proxyUrl": "{{ site.google_analytics.proxy_url }}"
-}
\ No newline at end of file
diff --git a/assets/data/pv-data.json b/assets/data/pv-data.json
new file mode 100644
index 0000000..230a0dc
--- /dev/null
+++ b/assets/data/pv-data.json
@@ -0,0 +1,13 @@
+---
+layout: compress
+---
+
+const proxyData = '{"url": "{{ site.google_analytics.pv.proxy_endpoint }}"}';
+
+{%- capture pv_data -%}
+ {%- if site.google_analytics.pv.cache and site.google_analytics.pv.enabled -%}
+ {% include_relative pageviews.json %}
+ {%- endif -%}
+{%- endcapture -%}
+
+const pageviews = '{{ pv_data }}';
diff --git a/assets/data/search.json b/assets/data/search.json
index 08d853d..6ae087f 100644
--- a/assets/data/search.json
+++ b/assets/data/search.json
@@ -1,4 +1,5 @@
---
+layout: compress
---
[
diff --git a/assets/js/_src/pageviews.js b/assets/js/_src/pageviews.js
index 800ab8c..bd8654e 100644
--- a/assets/js/_src/pageviews.js
+++ b/assets/js/_src/pageviews.js
@@ -3,7 +3,7 @@
*
* Dependences:
* - jQuery
- * - countUp.js(https://github.com/inorganik/countUp.js)
+ * - countUp.js
*
* v2.0
* https://github.com/cotes2020/jekyll-theme-chirpy
@@ -77,42 +77,148 @@ function displayPageviews(data) {
var path = window.location.pathname;
tacklePV(rows, path, $('#pv'), hasInit);
}
-
}
var getInitStatus = (function() {
var hasInit = false;
return function() {
- if (hasInit) {
- return true;
- } else {
+ let ret = hasInit;
+ if (!hasInit) {
hasInit = true;
- return false;
}
+ return ret;
}
})();
+var PvCache = (function() {
+ const KEY_PV = "pv";
+ const KEY_CREATION = "pv-created-date";
+ const KEY_PV_TYPE = "pv-type";
+
+ var PvType = {
+ ORIGIN: "origin",
+ PROXY: "proxy"
+ };
+
+ function get(key) {
+ return localStorage.getItem(key);
+ }
+
+ function set(key, val) {
+ localStorage.setItem(key, val);
+ }
+
+ return {
+ getData: function() {
+ return JSON.parse(localStorage.getItem(KEY_PV) );
+ },
+ saveOriginCache: function(pv) {
+ set(KEY_PV, pv);
+ set(KEY_PV_TYPE, PvType.ORIGIN );
+ set(KEY_CREATION, new Date().toJSON() );
+ },
+ saveProxyCache: function(pv) {
+ set(KEY_PV, pv);
+ set(KEY_PV_TYPE, PvType.PROXY );
+ set(KEY_CREATION, new Date().toJSON() );
+ },
+ isOriginCache: function() {
+ return get(KEY_PV_TYPE) == PvType.ORIGIN;
+ },
+ isProxyCache: function() {
+ return get(KEY_PV_TYPE) == PvType.PROXY;
+ },
+ isExpired: function() {
+ if (PvCache.isOriginCache() ) {
+ let date = new Date(get(KEY_CREATION));
+ date.setDate(date.getDate() + 1); // fetch origin-data every day
+ return Date.now() >= date.getTime();
+
+ } else if (PvCache.isProxyCache() ) {
+ let date = new Date(get(KEY_CREATION) );
+ date.setHours(date.getHours() + 1); // proxy-data is updated every hour
+ return Date.now() >= date.getTime();
+ }
+ return false;
+ },
+ getAllPagevies: function() {
+ return PvCache.getData().totalsForAllResults["ga:pageviews"];
+ },
+ newerThan: function(pv) {
+ return PvCache.getAllPagevies() > pv.totalsForAllResults["ga:pageviews"];
+ }
+ };
+
+})(); // PvCache
+
+
+function fetchOriginPageviews(pvData) {
+ if (pvData === undefined) {
+ return;
+ }
+ displayPageviews(pvData);
+ PvCache.saveOriginCache(JSON.stringify(pvData));
+}
+
+
+function fetchProxyPageviews() {
+ let proxy = JSON.parse(proxyData); // see file '/assets/data/pv-data.json'
+ $.ajax({
+ type: 'GET',
+ url: proxy.url,
+ dataType: 'jsonp',
+ jsonpCallback: "displayPageviews",
+ success: function(data, textStatus, jqXHR) {
+ PvCache.saveProxyCache(JSON.stringify(data));
+ },
+ error: function(jqXHR, textStatus, errorThrown) {
+ console.log("Failed to load pageviews from proxy server: " + errorThrown);
+ }
+ });
+}
+
+
$(function() {
- // load pageview if this page has .pageviews
+
if ($('.pageviews').length > 0) {
- // Get data from daily cache.
- $.getJSON('/assets/data/pageviews.json', displayPageviews);
+ let originPvData = pageviews ? JSON.parse(pageviews) : undefined;
+ let cache = PvCache.getData();
- $.getJSON('/assets/data/proxy.json', function(meta) {
- $.ajax({
- type: 'GET',
- url: meta.proxyUrl,
- dataType: 'jsonp',
- jsonpCallback: "displayPageviews",
- error: function(jqXHR, textStatus, errorThrown) {
- console.log("Failed to load pageviews from proxy server: " + errorThrown);
+ if (cache) {
+ if (PvCache.isExpired()) {
+ if (PvCache.isProxyCache() ) {
+ if (originPvData) {
+ if (PvCache.newerThan(originPvData)) {
+ displayPageviews(cache);
+ } else {
+ fetchOriginPageviews(originPvData);
+ }
+ }
+
+ fetchProxyPageviews();
+
+ } else if (PvCache.isOriginCache() ) {
+ fetchOriginPageviews(originPvData);
+ fetchProxyPageviews();
}
- });
- });
+ } else { // still valid
+ displayPageviews(cache);
+
+ if (PvCache.isOriginCache() ) {
+ fetchProxyPageviews();
+ }
+
+ }
+
+ } else {
+ fetchOriginPageviews(originPvData);
+ fetchProxyPageviews();
+ }
+
+ }
- } // endif
});
diff --git a/assets/js/dist/pageviews.min.js b/assets/js/dist/pageviews.min.js
index ce5404a..a480572 100644
--- a/assets/js/dist/pageviews.min.js
+++ b/assets/js/dist/pageviews.min.js
@@ -1 +1 @@
-function countUp(b,a,d){if(ba){countUp(a,c,d.attr("id"))}}}function displayPageviews(c){if(c===undefined){return}var a=getInitStatus();var b=c.rows;if($("#post-list").length>0){$(".post-preview").each(function(){var e=$(this).children("h1").children("a").attr("href");tacklePV(b,e,$(this).find(".pageviews"),a)})}else{if($(".post").length>0){var d=window.location.pathname;tacklePV(b,d,$("#pv"),a)}}}var getInitStatus=(function(){var a=false;return function(){if(a){return true}else{a=true;return false}}})();$(function(){if($(".pageviews").length>0){$.getJSON("/assets/data/pageviews.json",displayPageviews);$.getJSON("/assets/data/proxy.json",function(a){$.ajax({type:"GET",url:a.proxyUrl,dataType:"jsonp",jsonpCallback:"displayPageviews",error:function(b,d,c){console.log("Failed to load pageviews from proxy server: "+c)}})})}});
\ No newline at end of file
+function countUp(b,a,d){if(ba){countUp(a,c,d.attr("id"))}}}function displayPageviews(c){if(c===undefined){return}var a=getInitStatus();var b=c.rows;if($("#post-list").length>0){$(".post-preview").each(function(){var e=$(this).children("h1").children("a").attr("href");tacklePV(b,e,$(this).find(".pageviews"),a)})}else{if($(".post").length>0){var d=window.location.pathname;tacklePV(b,d,$("#pv"),a)}}}var getInitStatus=(function(){var a=false;return function(){let ret=a;if(!a){a=true}return ret}})();var PvCache=(function(){const e="pv";const b="pv-created-date";const d="pv-type";var c={ORIGIN:"origin",PROXY:"proxy"};function a(g){return localStorage.getItem(g)}function f(g,h){localStorage.setItem(g,h)}return{getData:function(){return JSON.parse(localStorage.getItem(e))},saveOriginCache:function(g){f(e,g);f(d,c.ORIGIN);f(b,new Date().toJSON())},saveProxyCache:function(g){f(e,g);f(d,c.PROXY);f(b,new Date().toJSON())},isOriginCache:function(){return a(d)==c.ORIGIN},isProxyCache:function(){return a(d)==c.PROXY},isExpired:function(){if(PvCache.isOriginCache()){let date=new Date(a(b));date.setDate(date.getDate()+1);return Date.now()>=date.getTime()}else{if(PvCache.isProxyCache()){let date=new Date(a(b));date.setHours(date.getHours()+1);return Date.now()>=date.getTime()}}return false},getAllPagevies:function(){return PvCache.getData().totalsForAllResults["ga:pageviews"]},newerThan:function(g){return PvCache.getAllPagevies()>g.totalsForAllResults["ga:pageviews"]}}})();function fetchOriginPageviews(a){if(a===undefined){return}displayPageviews(a);PvCache.saveOriginCache(JSON.stringify(a))}function fetchProxyPageviews(){let proxy=JSON.parse(proxyData);$.ajax({type:"GET",url:proxy.url,dataType:"jsonp",jsonpCallback:"displayPageviews",success:function(b,c,a){PvCache.saveProxyCache(JSON.stringify(b))},error:function(a,c,b){console.log("Failed to load pageviews from proxy server: "+b)}})}$(function(){if($(".pageviews").length>0){let originPvData=pageviews?JSON.parse(pageviews):undefined;let cache=PvCache.getData();if(cache){if(PvCache.isExpired()){if(PvCache.isProxyCache()){if(originPvData){if(PvCache.newerThan(originPvData)){displayPageviews(cache)}else{fetchOriginPageviews(originPvData)}}fetchProxyPageviews()}else{if(PvCache.isOriginCache()){fetchOriginPageviews(originPvData);fetchProxyPageviews()}}}else{displayPageviews(cache);if(PvCache.isOriginCache()){fetchProxyPageviews()}}}else{fetchOriginPageviews(originPvData);fetchProxyPageviews()}}});
\ No newline at end of file