Merge pull request #23 from eiblog/fix_disqus

Fix disqus
This commit is contained in:
Deepzz authored and GitHub committed 2019-12-18 19:22:11 +08:00
commit f5c0bcdb99
5 files changed
+96 -21

No files matched your search

-2
View File
@@ -43,8 +43,6 @@ disqus:
postcreate: https://disqus.com/api/3.0/posts/create.json postcreate: https://disqus.com/api/3.0/posts/create.json
postapprove: https://disqus.com/api/3.0/posts/approve.json postapprove: https://disqus.com/api/3.0/posts/approve.json
threadcreate: https://disqus.com/api/3.0/threads/create.json threadcreate: https://disqus.com/api/3.0/threads/create.json
# disqus.js 文件名
embed: disqus_7d3cf2.js
# 获取评论数量间隔 # 获取评论数量间隔
interval: 5 interval: 5
# 谷歌统计 # 谷歌统计
+94 -15
View File
@@ -3,10 +3,12 @@
package main package main
import ( import (
"crypto/tls"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@@ -58,7 +60,7 @@ func PostsCount() error {
count++ count++
} }
count = 0 count = 0
resp, err := http.Get(setting.Conf.Disqus.PostsCount + "?" + vals.Encode()) resp, err := Get(setting.Conf.Disqus.PostsCount + "?" + vals.Encode())
if err != nil { if err != nil {
return err return err
} }
@@ -128,7 +130,7 @@ func PostsList(slug, cursor string) (*postsListResp, error) {
vals.Set("cursor", cursor) vals.Set("cursor", cursor)
vals.Set("limit", "50") vals.Set("limit", "50")
resp, err := http.Get(setting.Conf.Disqus.PostsList + "?" + vals.Encode()) resp, err := Get(setting.Conf.Disqus.PostsList + "?" + vals.Encode())
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -181,12 +183,8 @@ func PostCreate(pc *PostComment) (*postCreateResp, error) {
vals.Set("author_name", pc.AuthorName) vals.Set("author_name", pc.AuthorName)
// vals.Set("state", "approved") // vals.Set("state", "approved")
request, err := http.NewRequest("POST", setting.Conf.Disqus.PostCreate, strings.NewReader(vals.Encode())) header := http.Header{"Referer": {"https://disqus.com"}}
if err != nil { resp, err := PostWithHeader(setting.Conf.Disqus.PostCreate, vals, header)
return nil, err
}
request.Header.Set("Referer", "https://disqus.com")
resp, err := http.DefaultClient.Do(request)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -225,12 +223,8 @@ func PostApprove(post string) error {
vals.Set("access_token", setting.Conf.Disqus.AccessToken) vals.Set("access_token", setting.Conf.Disqus.AccessToken)
vals.Set("post", post) vals.Set("post", post)
request, err := http.NewRequest("POST", setting.Conf.Disqus.PostApprove, strings.NewReader(vals.Encode())) header := http.Header{"Referer": {"https://disqus.com"}}
if err != nil { resp, err := PostWithHeader(setting.Conf.Disqus.PostApprove, vals, header)
return err
}
request.Header.Set("Referer", "https://disqus.com")
resp, err := http.DefaultClient.Do(request)
if err != nil { if err != nil {
return err return err
} }
@@ -276,7 +270,7 @@ func ThreadCreate(artc *Article) error {
urlPath := fmt.Sprintf("https://%s/post/%s.html", setting.Conf.Mode.Domain, artc.Slug) urlPath := fmt.Sprintf("https://%s/post/%s.html", setting.Conf.Mode.Domain, artc.Slug)
vals.Set("url", urlPath) vals.Set("url", urlPath)
resp, err := http.PostForm(setting.Conf.Disqus.ThreadCreate, vals) resp, err := PostForm(setting.Conf.Disqus.ThreadCreate, vals)
if err != nil { if err != nil {
return err return err
} }
@@ -299,3 +293,88 @@ func ThreadCreate(artc *Article) error {
artc.Thread = result.Response.Id artc.Thread = result.Response.Id
return nil return nil
} }
///////////////////////////// HTTP 请求 /////////////////////////////
var httpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
func newRequest(method, rawurl string, vals url.Values) (*http.Request, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
host := u.Host
// 获取主机IP
ips, err := net.LookupHost(u.Host)
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, errors.New("not found ip: " + u.Host)
}
// 设置ServerName
httpClient.Transport.(*http.Transport).TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
u.Host = ips[0]
// 创建HTTP Request
var req *http.Request
if vals != nil {
req, err = http.NewRequest(method, u.String(), strings.NewReader(vals.Encode()))
} else {
req, err = http.NewRequest(method, u.String(), nil)
}
if err != nil {
return nil, err
}
// 改变Host
req.Host = host
return req, nil
}
// Get HTTP Get请求
func Get(rawurl string) (*http.Response, error) {
req, err := newRequest(http.MethodGet, rawurl, nil)
if err != nil {
return nil, err
}
// 发起请求
return httpClient.Do(req)
}
// PostForm HTTP Post请求
func PostForm(rawurl string, vals url.Values) (*http.Response, error) {
req, err := newRequest(http.MethodPost, rawurl, vals)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// 发起请求
return httpClient.Do(req)
}
// PostWithHeader HTTP Post请求,自定义Header
func PostWithHeader(rawurl string, vals url.Values, header http.Header) (*http.Response, error) {
req, err := newRequest(http.MethodPost, rawurl, vals)
if err != nil {
return nil, err
}
// set header
req.Header = header
// 发起请求
return httpClient.Do(req)
}
+1 -2
View File
@@ -87,13 +87,12 @@ $ docker run -d --name eisearch \
博主是一个有强迫症的人,一些文件的路径我使用了固定的路径,请大家见谅。假如你的 cdn 域名为 `st.example.com`,你需要确定这些文件已经在你的 cdn 中,它们路径分别是: 博主是一个有强迫症的人,一些文件的路径我使用了固定的路径,请大家见谅。假如你的 cdn 域名为 `st.example.com`,你需要确定这些文件已经在你的 cdn 中,它们路径分别是:
| 文件 | 地址 | 描述 | | 文件 | 地址 | 描述 |
| ------------------ | ---------------------------------------- | ---------------------------------------- | | ------------------ | -------------------------------------------- | ------------------------------------------------------------ |
| favicon.ico | st.example.com/static/img/favicon.ico | cdn 中的文件名为 `static/img/favicon.ico`。你也可以复制 favicon.ico 到 static 文件夹下,通过 example.com/favicon.ico 也是能够访问到。docker 用户可能需要重新打包镜像。 | | favicon.ico | st.example.com/static/img/favicon.ico | cdn 中的文件名为 `static/img/favicon.ico`。你也可以复制 favicon.ico 到 static 文件夹下,通过 example.com/favicon.ico 也是能够访问到。docker 用户可能需要重新打包镜像。 |
| bg04.jpg | st.example.com/static/img/bg04.jpg | 首页左侧的大背景图,需要更名请到 views/st_blog.css 修改。 | | bg04.jpg | st.example.com/static/img/bg04.jpg | 首页左侧的大背景图,需要更名请到 views/st_blog.css 修改。 |
| avatar.png | st.example.com/static/img/avatar.png | 头像 | | avatar.png | st.example.com/static/img/avatar.png | 头像 |
| blank.gif | st.example.com/static/img/blank.gif | 空白图片,[下载](https://st.deepzz.com/static/img/blank.gif) | | blank.gif | st.example.com/static/img/blank.gif | 空白图片,[下载](https://st.deepzz.com/static/img/blank.gif) |
| default_avatar.png | st.example.com/static/img/default_avatar.png | disqus 默认图片,[下载](https://st.deepzz.com/static/img/default_avatar.png) | | default_avatar.png | st.example.com/static/img/default_avatar.png | disqus 默认图片,[下载](https://st.deepzz.com/static/img/default_avatar.png) |
| disqus.js | st.example.com/static/js/disqus_xxx.js | disqus 文件,你可以通过 https://short_name.disqus.com/embed.js 下载你的专属文件,并上传到七牛。更新配置文件 app.yml。 |
> 注意,cdn 提到的文件下载,请复制链接进行下载,因为博主使用了防盗链功能,还有: > 注意,cdn 提到的文件下载,请复制链接进行下载,因为博主使用了防盗链功能,还有:
 1、每次修改 app.yml 文件(如:更换 cdn 域名或更新头像),如果你不知道是否应该提高 staticversion 一个版本,那么最好提高一个 +1。  1、每次修改 app.yml 文件(如:更换 cdn 域名或更新头像),如果你不知道是否应该提高 staticversion 一个版本,那么最好提高一个 +1。
-1
View File
@@ -43,7 +43,6 @@ type Config struct {
PostCreate string PostCreate string
PostApprove string PostApprove string
ThreadCreate string ThreadCreate string
Embed string
Interval int Interval int
} }
Google struct { // 谷歌统计 Google struct { // 谷歌统计
+1 -1
View File
@@ -1,3 +1,3 @@
{{define "blog_js"}} {{define "blog_js"}}
var stringProto=String.prototype;stringProto.stripTags=function(){return this.replace(/<[^>]*>/gi,"")},stringProto.decode4Html=function(){var t=document.createElement("div");return t.innerHTML=this.stripTags(),t.childNodes[0]?t.childNodes[0].nodeValue||"":""},stringProto.queryUrl=function(t){var a=this.replace(/^[^?=]*\?/gi,"").split("#")[0],e={};return a.replace(/(^|&)([^&=]+)=([^&]*)/g,function(t,a,n,i){try{n=decodeURIComponent(n)}catch(o){}try{i=decodeURIComponent(i)}catch(o){}n in e?e[n] instanceof Array?e[n].push(i):e[n]=[e[n],i]:e[n]=/\[\]$/.test(n)?[i]:i}),t?e[t]:e},function(t){t.disqus_shortname="{{.Disqus.ShortName}}",$.each(["CURRENT_PAGE","CDN_DOMAIN"],function(a,e){t[e]="";var n=$("#"+e);n&&(t[e]=n.val())})}(this),function(t){function a(a){var e,n,i={selector:null,height:200};i=$.extend(i,a),e=i.height,n=function(){var a=$(t).scrollTop(),n=$(t).height()+a;$(i.selector).find("img[data-src]").each(function(){var t=$(this);setTimeout(function(){var i,o=t.offset(),s=t.height();o.top>n+e||o.top+s<a-e||(i=t.data("src"),i&&(t.on("load",function(){t.addClass("loaded")}),t.attr("src",i),t.removeAttr("data-src")))},0)})},$(t).on("resize",n),$(t).on("scroll",n),n()}t.lazyLoad=a}(this),function(t){$(function(){$(".entry-content pre").each(function(t){var a,e,n,i=$(this),o=i.find("code");if(o.length&&o.prop("className")&&(o.hasClass("language-html")&&(a="__HTML_CODE_"+t,o.prop("id",a),e=$('<input data-id="'+a+'" type="button" class="runcode" value="在新窗口运行以上代码" />'),e.insertAfter(i)),o.html().split("\n").length>3&&o.prop("className").indexOf("language")>-1)){switch(n=o.prop("className").replace("language-","").toUpperCase()){case"XML":n="HTML";break;case"SHELL":n="BASH"}$('<b class="name">'+n+"</a>").insertBefore(o)}}),$(".entry-content input.runcode").each(function(){var a=$(this);a.click(function(a){var e,n,i;a.preventDefault(),e=$("#"+$(this).data("id")).html().stripTags().decode4Html(),n=t.open("","_preview",""),i=n.document,i.open(),i.write(e),i.close()})}),$(".entry-content > pre code").each(function(i,block){hljs.highlightBlock(block)})})}(this),function(){$(function(){$(".entry-content img[data-replace]").each(function(){var t=$(this);t.click(function(){var a,e,n,i,o=1000*(t.data("dur")||20);t.css("cursor")&&(a="/static/img/blank.gif",e=t.prop("src"),n=t.data("replace"),t.prop("src",a),t.css("cursor",""),i=new Image,i.onload=function(){t.prop("src",n),setTimeout(function(){t.prop("src",e),t.css("cursor","pointer")},o)},i.src=n)}),t.css("cursor","pointer")})})}(this),function(t){var a=function(){var e=[],n="comment_type",i=function(){if(!t.atob){return 1}try{t.postMessage("ping","*")}catch(a){return 2}return 0};return{addService:function(t){e.push(t)},clear:function(){localStorage.removeItem(n)},init:function(t){var o,r,s,c;return e.length?t.length?(o=t.data("url")||location.href,r=t.data("identifier"),o&&r?i()?void t.html("很抱歉,本站评论功能只支持这些浏览器:Chrome、Firefox、Safari、Opera、Edge、IE11+。"):(s=function(i){var c,l=e[i];l&&(c=$("<div>").prop("id",l.id),t.append(c),l.init(c,o,r),l.check(function(t){t?(c.hide(),s(++i)):(l.load(),localStorage[n]=i,a.currentServer=l)},c,o,r))},c=0,localStorage.comment_type&&(c=parseInt(localStorage[n],10)||0),c=Math.min(e.length-1,c),c=Math.max(c,0),void s(c)):void alert("没有找到评论所需标记!")):void alert("没有找到评论容器!"):void alert("没有找到可用的服务!")}}}();t.TotalThread=a}(this),function(t){var a=function(){var a=!1;return{id:"disqus_thread",check:function(a){var e,n,i=["https://c.disquscdn.com/favicon.ico","https://disqus.com/favicon.ico"],o=0,r=0,s=function(){o==i.length&&a(r==o?0:1)};for(t.__disqus_img=[],e=function(a){var e=new Image,n=setTimeout(function(){e.onerror=e.onload=null,o++,s()},2500);e.onerror=function(){clearTimeout(n),o++,s()},e.onload=function(){clearTimeout(n),o++,r++,s()},e.src=i[a]+"?"+ +new Date,t.__disqus_img[a]=e},n=0;n<i.length;n++){e(n)}},load:function(){if(!a){a=!0;var e=this;t.disqus_config=function(){this.page.url=e.url,this.page.identifier=e.identifier},$.ajax({url:t.CDN_DOMAIN+"/static/js/{{.Disqus.Embed}}",dataType:"script",cache:!0})}},init:function(t,a,e){t.html("评论完整模式加载中...<br /><br />注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。"),this.elThread=t,this.url=a,this.identifier=e}}}();t.TotalThread.addService(a)}(this),function(t){var a=function(){var e=!1,n=function(e,n){var i,o,r=!1,s="",c=function(a){var e='<li class="post '+(a.isDeleted?"minimized":"")+'" id="post-'+a.id+'"><div class="post-content clearfix"><div class="indicator"></div><div class="avatar"><div class="user">'+(a.url?'<a href="'+a.url+'"><img data-src="'+a.avatar+'" /></a>':'<img data-src="'+t.CDN_DOMAIN+'/static/img/default_avatar.png" />')+'</div></div><div class="post-body"><header class="post-header"><span class="post-byline"><span class="author publisher-anchor-color">'+(a.url?'<a href="'+a.urLine truncated var stringProto=String.prototype;stringProto.stripTags=function(){return this.replace(/<[^>]*>/gi,"")},stringProto.decode4Html=function(){var t=document.createElement("div");return t.innerHTML=this.stripTags(),t.childNodes[0]?t.childNodes[0].nodeValue||"":""},stringProto.queryUrl=function(t){var a=this.replace(/^[^?=]*\?/gi,"").split("#")[0],e={};return a.replace(/(^|&)([^&=]+)=([^&]*)/g,function(t,a,n,i){try{n=decodeURIComponent(n)}catch(o){}try{i=decodeURIComponent(i)}catch(o){}n in e?e[n] instanceof Array?e[n].push(i):e[n]=[e[n],i]:e[n]=/\[\]$/.test(n)?[i]:i}),t?e[t]:e},function(t){t.disqus_shortname="{{.Disqus.ShortName}}",$.each(["CURRENT_PAGE","CDN_DOMAIN"],function(a,e){t[e]="";var n=$("#"+e);n&&(t[e]=n.val())})}(this),function(t){function a(a){var e,n,i={selector:null,height:200};i=$.extend(i,a),e=i.height,n=function(){var a=$(t).scrollTop(),n=$(t).height()+a;$(i.selector).find("img[data-src]").each(function(){var t=$(this);setTimeout(function(){var i,o=t.offset(),s=t.height();o.top>n+e||o.top+s<a-e||(i=t.data("src"),i&&(t.on("load",function(){t.addClass("loaded")}),t.attr("src",i),t.removeAttr("data-src")))},0)})},$(t).on("resize",n),$(t).on("scroll",n),n()}t.lazyLoad=a}(this),function(t){$(function(){$(".entry-content pre").each(function(t){var a,e,n,i=$(this),o=i.find("code");if(o.length&&o.prop("className")&&(o.hasClass("language-html")&&(a="__HTML_CODE_"+t,o.prop("id",a),e=$('<input data-id="'+a+'" type="button" class="runcode" value="在新窗口运行以上代码" />'),e.insertAfter(i)),o.html().split("\n").length>3&&o.prop("className").indexOf("language")>-1)){switch(n=o.prop("className").replace("language-","").toUpperCase()){case"XML":n="HTML";break;case"SHELL":n="BASH"}$('<b class="name">'+n+"</a>").insertBefore(o)}}),$(".entry-content input.runcode").each(function(){var a=$(this);a.click(function(a){var e,n,i;a.preventDefault(),e=$("#"+$(this).data("id")).html().stripTags().decode4Html(),n=t.open("","_preview",""),i=n.document,i.open(),i.write(e),i.close()})}),$(".entry-content > pre code").each(function(i,block){hljs.highlightBlock(block)})})}(this),function(){$(function(){$(".entry-content img[data-replace]").each(function(){var t=$(this);t.click(function(){var a,e,n,i,o=1000*(t.data("dur")||20);t.css("cursor")&&(a="/static/img/blank.gif",e=t.prop("src"),n=t.data("replace"),t.prop("src",a),t.css("cursor",""),i=new Image,i.onload=function(){t.prop("src",n),setTimeout(function(){t.prop("src",e),t.css("cursor","pointer")},o)},i.src=n)}),t.css("cursor","pointer")})})}(this),function(t){var a=function(){var e=[],n="comment_type",i=function(){if(!t.atob){return 1}try{t.postMessage("ping","*")}catch(a){return 2}return 0};return{addService:function(t){e.push(t)},clear:function(){localStorage.removeItem(n)},init:function(t){var o,r,s,c;return e.length?t.length?(o=t.data("url")||location.href,r=t.data("identifier"),o&&r?i()?void t.html("很抱歉,本站评论功能只支持这些浏览器:Chrome、Firefox、Safari、Opera、Edge、IE11+。"):(s=function(i){var c,l=e[i];l&&(c=$("<div>").prop("id",l.id),t.append(c),l.init(c,o,r),l.check(function(t){t?(c.hide(),s(++i)):(l.load(),localStorage[n]=i,a.currentServer=l)},c,o,r))},c=0,localStorage.comment_type&&(c=parseInt(localStorage[n],10)||0),c=Math.min(e.length-1,c),c=Math.max(c,0),void s(c)):void alert("没有找到评论所需标记!")):void alert("没有找到评论容器!"):void alert("没有找到可用的服务!")}}}();t.TotalThread=a}(this),function(t){var a=function(){var a=!1;return{id:"disqus_thread",check:function(a){var e,n,i=["https://c.disquscdn.com/favicon.ico","https://disqus.com/favicon.ico"],o=0,r=0,s=function(){o==i.length&&a(r==o?0:1)};for(t.__disqus_img=[],e=function(a){var e=new Image,n=setTimeout(function(){e.onerror=e.onload=null,o++,s()},2500);e.onerror=function(){clearTimeout(n),o++,s()},e.onload=function(){clearTimeout(n),o++,r++,s()},e.src=i[a]+"?"+ +new Date,t.__disqus_img[a]=e},n=0;n<i.length;n++){e(n)}},load:function(){if(!a){a=!0;var e=this;t.disqus_config=function(){this.page.url=e.url,this.page.identifier=e.identifier},$.ajax({url:"//{{.Disqus.ShortName}}.disqus.com/embed.js",dataType:"script",cache:!0})}},init:function(t,a,e){t.html("评论完整模式加载中...<br /><br />注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。"),this.elThread=t,this.url=a,this.identifier=e}}}();t.TotalThread.addService(a)}(this),function(t){var a=function(){var e=!1,n=function(e,n){var i,o,r=!1,s="",c=function(a){var e='<li class="post '+(a.isDeleted?"minimized":"")+'" id="post-'+a.id+'"><div class="post-content clearfix"><div class="indicator"></div><div class="avatar"><div class="user">'+(a.url?'<a href="'+a.url+'"><img data-src="'+a.avatar+'" /></a>':'<img data-src="'+t.CDN_DOMAIN+'/static/img/default_avatar.png" />')+'</div></div><div class="post-body"><header class="post-header"><span class="post-byline"><span class="author publisher-anchor-color">'+(a.url?'<a href="'+a.Line truncated
{{end}} {{end}}