优化代码

master
taoshihan 2 years ago
parent 83858146ab
commit 5e84e65fdd

@ -24,7 +24,7 @@ func install() {
log.Println("请先删除./install.lock") log.Println("请先删除./install.lock")
os.Exit(1) os.Exit(1)
} }
sqlFile := common.Dir + "go-fly.sql" sqlFile := "import.sql"
isExit, _ := tools.IsFileExist(common.MysqlConf) isExit, _ := tools.IsFileExist(common.MysqlConf)
dataExit, _ := tools.IsFileExist(sqlFile) dataExit, _ := tools.IsFileExist(sqlFile)
if !isExit || !dataExit { if !isExit || !dataExit {
@ -32,8 +32,9 @@ func install() {
os.Exit(1) os.Exit(1)
} }
sqls, _ := ioutil.ReadFile(sqlFile) sqls, _ := ioutil.ReadFile(sqlFile)
sqlArr := strings.Split(string(sqls), "|") sqlArr := strings.Split(string(sqls), ";")
for _, sql := range sqlArr { for _, sql := range sqlArr {
sql = strings.TrimSpace(sql)
if sql == "" { if sql == "" {
continue continue
} }
@ -41,7 +42,7 @@ func install() {
if err == nil { if err == nil {
log.Println(sql, "\t success!") log.Println(sql, "\t success!")
} else { } else {
log.Println(sql, err, "\t failed!") log.Println(sql, err, "\t failed!", "数据库导入失败")
os.Exit(1) os.Exit(1)
} }
} }

@ -113,6 +113,7 @@ CREATE TABLE `config` (
INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(SMTP地址)', 'NoticeEmailSmtp', '')| INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(SMTP地址)', 'NoticeEmailSmtp', '')|
INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(邮箱)', 'NoticeEmailAddress', '')| INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(邮箱)', 'NoticeEmailAddress', '')|
INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(密码)', 'NoticeEmailPassword', '')| INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(密码)', 'NoticeEmailPassword', '')|
INSERT INTO `config` (`id`, `conf_name`, `conf_key`, `conf_value`) VALUES (NULL, '发送通知邮件(密码)', 'NoticeEmailPassword', '')|
DROP TABLE IF EXISTS `about`| DROP TABLE IF EXISTS `about`|
CREATE TABLE `about` ( CREATE TABLE `about` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,

@ -110,8 +110,6 @@ func SendMessageV2(c *gin.Context) {
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
ws.OneKefuMessage(kefuInfo.Name, str) ws.OneKefuMessage(kefuInfo.Name, str)
//ws.KefuMessage(vistorInfo.VisitorId, content, kefuInfo) //ws.KefuMessage(vistorInfo.VisitorId, content, kefuInfo)
go ws.SendServerJiang(vistorInfo.Name+"说", content, c.Request.Host)
go SendAppGetuiPush(kefuInfo.Name, vistorInfo.Name, content)
kefu, ok := ws.KefuList[kefuInfo.Name] kefu, ok := ws.KefuList[kefuInfo.Name]
if !ok || kefu == nil{ if !ok || kefu == nil{
go SendNoticeEmail(content+"|"+vistorInfo.Name, content) go SendNoticeEmail(content+"|"+vistorInfo.Name, content)

@ -1,80 +1,32 @@
package controller package controller
import ( import (
"fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/taoshihan1991/imaptool/models" "github.com/taoshihan1991/imaptool/models"
"github.com/taoshihan1991/imaptool/ws"
"time"
) )
func GetNotice(c *gin.Context) { func GetNotice(c *gin.Context) {
kefuId := c.Query("kefu_id") kefuId := c.Query("kefu_id")
welcomes := models.FindWelcomesByKeyword(kefuId, "welcome")
user := models.FindUser(kefuId) user := models.FindUser(kefuId)
result := make([]gin.H, 0) if user.ID==0{
for _, welcome := range welcomes { c.JSON(200, gin.H{
h := gin.H{ "code": 400,
"name": user.Nickname, "msg": "user not found",
"avator": user.Avator, })
"is_kefu": false, return
"content": welcome.Content,
"time": time.Now().Format("2006-01-02 15:04:05"),
}
result = append(result, h)
}
status := "online"
if _, ok := ws.KefuList[kefuId]; !ok {
status = "offline"
} }
welcomeMessage:=models.FindConfig("WelcomeMessage")
offlineMessage:=models.FindConfig("OfflineMessage")
allNotice:=models.FindConfig("AllNotice")
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result": gin.H{ "result": gin.H{
"welcome": result, "welcome":welcomeMessage,
"username": user.Nickname, "offline":offlineMessage,
"avatar": user.Avator, "avatar":user.Avator,
"status": status, "nickname":user.Nickname,
"allNotice":allNotice,
}, },
}) })
} }
func GetNotices(c *gin.Context) {
kefuId, _ := c.Get("kefu_name")
welcomes := models.FindWelcomesByUserId(kefuId)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result": welcomes,
})
}
func PostNotice(c *gin.Context) {
kefuId, _ := c.Get("kefu_name")
content := c.PostForm("content")
models.CreateWelcome(fmt.Sprintf("%s", kefuId), content)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result": "",
})
}
func PostNoticeSave(c *gin.Context) {
kefuId, _ := c.Get("kefu_name")
content := c.PostForm("content")
id := c.PostForm("id")
models.UpdateWelcome(fmt.Sprintf("%s", kefuId), id, content)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result": "",
})
}
func DelNotice(c *gin.Context) {
kefuId, _ := c.Get("kefu_name")
id := c.Query("id")
models.DeleteWelcome(kefuId, id)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result": "",
})
}

@ -9,6 +9,7 @@ require (
github.com/gin-contrib/pprof v1.3.0 github.com/gin-contrib/pprof v1.3.0
github.com/gin-contrib/sessions v0.0.3 github.com/gin-contrib/sessions v0.0.3
github.com/gin-gonic/gin v1.7.7 github.com/gin-gonic/gin v1.7.7
github.com/go-sql-driver/mysql v1.5.0
github.com/gobuffalo/packr/v2 v2.5.1 github.com/gobuffalo/packr/v2 v2.5.1
github.com/golang-jwt/jwt v3.2.2+incompatible github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/gorilla/websocket v1.4.2 github.com/gorilla/websocket v1.4.2
@ -19,6 +20,5 @@ require (
github.com/satori/go.uuid v1.2.0 github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.4.2 github.com/sirupsen/logrus v1.4.2
github.com/spf13/cobra v0.0.5 github.com/spf13/cobra v0.0.5
github.com/tidwall/gjson v1.14.1
github.com/zh-five/xdaemon v0.1.1 github.com/zh-five/xdaemon v0.1.1
) )

@ -146,12 +146,6 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/tidwall/gjson v1.14.1 h1:iymTbGkQBhveq21bEvAQ81I0LEBork8BFe1CUZXdyuo=
github.com/tidwall/gjson v1.14.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=

@ -69,10 +69,6 @@ func InitApiRouter(engine *gin.Engine) {
engine.POST("/about", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostAbout) engine.POST("/about", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostAbout)
engine.GET("/aboutpages", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetAbouts) engine.GET("/aboutpages", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetAbouts)
engine.GET("/notice",controller.GetNotice) engine.GET("/notice",controller.GetNotice)
engine.POST("/notice", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostNotice)
engine.DELETE("/notice", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.DelNotice)
engine.POST("/notice_save", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostNoticeSave)
engine.GET("/notices", middleware.JwtApiMiddleware, controller.GetNotices)
engine.POST("/ipblack", middleware.JwtApiMiddleware, middleware.Ipblack, controller.PostIpblack) engine.POST("/ipblack", middleware.JwtApiMiddleware, middleware.Ipblack, controller.PostIpblack)
engine.DELETE("/ipblack", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.DelIpblack) engine.DELETE("/ipblack", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.DelIpblack)
engine.GET("/ipblacks_all", middleware.JwtApiMiddleware, controller.GetIpblacks) engine.GET("/ipblacks_all", middleware.JwtApiMiddleware, controller.GetIpblacks)

@ -558,4 +558,10 @@ a{color: #07a9fe;text-decoration: none;}
} }
.chatBoxMe .chatRowAvator { .chatBoxMe .chatRowAvator {
margin-left: 10px; margin-left: 10px;
}
.allNotice{
font-size: 12px;
margin: 10px 0px;
line-height: 23px;
color: #666;
} }

@ -25,6 +25,7 @@ new Vue({
showIconBtns:false, showIconBtns:false,
showFaceIcon:false, showFaceIcon:false,
isIframe:false, isIframe:false,
kefuInfo:{},
}, },
methods: { methods: {
//初始化websocket //初始化websocket
@ -226,6 +227,8 @@ new Vue({
_this.setCache("visitor",res.result); _this.setCache("visitor",res.result);
//_this.getMesssagesByVisitorId(); //_this.getMesssagesByVisitorId();
_this.initConn(); _this.initConn();
//获取欢迎
_this.getNotice();
}); });
// }else{ // }else{
// this.visitor=obj; // this.visitor=obj;
@ -337,35 +340,20 @@ new Vue({
getNotice : function (){ getNotice : function (){
let _this=this; let _this=this;
$.get("/notice?kefu_id="+KEFU_ID,function(res) { $.get("/notice?kefu_id="+KEFU_ID,function(res) {
//debugger; var code=res.code;
_this.noticeName=res.result.username; if(code!=200) return;
_this.noticeAvatar=res.result.avatar; _this.kefuInfo=res.result;
if (res.result.welcome != null) { var welcome=res.result.welcome;
let msg = res.result.welcome; if(!welcome) return;
var len=msg.length; var msg={
var i=0; content:replaceContent(welcome),
if(len>0){ avator:res.result.avatar,
_this.timer=setInterval(function(){ name :res.result.nickname,
if(i>=len||typeof msg[i]=="undefined"||msg[i]==null){ time:new Date(),
clearInterval(_this.timer);
return;
}
let content = msg[i];
if(typeof content.content =="undefined"){
return;
}
content.content = replaceContent(content.content);
_this.msgList.push(content);
_this.scrollBottom();
if(i==0){
_this.alertSound();
}
i++;
},4000);
}
} }
_this.msgList.push(msg);
_this.scrollBottom();
_this.alertSound();
}); });
}, },
initCss:function(){ initCss:function(){
@ -638,8 +626,7 @@ new Vue({
//this.msgList=this.getHistory(); //this.msgList=this.getHistory();
//滚动底部 //滚动底部
//this.scrollBottom(); //this.scrollBottom();
//获取欢迎
this.getNotice();
this.getAutoReply(); this.getAutoReply();
} }
}) })

@ -23,10 +23,10 @@
<!--客服代码--> <!--客服代码-->
<div class="chatEntTitle" v-show="!isIframe"> <div class="chatEntTitle" v-show="!isIframe">
<el-badge type="success" is-dot class="item"> <el-badge type="success" is-dot class="item">
<el-avatar class="chatEntTitleLogo" :size="35" src="/static/images/1.jpg"></el-avatar> <el-avatar class="chatEntTitleLogo" :size="35" :src="kefuInfo.avatar"></el-avatar>
</el-badge> </el-badge>
<div> <div>
<div>智能在线客服系统</div> <div><{kefuInfo.nickname}></div>
</div> </div>
</div> </div>
<div class="chatEntBox"> <div class="chatEntBox">
@ -71,6 +71,7 @@
<div class="chatArticle"> <div class="chatArticle">
<h3 class="hotQuestionTitle"><img src="/static/images/fire.svg" class="fire">公告通知 <h3 class="hotQuestionTitle"><img src="/static/images/fire.svg" class="fire">公告通知
</h3> </h3>
<div class="allNotice" v-html><{kefuInfo.allNotice}></div>
</div> </div>

@ -10,7 +10,6 @@
</template> </template>
<el-menu-item-group> <el-menu-item-group>
<el-menu-item index="1-1" v-on:click="openUrl('/setting_statistics')">统计信息</el-menu-item> <el-menu-item index="1-1" v-on:click="openUrl('/setting_statistics')">统计信息</el-menu-item>
<el-menu-item index="1-2" v-on:click="openUrl('/setting_welcome')">自动欢迎</el-menu-item>
<el-menu-item index="1-3" v-on:click="openUrl('/setting_modifypass')">修改密码</el-menu-item> <el-menu-item index="1-3" v-on:click="openUrl('/setting_modifypass')">修改密码</el-menu-item>
<el-menu-item index="1-4" v-on:click="openUrl('/setting_avator')">修改头像</el-menu-item> <el-menu-item index="1-4" v-on:click="openUrl('/setting_avator')">修改头像</el-menu-item>
</el-menu-item-group> </el-menu-item-group>

@ -0,0 +1,56 @@
package tools
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
type ImportSqlTool struct {
SqlPath string
Username, Password, Server, Port, Database string
}
func (this *ImportSqlTool) ImportSql() error {
_, err := os.Stat(this.SqlPath)
if os.IsNotExist(err) {
log.Println("数据库SQL文件不存在:", err)
return err
}
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", this.Username, this.Password, this.Server, this.Port, this.Database)
db, err := gorm.Open("mysql", dsn)
if err != nil {
log.Println("数据库连接失败:", err)
//panic("数据库连接失败!")
return err
}
db.SingularTable(true)
db.LogMode(true)
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.DB().SetConnMaxLifetime(59 * time.Second)
sqls, _ := ioutil.ReadFile(this.SqlPath)
sqlArr := strings.Split(string(sqls), ";")
for _, sql := range sqlArr {
sql = strings.TrimSpace(sql)
if sql == "" {
continue
}
err := db.Exec(sql).Error
if err != nil {
log.Println("数据库导入失败:" + err.Error())
return err
} else {
log.Println(sql, "\t success!")
}
}
return nil
}

@ -0,0 +1,15 @@
package tools
import "testing"
func TestImportSql(t *testing.T) {
tool:=&ImportSqlTool{
SqlPath: "../import.sql",
Username: "go-fly",
Password: "go-fly",
Server: "127.0.0.1",
Port: "3306",
Database: "go-fly",
}
tool.ImportSql()
}

@ -171,12 +171,12 @@ func VisitorAutoReply(vistorInfo models.Visitor, kefuInfo models.User, content s
} }
if !ok || kefu == nil { if !ok || kefu == nil {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
welcome := models.FindWelcomeByUserIdKey(kefuInfo.Name, "offline") welcome := models.FindConfig("OfflineMessage")
if welcome.Content == "" || reply.Content != "" { if welcome == "" || reply.Content != "" {
return return
} }
VisitorMessage(vistorInfo.VisitorId, welcome.Content, kefuInfo) VisitorMessage(vistorInfo.VisitorId, welcome, kefuInfo)
models.CreateMessage(kefuInfo.Name, vistorInfo.VisitorId, welcome.Content, "kefu") models.CreateMessage(kefuInfo.Name, vistorInfo.VisitorId, welcome, "kefu")
} }
} }
func CleanVisitorExpire() { func CleanVisitorExpire() {

Loading…
Cancel
Save