UNPKG

hexo-seo-submit

Version:

Manual or automatic submit your site to search engines(google, bing, baidu). There are Github actions and coding jenkins available for CI

7 lines 8.38 kB
import P from'chalk';import De from'lodash.merge';import te from'node:path';import oe from'wildcard-match';import W from'node:fs/promises';import k from'handlebars';import fe from'axios';import {HttpsProxyAgent}from'https-proxy-agent';import {GoogleAuth}from'google-auth-library';var s="hexo-seo-submit",c=(n=>(n.BAIDU="baidu",n.BING="bing",n.GOOGLE="google",n))(c||{});var M="hexo-seo-submit",x={baidu:"http://data.zz.baidu.com/urls",bing:"https://ssl.bing.com/webmaster/api.svc/pox/SubmitUrlBatch",google:"https://indexing.googleapis.com/batch"},b=` `;function T(e,o){return e?.length?oe(e)(o):true}var ne=(e,o)=>(e?.slice()||[])?.sort((n,t)=>t[o]-n[o]),E=(e,o)=>{let r=e.toArray()?.slice()||[];r=r?.map(u=>{let{date:h,updated:d,permalink:O}=u;return {permalink:O,created:Date.parse(h.format("yyyy-MM-DD HH:mm:ss")),updated:Date.parse(d.format("yyyy-MM-DD HH:mm:ss"))}});let{sortBy:n,count:t,includePaths:i,excludePaths:f}=o||{},a=hexo.config[s],g=i||a.includePaths,m=f||a.excludePaths,l=ne(r,n||a.sortBy||"created")?.map(u=>u.permalink);return (g?.length||m?.length)&&(l=l.filter(u=>{let h=new URL(u).pathname,d=T(g,h),O=T(m,h);return d||!O})),l=l?.slice(0,t||a.count||void 0),l?.join(b)},p=e=>{let o=hexo.config[s];return te.join(o.fileRootPath??M,e)},S=e=>{let o=hexo.config[s][e];return typeof o!="object"?(console.log(P.bgRed(`${s}: wrong search engine config, please check`)),{}):o||{}},G=()=>hexo.config.url;var y=e=>new Promise((o,r)=>{if(!Object.keys(e||{}).length){r(new Error("exit~ can not find any config"));return}let{enable:n}=e;if(typeof n!="boolean"||!n){r(new Error("exit~ this engine is not enabled"));return}o("success");}),J=e=>new Promise((o,r)=>{if(!e){r(new Error("no config here"));return}let{file:n,accountKeysJSon:t,accountKeysJSonFile:i}=e;if(!n){r(new Error("Where are files?"));return}if(!t&&!i){r(new Error("Where are accountKeys?"));return}o("done");});var w=`${s}[baidu]engine`,ie=async e=>{console.log(P.bgGreen(`${w}: generator running`));let o=S("baidu");try{await y(o);}catch(i){console.log(P.bgRed.bold(`${w}: ${i.message}`));return}let{path:r,...n}=o,t={data:E(e.posts,n),path:p(r)};if(!t.data?.length){P.bgRed(`${s}: generator error, no post found, please check your config`);return}return console.log(P.bgGreen(`${w}: generator done`)),t},N=ie;var H=`${s}[bing]engine`,se=async e=>{console.log(P.bgBlue.white(`${H}: generator running`));let o=S("bing");try{await y(o);}catch(f){console.log(P.bgRed.bold(`${H}: ${f.message}`));return}let{path:r,...n}=o,t={data:E(e.posts,n)};if(!t.data?.length){P.bgRed(`${s}: generator error, no post found, please check your config`);return}let i={data:JSON.stringify({siteUrl:hexo.config.url,urlList:t.data.split(b)}),path:p(r)};return console.log(P.bgBlue.white(`${H}: generator done`)),i},B=se;var D=`${s}[google]engine`,ae=async e=>{console.log(P.bgYellowBright(`${D}: generator running`));let o=S("google");try{await y(o);}catch(i){console.log(P.bgRed.bold(`${D}: ${i.message}`));return}let{path:r,...n}=o,t={data:E(e.posts,n),path:p(r)};if(!t.data?.length){P.bgRed(`${s}: generator error, no post found, please check your config`);return}return console.log(P.bgYellowBright(`${D}: generator done`)),t},R=ae;k.registerHelper("if_eq",function(e,o,r){return e===o?r.fn(this):r.inverse(this)});k.registerHelper("raw",function(e){return e.toString()});var ce=(e,o)=>k.compile(e,{noEscape:true})(o),K=ce;var _=`${s}[CI]:`,v=async e=>await W.readFile(te.join(__dirname,e),"utf-8"),pe=async()=>{let e=hexo.config[s],o=e.CI;if(!o||!o?.enable)return;console.log(P.bgGreen(`${_} running.`));let{cron:r,branch:n}=o,t=Object.values(c).map(m=>({...e[m],key:m})).filter(m=>m.enable).reduce((m,l)=>{let{enable:u,path:h,key:d}=l||{};return m[d]={enable:u,file:p(h),name:d},m},{});if(!Object.keys(t).length){console.log(P.bgRed(`${_} error, no search engine enabled, please check your config`));return}let i={github:{schedule:{cron:r},site:G(),path:`.github/workflows/${s}.yml`,templateFile:await v("handlebars/template/actions.tpl"),branch:n,...t},coding:{site:G(),path:"Jenkinsfile",templateFile:await v("handlebars/template/jenkins.tpl"),...t}},a={...{PACKAGE_VERSION:"1.8.0"},...i[o.platform]};if(!a){P.bgRed(`${_} error, no platform found, please check your config`);return}let g=K(a.templateFile,a);return {path:a.path,data:g}},j=pe;var ue=2e4,he=fe.create({timeout:ue,paramsSerializer:{}}),de=he.request,C=de;var q=(e,o)=>{let{site:r,...n}=o;return C({url:`${x.baidu}?site=${r}`,data:e,method:"post",params:n,headers:{"Content-type":"text/plain"}})};var Se=async e=>{console.log(P.bgGreen("baidu push running"));let{path:o,token:r}=e,n=await W.readFile(te.join(hexo.public_dir,p(o)),"utf8");try{let t=await q(n,{site:G(),token:r});return Promise.resolve(`baidu: success ${t?.data?.success}; ${t?.data?.remain} remain`)}catch(t){return Promise.reject(new Error(t.response?.data?.message||t.message))}},z=Se;var Y=(e,o)=>{let{apiKey:r,siteUrl:n}=o;return C({url:x.bing,method:"post",params:{apiKey:r},data:{urlList:e,siteUrl:n},headers:{"Content-Type":"application/json; charset=utf-8"}})};var Pe=async e=>{console.log(P.bgGreen("bing push running"));let{path:o,apiKey:r}=e,n=await W.readFile(te.join(hexo.public_dir,p(o)),"utf8"),t=JSON.parse(n||"");if(!t||typeof t!="object")return Promise.reject(new Error("bing: parse content failed"));try{return await Y(t?.urlList,{siteUrl:t?.siteUrl,apiKey:r}),Promise.resolve("bing: push success")}catch(i){return Promise.reject(new Error(i?.response?.data||i.message))}},Q=Pe;var Ue=async e=>await(await new GoogleAuth({credentials:{client_email:e.client_email,private_key:e.private_key?.replace(/(\\|\\\\)n/g,` `)},scopes:["https://www.googleapis.com/auth/indexing"]}).getClient()).getAccessToken(),V=async e=>{let{urlList:o,secretsConfig:r,proxy:n}=e,t={};if(n){let l=new HttpsProxyAgent(n);t.proxy=false,t.httpsAgent=l,process.env.HTTPS_PROXY=n,process.env.HTTP_PROXY=n;}let i=await Ue(r),f=`===============${Math.round(Math.random()*2e5)}==`,a=o.map(l=>({body:JSON.stringify({url:l,type:"URL_UPDATED"})})),g=` `,m=a.map(l=>`\r --${f}${g}Content-Type: application/http ${g}Content-Transfer-Encoding: binary ${g}\r POST /v3/urlNotifications:publish ${g}Content-Type: application/json ${g}accept: application/json ${g}Content-Length:${l.body.length}${g}\r ${l.body}`).join("");return C({method:"post",url:x.google,headers:{Authorization:`Bearer ${i.token}`,"Content-Type":`multipart/mixed; boundary=${f}`},data:m,...t})};var Oe=async e=>{try{await J(e);}catch(m){return Promise.reject(m.message)}let{file:o,accountKeysJSon:r,accountKeysJSonFile:n,proxy:t}=e,i=r;n&&(i=await W.readFile(te.join(process.cwd(),n),"utf8"));let f=JSON.parse(i||""),a=await W.readFile(o,"utf8");if(!a)return Promise.reject(new Error("no url to submit"));let g=a.split(b);return V({urlList:g,secretsConfig:f,proxy:t})},X=Oe;var Ne=async e=>{console.log(P.bgGreen("google push running"));let{path:o,accountKeysJSonFile:r,proxy:n}=e;try{let t=await X({file:te.join(hexo.public_dir,p(o)),accountKeysJSonFile:r,proxy:n});return t?.data?.includes(200)?Promise.resolve("google push success"):Promise.reject(`google failed ${t?.data}`)}catch(t){return Promise.reject(t?.response?.data.error.message||t.message)}},Z=Ne;var I=`${s}-deploys:`,He=async e=>{console.log(P.bgGreenBright(`${I} running`));let o=e.config[s];o||console.log(P.bgRed(`${I} please check your config`));let r=Object.values(c).map(i=>({...o[i],engineType:i})).filter(i=>i.enable===true);r.length||console.log(P.bgRed(`${I} no search engine config enabled`));let n={baidu:z,bing:Q,google:Z},t=r.map(async i=>n[i.engineType]?.(i));try{(await Promise.allSettled(t)).forEach(f=>{let{status:a}=f;if(a==="fulfilled")console.log(P.bgGreen(f.value));else throw new Error(f.reason)});}catch(i){console.log(P.bgRed(`${I} ${i.message}`));}},ee=He;console.log(P.bold.bgMagenta(`${s}@1.8.0 run, have fun!`));var F={enable:false},Re={fileRootPath:"",count:10,CI:{enable:true,platform:"github",cron:"0 4 * * *",branch:"master"},baidu:{...F,path:"baidu.txt"},bing:{...F,path:"bing.json"},google:{...F,path:"google.txt"}};hexo.config[s]=De({},Re,hexo.config[s]);hexo.extend.generator.register(`${s}[baidu] generator`,N);hexo.extend.generator.register(`${s}[bing] generator`,B);hexo.extend.generator.register(`${s}[google] generator`,R);hexo.extend.generator.register(`${s}[CI] generator`,j);hexo.extend.deployer.register(s,async()=>await ee(hexo));