完善 disqus 评论

This commit is contained in:
deepzz0
2017-06-26 23:51:13 +08:00
parent 66811830b0
commit 2825bbfeae
6 changed files with 127 additions and 54 deletions

View File

@@ -37,12 +37,15 @@ general:
disqus: disqus:
shortname: deepzz shortname: deepzz
publickey: wdSgxRm9rdGAlLKFcFdToBe3GT4SibmV7Y8EjJQ0r4GWXeKtxpopMAeIeoI2dTEg publickey: wdSgxRm9rdGAlLKFcFdToBe3GT4SibmV7Y8EjJQ0r4GWXeKtxpopMAeIeoI2dTEg
accesstoken: 50023908f39f4607957e909b495326af
postscount: https://disqus.com/api/3.0/threads/set.json postscount: https://disqus.com/api/3.0/threads/set.json
postslist: https://disqus.com/api/3.0/threads/listPosts.json postslist: https://disqus.com/api/3.0/threads/listPosts.json
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
interval: 5 interval: 5
# 谷歌统计 # 谷歌统计
google: google:
url: https://www.google-analytics.com/collect
tid: UA-77251712-1 tid: UA-77251712-1
v: "1" v: "1"
t: pageview t: pageview

132
disqus.go
View File

@@ -4,16 +4,19 @@ package main
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/deepzz0/logd"
"github.com/eiblog/eiblog/setting" "github.com/eiblog/eiblog/setting"
"github.com/eiblog/utils/logd"
) )
var ErrDisqusConfig = errors.New("disqus config incorrect")
type result struct { type result struct {
Code int Code int
Response []struct { Response []struct {
@@ -23,12 +26,21 @@ type result struct {
} }
} }
func PostsCount() { // 定时获取所有文章评论数量
func PostsCount() error {
if setting.Conf.Disqus.PostsCount == "" || if setting.Conf.Disqus.PostsCount == "" ||
setting.Conf.Disqus.PublicKey == "" || setting.Conf.Disqus.PublicKey == "" ||
setting.Conf.Disqus.ShortName == "" { setting.Conf.Disqus.ShortName == "" {
return return ErrDisqusConfig
} }
time.AfterFunc(time.Duration(setting.Conf.Disqus.Interval)*time.Hour, func() {
err := PostsCount()
if err != nil {
logd.Error(err)
}
})
baseUrl := setting.Conf.Disqus.PostsCount + baseUrl := setting.Conf.Disqus.PostsCount +
"?api_key=" + setting.Conf.Disqus.PublicKey + "?api_key=" + setting.Conf.Disqus.PublicKey +
"&forum=" + setting.Conf.Disqus.ShortName + "&" "&forum=" + setting.Conf.Disqus.ShortName + "&"
@@ -44,24 +56,22 @@ func PostsCount() {
url := baseUrl + strings.Join(threads, "&") url := baseUrl + strings.Join(threads, "&")
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
logd.Error(err) return err
break
} }
defer resp.Body.Close() defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body) b, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
logd.Error(err) return err
break
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
logd.Error(string(b)) return errors.New(string(b))
break
} }
rst := result{} rst := result{}
err = json.Unmarshal(b, &rst) err = json.Unmarshal(b, &rst)
if err != nil { if err != nil {
logd.Error(err) return err
break
} }
for _, v := range rst.Response { for _, v := range rst.Response {
i := strings.Index(v.Identifiers[0], "-") i := strings.Index(v.Identifiers[0], "-")
@@ -72,7 +82,8 @@ func PostsCount() {
} }
} }
} }
time.AfterFunc(time.Duration(setting.Conf.Disqus.Interval)*time.Hour, PostsCount)
return nil
} }
type postsList struct { type postsList struct {
@@ -97,35 +108,34 @@ type postsList struct {
} }
} }
func PostsList(slug, cursor string) *postsList { // 获取文章评论列表
if setting.Conf.Disqus.PostsList == "" || setting.Conf.Disqus.PublicKey == "" || setting.Conf.Disqus.ShortName == "" { func PostsList(slug, cursor string) (*postsList, error) {
return nil if setting.Conf.Disqus.PostsList == "" ||
setting.Conf.Disqus.PublicKey == "" ||
setting.Conf.Disqus.ShortName == "" {
return nil, ErrDisqusConfig
} }
url := setting.Conf.Disqus.PostsList + "?limit=50&api_key=" + url := setting.Conf.Disqus.PostsList + "?limit=50&api_key=" +
setting.Conf.Disqus.PublicKey + "&forum=" + setting.Conf.Disqus.ShortName + setting.Conf.Disqus.PublicKey + "&forum=" + setting.Conf.Disqus.ShortName +
"&cursor=" + cursor + "&thread:ident=post-" + slug "&cursor=" + cursor + "&thread:ident=post-" + slug
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
logd.Error(err) return nil, err
return nil
} }
defer resp.Body.Close() defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body) b, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
logd.Error(err) return nil, err
return nil
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
logd.Error(string(b)) return nil, errors.New(string(b))
return nil
} }
pl := &postsList{} pl := &postsList{}
err = json.Unmarshal(b, pl) err = json.Unmarshal(b, pl)
if err != nil { if err != nil {
logd.Error(err) return nil, err
return nil
} }
return pl return pl, nil
} }
type PostCreate struct { type PostCreate struct {
@@ -146,9 +156,12 @@ type PostResponse struct {
} `json:"response"` } `json:"response"`
} }
func PostComment(pc *PostCreate) string { // 评论文章
if setting.Conf.Disqus.PostsList == "" || setting.Conf.Disqus.PublicKey == "" || setting.Conf.Disqus.ShortName == "" { func PostComment(pc *PostCreate) (string, error) {
return "" if setting.Conf.Disqus.PostsList == "" ||
setting.Conf.Disqus.PublicKey == "" ||
setting.Conf.Disqus.ShortName == "" {
return "", ErrDisqusConfig
} }
url := setting.Conf.Disqus.PostCreate + url := setting.Conf.Disqus.PostCreate +
"?api_key=E8Uh5l5fHZ6gD8U3KycjAIAk46f68Zw7C6eW8WSjZvCLXebZ7p0r1yrYDrLilk2F" + "?api_key=E8Uh5l5fHZ6gD8U3KycjAIAk46f68Zw7C6eW8WSjZvCLXebZ7p0r1yrYDrLilk2F" +
@@ -158,31 +171,72 @@ func PostComment(pc *PostCreate) string {
request, err := http.NewRequest("POST", url, nil) request, err := http.NewRequest("POST", url, nil)
if err != nil { if err != nil {
logd.Error(err) return "", err
return ""
} }
request.Header.Set("Referer", "https://disqus.com") request.Header.Set("Referer", "https://disqus.com")
resp, err := http.DefaultClient.Do(request) resp, err := http.DefaultClient.Do(request)
if err != nil { if err != nil {
logd.Error(err) return "", err
return ""
} }
defer resp.Body.Close() defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body) b, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
logd.Error(err) return "", err
return ""
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
logd.Error(string(b)) return "", errors.New(string(b))
return ""
} }
pr := &PostResponse{} pr := &PostResponse{}
err = json.Unmarshal(b, pr) err = json.Unmarshal(b, pr)
if err != nil { if err != nil {
logd.Error(err) return "", err
return ""
} }
logd.Print(pr.Response.Id) return pr.Response.Id, nil
return pr.Response.Id }
type ApprovedResponse struct {
Code int `json:"code"`
Response []struct {
Id string `json:"id"`
} `json:"response"`
}
// 批准评论通过
func PostApprove(post string) error {
if setting.Conf.Disqus.PostsList == "" ||
setting.Conf.Disqus.PublicKey == "" ||
setting.Conf.Disqus.ShortName == "" {
return ErrDisqusConfig
}
url := setting.Conf.Disqus.PostApprove +
"?api_key=" + setting.Conf.Disqus.PublicKey +
"&access_token=" + setting.Conf.Disqus.AccessToken +
"&post=" + post
request, err := http.NewRequest("POST", url, nil)
if err != nil {
return err
}
request.Header.Set("Referer", "https://disqus.com")
resp, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.New(string(b))
}
ar := &ApprovedResponse{}
err = json.Unmarshal(b, ar)
if err != nil {
return err
}
return nil
} }

View File

@@ -23,3 +23,7 @@ func TestPostComment(t *testing.T) {
} }
t.Log("post success") t.Log("post success")
} }
func TestApprovePost(t *testing.T) {
ApprovePost()
}

View File

@@ -245,7 +245,7 @@ func HandleBeacon(c *gin.Context) {
vals.Set("dl", c.Request.Referer()) vals.Set("dl", c.Request.Referer())
vals.Set("uip", c.ClientIP()) vals.Set("uip", c.ClientIP())
go func() { go func() {
req, err := http.NewRequest("POST", "https://www.google-analytics.com/collect", strings.NewReader(vals.Encode())) req, err := http.NewRequest("POST", setting.Conf.Google.URL, strings.NewReader(vals.Encode()))
if err != nil { if err != nil {
logd.Error(err) logd.Error(err)
return return
@@ -301,8 +301,12 @@ func HandleDisqus(c *gin.Context) {
if artc := Ei.MapArticles[slug]; artc != nil { if artc := Ei.MapArticles[slug]; artc != nil {
dcs.Data.Thread = artc.Thread dcs.Data.Thread = artc.Thread
} }
postsList := PostsList(slug, cursor) postsList, err := PostsList(slug, cursor)
if postsList != nil { if err != nil {
logd.Error(err)
dcs.ErrNo = FAIL
dcs.ErrMsg = "系统错误"
} else {
dcs.ErrNo = postsList.Code dcs.ErrNo = postsList.Code
if postsList.Cursor.HasNext { if postsList.Cursor.HasNext {
dcs.Data.Next = postsList.Cursor.Next dcs.Data.Next = postsList.Cursor.Next
@@ -324,9 +328,6 @@ func HandleDisqus(c *gin.Context) {
Message: v.Message, Message: v.Message,
} }
} }
} else {
dcs.ErrNo = FAIL
dcs.ErrMsg = "系统错误"
} }
c.JSON(http.StatusOK, dcs) c.JSON(http.StatusOK, dcs)
} }
@@ -355,8 +356,16 @@ func HandleDisqusCreate(c *gin.Context) {
IpAddress: c.ClientIP(), IpAddress: c.ClientIP(),
} }
id := PostComment(pc) id, err := PostComment(pc)
if id == "" { if err != nil {
logd.Error(err)
rep["errno"] = FAIL
rep["errmsg"] = "系统错误"
return
}
err = PostApprove(id)
if err != nil {
logd.Error(err)
rep["errno"] = FAIL rep["errno"] = FAIL
rep["errmsg"] = "系统错误" rep["errmsg"] = "系统错误"
return return

View File

@@ -35,14 +35,17 @@ type Config struct {
Clean int // 清理回收箱频率 Clean int // 清理回收箱频率
} }
Disqus struct { // 获取文章数量相关 Disqus struct { // 获取文章数量相关
ShortName string ShortName string
PublicKey string PublicKey string
PostsCount string AccessToken string
PostsList string PostsCount string
PostCreate string PostsList string
Interval int PostCreate string
PostApprove string
Interval int
} }
Google struct { // 谷歌统计 Google struct { // 谷歌统计
URL string
Tid string Tid string
V string V string
T string T string

View File

@@ -1 +1 @@
<!Doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta content="width=device-width,minimum-scale=1.0" name=viewport><meta name="format-detection" content="telephone=no"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name=referrer content=always><meta name=robots content="noindex, nofollow, noarchive"><title>{{.Title}}</title><style type="text/css">*{margin:0;padding:0}html,body{height:100%}body{background:#fff;color:#2a2e2e;font-size:15px;font-family:"Helvetica Neue",arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}::selection,::-moz-selection,::-webkit-selection{background-color:#2479CC;color:#eee}h3{font-size:1.3em;line-height:1.5;margin:15px 30px;text-align:center}a{color:#2479CC;text-decoration:none}.card{margin:15px 25px;text-align:left}.submit input,.submit textarea{-webkit-appearance:none;border:1px solid #bbb;border-radius:1px;font-size:15px;height:20px;line-height:20px;margin-left:10px;padding:6px 8px}.submit span{position:relative;top:8px}.submit li{display:-webkit-box;display:-ms-flexbox;display:flex;margin:15px 0}.submit textarea{height:130px}.submit .line{-webkit-box-flex:1;display:block;-ms-flex:1;flex:1}.submit .btn-submit{-webkit-appearance:none;background:#12b0e6;border:none;border-radius:0;box-shadow:inset 0 -5px 20px rgba(0,0,0,.1);color:#fff;cursor:pointer;display:block;font-size:14px;line-height:1;padding:0.625em .5em;width:100%}.submit li.tips{color:#999;font-size:14px}</style></head><body><header><h3>对「{{.ATitle}}」发表评论</h3></header><div class=bd><div class="card submit"><form onsubmit="return false" id="create-post"><ul><li><span>昵称:</span><input class=line name=author_name required placeholder="昵称会被公开显示"><li><span>邮箱:</span><input class=line name=author_email type=email required placeholder="邮箱不会公开显示"><li><span>内容:</span><textarea class="line" name="message" required placeholder="请不要发表无意义的评论内容"></textarea><li><input type=hidden name=thread value="{{.Thread}}"><input type=hidden name=parent value=""><input type=hidden name=identifier value="post-{{.Slug}}"><input type=hidden name=next value=""><button class="btn-submit" type=submit>立即发表</button><li class=tips>注:通过本表单提交的数据,会原样转发给 Disqus本站不做任何存储和记录。<li><a href="#close" onclick="window.close();void(0)">放弃评论</a></ul></form></div></div><footer></footer><script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js" ></script><script>!function(a){function e(){try{localStorage.author_name=$('[name="author_name"]').val(),localStorage.author_email=$('[name="author_email"]').val()}catch(a){}}function t(){$('[name="author_name"]').val(localStorage.author_name),$('[name="author_email"]').val(localStorage.author_email),["author_name","author_email","message"].some(function(a){var e=$('[name="'+a+'"]');return e.val()?void 0:e.focus()})}var o=!1;$("#create-post").on("submit",function(e){if(e.preventDefault(),!o){o=!0;var t=$(".tips");t.html("提交中..."),$.post("/disqus/create/",$("#create-post").serialize()).then(function(e){o=!1,e.errno?t.html("提交失败:"+e.errmsg):($(".btn-submit").prop("disabled",!0),t.html("提交成功!本窗口即将关闭。"),setTimeout(function(){try{a.opener.location.hash="comment-"+e.data.id,a.opener.TotalThread.currentServer.insertItem(e.data),a.close()}catch(t){a.close()}},1e3))})}}),t(),$('[name="author_name"], [name="author_email"]').on("change",e)}(this)</script></body></html> <!Doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta content="width=device-width,minimum-scale=1.0" name=viewport><meta name="format-detection" content="telephone=no"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name=referrer content=always><meta name=robots content="noindex, nofollow, noarchive"><title>{{.Title}}</title><style type="text/css">*{margin:0;padding:0}html,body{height:100%}body{background:#fff;color:#2a2e2e;font-size:15px;font-family:"Helvetica Neue",arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}::selection,::-moz-selection,::-webkit-selection{background-color:#2479CC;color:#eee}h3{font-size:1.3em;line-height:1.5;margin:15px 30px;text-align:center}a{color:#2479CC;text-decoration:none}.card{margin:15px 25px;text-align:left}.submit input,.submit textarea{-webkit-appearance:none;border:1px solid #bbb;border-radius:1px;font-size:15px;height:20px;line-height:20px;margin-left:10px;padding:6px 8px}.submit span{position:relative;top:8px}.submit li{display:-webkit-box;display:-ms-flexbox;display:flex;margin:15px 0}.submit textarea{height:130px}.submit .line{-webkit-box-flex:1;display:block;-ms-flex:1;flex:1}.submit .btn-submit{-webkit-appearance:none;background:#12b0e6;border:none;border-radius:0;box-shadow:inset 0 -5px 20px rgba(0,0,0,.1);color:#fff;cursor:pointer;display:block;font-size:14px;line-height:1;padding:0.625em .5em;width:100%}.submit li.tips{color:#999;font-size:14px}</style></head><body><header><h3>对「{{.ATitle}}」发表评论</h3></header><div class=bd><div class="card submit"><form onsubmit="return false" id="create-post"><ul><li><span>昵称:</span><input class=line name=author_name required placeholder="昵称会被公开显示"><li><span>邮箱:</span><input class=line name=author_email type=email required placeholder="邮箱不会公开显示"><li><span>内容:</span><textarea class="line" name="message" required placeholder="请不要发表无意义的评论内容"></textarea><li><input type=hidden name=thread value="{{.Thread}}"><input type=hidden name=parent value=""><input type=hidden name=identifier value="post-{{.Slug}}"><input type=hidden name=next value=""><button class="btn-submit" type=submit>立即发表</button><li class=tips>注:通过本表单提交的数据,会原样转发给 Disqus本站不做任何存储和记录。<li><a href="#close" onclick="window.close();void(0)">放弃评论</a></ul></form></div></div><footer></footer><script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js" ></script><script>!function(a){function e(){try{localStorage.author_name=$('[name="author_name"]').val(),localStorage.author_email=$('[name="author_email"]').val()}catch(a){}}function t(){$('[name="author_name"]').val(localStorage.author_name),$('[name="author_email"]').val(localStorage.author_email),["author_name","author_email","message"].some(function(a){var e=$('[name="'+a+'"]');return e.val()?void 0:e.focus()})}var o=!1;$("#create-post").on("submit",function(e){if(e.preventDefault(),!o){o=!0;var t=$(".tips");t.html("提交中..."),$.post("/disqus/create",$("#create-post").serialize()).then(function(e){o=!1,e.errno?t.html("提交失败:"+e.errmsg):($(".btn-submit").prop("disabled",!0),t.html("提交成功!本窗口即将关闭。"),setTimeout(function(){try{a.opener.location.hash="comment-"+e.data.id,a.opener.TotalThread.currentServer.insertItem(e.data),a.close()}catch(t){a.close()}},1e3))})}}),t(),$('[name="author_name"], [name="author_email"]').on("change",e)}(this)</script></body></html>