From 184ddd2cb05c98a1522cdb9a2183c798e30dac94 Mon Sep 17 00:00:00 2001 From: jokenox Date: Fri, 8 Jun 2018 15:25:03 -0500 Subject: [PATCH] Blogger API v3 Compatibility --- README.md | 123 +++++++++---------------------------------------- blogger.js | 72 +++++++++++++++-------------- blogger.min.js | 18 +++++++- 3 files changed, 76 insertions(+), 137 deletions(-) diff --git a/README.md b/README.md index 86feae8..cb86a45 100644 --- a/README.md +++ b/README.md @@ -9,112 +9,35 @@ El script "limpia" la URL, eliminando de ella la fecha ```"/YYYY/MM"``` o el ``` Para implementar **BloggerJS** en tu blog, copia todo el siguiente código: ```javascript - ``` @@ -128,8 +51,6 @@ Ya que copiaste completamente el código anterior, dirígete al código HTML de ``` Una vez hecho esto, sólo guarda los cambios hechos a tu plantilla. Después de ello, **BloggerJS** estará funcionando. -Recuerda que también en su lugar, puedes usar la versión minificada de BloggerJS, que se encuentra en el archivo ```blogger.min.js``` de este repositorio. - ## Licencia Licensed under the [MIT License](./LICENSE).
Copyright (c) 2017-2018 [Kenny Cruz](https://github.com/jokenox). diff --git a/blogger.js b/blogger.js index 045510f..f0d9be9 100644 --- a/blogger.js +++ b/blogger.js @@ -1,4 +1,4 @@ -// BloggerJS v0.2.1 +// BloggerJS v0.3.0 // Copyright (c) 2017-2018 Kenny Cruz // Licensed under the MIT License @@ -11,36 +11,37 @@ var postsDatePrefix = false; // mas no en su funcionamiento general. var accessOnly = false; +// Usar API v3 de Blogger +var useApiV3 = false; +var apiKey = ""; +var blogId = ""; + // ------------------------- var postsOrPages = ["posts", "pages"], - amp = "&".substring(0, 1), urlTotal, jsonIndex = 1, secondRequest = true, - feedPriority = 0; + feedPriority = 0, + amp = "&"[0], + nextPageToken; // urlVal(); // Valida si la URL corresponde a un post/página, si no, // o si corresponde al index. function urlVal(){ - var url = window.location.pathname; var length = url.length; var urlEnd = url.substring(length - 5); - if(urlEnd === ".html") return 0; else if(length > 1) return 1; else return 2; - } // urlMod(); // Analiza la URL para identificar si se trata de un post o una página, // para después modificarla eliminando la fecha o el "/p/", así como el ".html". function urlMod(){ - var url = window.location.pathname; - if(url.substring(1, 2) === "p"){ url = url.substring(url.indexOf("/",1) + 1); url = url.substr(0, url.indexOf(".html")); @@ -52,30 +53,24 @@ function urlMod(){ url = url.substr(0, url.indexOf(".html")); history.replaceState(null, null, "../../" + url); } - } // urlSearch(url, database); // Busca una url específica en la base de datos, si la encuentra, // entonces dirigirá a ella. function urlSearch(url, database){ - var pathname = url + ".html"; - database.forEach(function(element){ var search = element.search(pathname); if(search !== -1) window.location = element; }); - } // urlManager(database, id); // Ejecuta una validación de URL, para determinar con el resultado // la acción a realizar (modificarla o buscarla en el feed del blog). function urlManager(){ - var validation = urlVal(); - if(validation === 0){ if(!accessOnly) urlMod(); } @@ -86,39 +81,46 @@ function urlManager(){ else if(validation === 2){ if(!accessOnly) history.replaceState(null, null, "/"); } - } // getJSON(); -// Realiza una petición al feed y obtiene los datos en formato JSON, -// y los envía mediante un callback. +// Realiza una petición de datos donde vienen las URLs +// y los pasa mediante un callback. function getJSON(postsOrPages, index){ - var script = document.createElement('script'); - var jsonUrl = window.location.protocol + "//" + window.location.hostname + "/feeds/" + postsOrPages + "/default?start-index=" + index + "#max-results=150#orderby=published#alt=json-in-script#callback=bloggerJSON"; + if(useApiV3){ + var jsonUrl = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/" + postsOrPages + "?key=" + apiKey + "#maxResults=500#fields=nextPageToken%2Citems(url)#callback=bloggerJSON"; + if(nextPageToken) jsonUrl += "#pageToken=" + nextPageToken; + nextPageToken = undefined; + } + else var jsonUrl = window.location.protocol + "//" + window.location.hostname + "/feeds/" + postsOrPages + "/default?start-index=" + index + "#max-results=150#orderby=published#alt=json-in-script#callback=bloggerJSON"; jsonUrl = jsonUrl.replace(/#/g, amp); - script.type = 'text/javascript'; script.src = jsonUrl; document.getElementsByTagName('head')[0].appendChild(script); - } // bloggerJSON(); -// Obtiene las URL del feed en formato JSON -// y las envía para comparar la URL actual. +// Obtiene datos en formato JSON, los clasifica +// y los envía para comparar la URL actual. function bloggerJSON(json){ - var database = []; - if(urlTotal === undefined) urlTotal = parseInt(json.feed.openSearch$totalResults.$t); - - json.feed.entry.forEach(function(element, index){ - var entry = json.feed.entry[index]; - entry.link.forEach(function(element, index){ - if(entry.link[index].rel === "alternate") database.push(entry.link[index].href); + if(!useApiV3) if(urlTotal === undefined) urlTotal = parseInt(json.feed.openSearch$totalResults.$t); + if(!useApiV3){ + json.feed.entry.forEach(function(element, index){ + var entry = json.feed.entry[index]; + entry.link.forEach(function(element, index){ + if(entry.link[index].rel === "alternate") database.push(entry.link[index].href); + }); }); - }); + } + else{ + json.items.forEach(function(element, index){ + database.push(element.url); + }); + nextPageToken = json.nextPageToken; + } urlSearch(window.location.pathname, database); @@ -127,7 +129,11 @@ function bloggerJSON(json){ urlTotal -= 150; getJSON(postsOrPages[feedPriority], jsonIndex); } + else if(nextPageToken){ + getJSON(postsOrPages[feedPriority]); + } else if(secondRequest){ + nextPageToken = undefined; urlTotal = undefined; jsonIndex = 1; secondRequest = false; @@ -140,7 +146,6 @@ function bloggerJSON(json){ getJSON("posts", 1); } } - } // bloggerJS(); @@ -149,9 +154,6 @@ function bloggerJSON(json){ // es decir, si iniciará a comparar contra las entradas o las páginas. // 0 ó vacío = Entradas, 1 = Páginas. function bloggerJS(priority){ - if(priority) feedPriority = priority; - urlManager(); - } diff --git a/blogger.min.js b/blogger.min.js index 6d84c1b..129b9ae 100644 --- a/blogger.min.js +++ b/blogger.min.js @@ -1 +1,17 @@ -function urlVal(){var e=window.location.pathname,t=e.length,r=e.substring(t-5);return".html"===r?0:t>1?1:2}function urlMod(){var e=window.location.pathname;"p"===e.substring(1,2)?(e=e.substring(e.indexOf("/",1)+1),e=e.substr(0,e.indexOf(".html")),history.replaceState(null,null,"../"+e)):(e=postsDatePrefix?e.substring(1):e.substring(e.indexOf("/",7)+1),e=e.substr(0,e.indexOf(".html")),history.replaceState(null,null,"../../"+e))}function urlSearch(e,t){var r=e+".html";t.forEach(function(e){var t=e.search(r);-1!==t&&(window.location=e)})}function urlManager(){var e=urlVal();0===e?accessOnly||urlMod():1===e?postsDatePrefix?getJSON("posts",1):getJSON(postsOrPages[feedPriority],1):2===e&&(accessOnly||history.replaceState(null,null,"/"))}function getJSON(e,t){var r=document.createElement("script"),n=window.location.protocol+"//"+window.location.hostname+"/feeds/"+e+"/default?start-index="+t+"#max-results=150#orderby=published#alt=json-in-script#callback=bloggerJSON";n=n.replace(/#/g,amp),r.type="text/javascript",r.src=n,document.getElementsByTagName("head")[0].appendChild(r)}function bloggerJSON(e){var t=[];void 0===urlTotal&&(urlTotal=parseInt(e.feed.openSearch$totalResults.$t)),e.feed.entry.forEach(function(r,n){var o=e.feed.entry[n];o.link.forEach(function(e,r){"alternate"===o.link[r].rel&&t.push(o.link[r].href)})}),urlSearch(window.location.pathname,t),urlTotal>150?(jsonIndex+=150,urlTotal-=150,getJSON(postsOrPages[feedPriority],jsonIndex)):secondRequest&&(urlTotal=void 0,jsonIndex=1,secondRequest=!1,0===feedPriority?(feedPriority=1,getJSON("pages",1)):1===feedPriority&&(feedPriority=0,getJSON("posts",1)))}function bloggerJS(e){e&&(feedPriority=e),urlManager()}var postsDatePrefix=!1,accessOnly=!1,postsOrPages=["posts","pages"],amp="&".substring(0,1),urlTotal,jsonIndex=1,secondRequest=!0,feedPriority=0;bloggerJS(); +var postsDatePrefix=!1;var accessOnly=!1;var useApiV3=!1;var apiKey="";var blogId="";var postsOrPages=["posts","pages"],urlTotal,jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0],nextPageToken;function urlVal(){var url=window.location.pathname;var length=url.length;var urlEnd=url.substring(length-5);if(urlEnd===".html")return 0;else if(length>1)return 1;else return 2} +function urlMod(){var url=window.location.pathname;if(url.substring(1,2)==="p"){url=url.substring(url.indexOf("/",1)+1);url=url.substr(0,url.indexOf(".html"));history.replaceState(null,null,"../"+url)} +else{if(!postsDatePrefix)url=url.substring(url.indexOf("/",7)+1);else url=url.substring(1);url=url.substr(0,url.indexOf(".html"));history.replaceState(null,null,"../../"+url)}} +function urlSearch(url,database){var pathname=url+".html";database.forEach(function(element){var search=element.search(pathname);if(search!==-1)window.location=element})} +function urlManager(){var validation=urlVal();if(validation===0){if(!accessOnly)urlMod()} +else if(validation===1){if(!postsDatePrefix)getJSON(postsOrPages[feedPriority],1);else getJSON("posts",1)} +else if(validation===2){if(!accessOnly)history.replaceState(null,null,"/")}} +function getJSON(postsOrPages,index){var script=document.createElement('script');if(useApiV3){var jsonUrl="https://www.googleapis.com/blogger/v3/blogs/"+blogId+"/"+postsOrPages+"?key="+apiKey+"#maxResults=500#fields=nextPageToken%2Citems(url)#callback=bloggerJSON";if(nextPageToken)jsonUrl+="#pageToken="+nextPageToken;nextPageToken=undefined} +else var jsonUrl=window.location.protocol+"//"+window.location.hostname+"/feeds/"+postsOrPages+"/default?start-index="+index+"#max-results=150#orderby=published#alt=json-in-script#callback=bloggerJSON";jsonUrl=jsonUrl.replace(/#/g,amp);script.type='text/javascript';script.src=jsonUrl;document.getElementsByTagName('head')[0].appendChild(script)} +function bloggerJSON(json){var database=[];if(!useApiV3)if(urlTotal===undefined)urlTotal=parseInt(json.feed.openSearch$totalResults.$t);if(!useApiV3){json.feed.entry.forEach(function(element,index){var entry=json.feed.entry[index];entry.link.forEach(function(element,index){if(entry.link[index].rel==="alternate")database.push(entry.link[index].href)})})} +else{json.items.forEach(function(element,index){database.push(element.url)});nextPageToken=json.nextPageToken} +urlSearch(window.location.pathname,database);if(urlTotal>150){jsonIndex+=150;urlTotal-=150;getJSON(postsOrPages[feedPriority],jsonIndex)} +else if(nextPageToken){getJSON(postsOrPages[feedPriority])} +else if(secondRequest){nextPageToken=undefined;urlTotal=undefined;jsonIndex=1;secondRequest=!1;if(feedPriority===0){feedPriority=1;getJSON("pages",1)} +else if(feedPriority===1){feedPriority=0;getJSON("posts",1)}}} +function bloggerJS(priority){if(priority)feedPriority=priority;urlManager()} +bloggerJS();