格式化项目代码

pull/23/head
taoshihan1991 5 years ago
parent 2596e46821
commit 1581b69627

@ -18,18 +18,19 @@ var installCmd = &cobra.Command{
install() install()
}, },
} }
func install(){
sqlFile:=config.Dir+"go-fly.sql" func install() {
isExit,_:=tools.IsFileExist(config.MysqlConf) sqlFile := config.Dir + "go-fly.sql"
dataExit,_:=tools.IsFileExist(sqlFile) isExit, _ := tools.IsFileExist(config.MysqlConf)
if !isExit||!dataExit{ dataExit, _ := tools.IsFileExist(sqlFile)
if !isExit || !dataExit {
fmt.Println("config/mysql.json 数据库配置文件或者数据库文件go-fly.sql不存在") fmt.Println("config/mysql.json 数据库配置文件或者数据库文件go-fly.sql不存在")
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 {
if sql==""{ if sql == "" {
continue continue
} }
models.Execute(sql) models.Execute(sql)

@ -1,21 +1,24 @@
package cmd package cmd
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"os" "os"
) )
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "go-fly", Use: "go-fly",
Short: "go-fly", Short: "go-fly",
Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`, Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`,
Args:args, Args: args,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
}, },
} }
func args(cmd *cobra.Command, args []string) error{
if len(args)<1{ func args(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("至少需要一个参数!") return errors.New("至少需要一个参数!")
} }

@ -13,28 +13,30 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
) )
var(
port string var (
tcpport string port string
daemon bool tcpport string
daemon bool
GoflyConfig *config.Config GoflyConfig *config.Config
) )
var serverCmd = &cobra.Command{ var serverCmd = &cobra.Command{
Use: "server", Use: "server",
Short: "example:go-fly server port 8081", Short: "example:go-fly server port 8081",
Example: "go-fly server -c config/", Example: "go-fly server -c config/",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
run() run()
}, },
} }
func init() { func init() {
serverCmd.PersistentFlags().StringVarP(&port, "port", "p", "8081", "监听端口号") serverCmd.PersistentFlags().StringVarP(&port, "port", "p", "8081", "监听端口号")
serverCmd.PersistentFlags().StringVarP(&tcpport, "tcpport", "t", "8082", "监听tcp端口号") serverCmd.PersistentFlags().StringVarP(&tcpport, "tcpport", "t", "8082", "监听tcp端口号")
serverCmd.PersistentFlags().BoolVarP(&daemon, "daemon", "d", false, "是否为守护进程模式") serverCmd.PersistentFlags().BoolVarP(&daemon, "daemon", "d", false, "是否为守护进程模式")
} }
func run(){ func run() {
if daemon==true{ if daemon == true {
if os.Getppid() != 1{ if os.Getppid() != 1 {
// 将命令行参数中执行文件路径转换成可用路径 // 将命令行参数中执行文件路径转换成可用路径
filePath, _ := filepath.Abs(os.Args[0]) filePath, _ := filepath.Abs(os.Args[0])
cmd := exec.Command(filePath, os.Args[1:]...) cmd := exec.Command(filePath, os.Args[1:]...)
@ -47,7 +49,7 @@ func run(){
} }
} }
baseServer := "0.0.0.0:"+port baseServer := "0.0.0.0:" + port
//tcpBaseServer := "0.0.0.0:"+tcpport //tcpBaseServer := "0.0.0.0:"+tcpport
log.Println("start server...\r\ngohttp://" + baseServer) log.Println("start server...\r\ngohttp://" + baseServer)
engine := gin.Default() engine := gin.Default()

@ -10,6 +10,6 @@ var versionCmd = &cobra.Command{
Use: "version", Use: "version",
Short: "example:go-fly version", Short: "example:go-fly version",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("go-fly "+config.Version) fmt.Println("go-fly " + config.Version)
}, },
} }

@ -7,27 +7,31 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
) )
var(
PageSize uint=10 var (
VisitorPageSize uint=8 PageSize uint = 10
Version = "0.1.2" VisitorPageSize uint = 8
GoflyConfig *Config Version = "0.1.2"
GoflyConfig *Config
) )
const Dir = "config/" const Dir = "config/"
const AccountConf = Dir + "account.json" const AccountConf = Dir + "account.json"
const MysqlConf = Dir + "mysql.json" const MysqlConf = Dir + "mysql.json"
const MailConf = Dir + "mail.json" const MailConf = Dir + "mail.json"
const LangConf=Dir+"language.json" const LangConf = Dir + "language.json"
const MainConf = Dir + "config.json" const MainConf = Dir + "config.json"
const WeixinToken="" const WeixinToken = ""
const ServerJiang="" const ServerJiang = ""
func init(){
func init() {
//配置文件 //配置文件
GoflyConfig=CreateConfig() GoflyConfig = CreateConfig()
} }
type Mysql struct{
Server string type Mysql struct {
Port string Server string
Port string
Database string Database string
Username string Username string
Password string Password string
@ -36,14 +40,15 @@ type MailServer struct {
Server, Email, Password string Server, Email, Password string
} }
type Config struct { type Config struct {
Upload string Upload string
NoticeServerJiang bool NoticeServerJiang bool
} }
func CreateConfig()*Config{
func CreateConfig() *Config {
var configObj Config var configObj Config
c:=&Config{ c := &Config{
Upload: "static/upload/", Upload: "static/upload/",
NoticeServerJiang:false, NoticeServerJiang: false,
} }
isExist, _ := tools.IsFileExist(MainConf) isExist, _ := tools.IsFileExist(MainConf)
if !isExist { if !isExist {

@ -1,43 +1,41 @@
package config package config
type Language struct { type Language struct {
WebCopyRight string WebCopyRight string
MainIntro string MainIntro string
Send string Send string
Notice string Notice string
IndexSubIntro,IndexVisitors,IndexAgent,IndexDocument,IndexOnlineChat string IndexSubIntro, IndexVisitors, IndexAgent, IndexDocument, IndexOnlineChat string
} }
func CreateLanguage(lang string)*Language{ func CreateLanguage(lang string) *Language {
var language *Language var language *Language
if lang=="en"{ if lang == "en" {
language=&Language{ language = &Language{
WebCopyRight: "TaoShihan", WebCopyRight: "TaoShihan",
MainIntro: "Simple and Powerful Go language online customer chat system", MainIntro: "Simple and Powerful Go language online customer chat system",
IndexSubIntro: "GO-FLY, a Vue 2.0-based online customer service instant messaging system for PHP engineers and Golang engineers", IndexSubIntro: "GO-FLY, a Vue 2.0-based online customer service instant messaging system for PHP engineers and Golang engineers",
IndexDocument:"API Documents", IndexDocument: "API Documents",
IndexVisitors:"Visitors Here", IndexVisitors: "Visitors Here",
IndexAgent:"Agents Here", IndexAgent: "Agents Here",
IndexOnlineChat:"Lets chat. - We're online", IndexOnlineChat: "Lets chat. - We're online",
Send:"Send", Send: "Send",
Notice:"Hello and welcome to go-fly - how can we help?", Notice: "Hello and welcome to go-fly - how can we help?",
} }
} }
if lang=="cn"{ if lang == "cn" {
language=&Language{ language = &Language{
WebCopyRight: "陶士涵的菜地版权所有", WebCopyRight: "陶士涵的菜地版权所有",
MainIntro:"极简强大的Go语言在线客服系统", MainIntro: "极简强大的Go语言在线客服系统",
IndexSubIntro:"GO-FLY一套为PHP工程师、Golang工程师准备的基于 Vue 2.0的在线客服即时通讯系统", IndexSubIntro: "GO-FLY一套为PHP工程师、Golang工程师准备的基于 Vue 2.0的在线客服即时通讯系统",
IndexVisitors:"访客入口", IndexVisitors: "访客入口",
IndexAgent:"客服入口", IndexAgent: "客服入口",
IndexDocument:"接口文档", IndexDocument: "接口文档",
IndexOnlineChat:"在线咨询", IndexOnlineChat: "在线咨询",
Send:"发送", Send: "发送",
Notice:"欢迎您访问go-fly有什么我能帮助您的", Notice: "欢迎您访问go-fly有什么我能帮助您的",
} }
} }
return language return language
} }

@ -25,15 +25,15 @@ func CheckPass(username string, password string) string {
} }
return "" return ""
} }
func CheckKefuPass(username string, password string) (models.User,models.User_role,bool) { func CheckKefuPass(username string, password string) (models.User, models.User_role, bool) {
info:=models.FindUser(username) info := models.FindUser(username)
var uRole models.User_role var uRole models.User_role
if info.Name==""||info.Password!=tools.Md5(password){ if info.Name == "" || info.Password != tools.Md5(password) {
return info,uRole,false return info, uRole, false
} }
uRole=models.FindRoleByUserId(info.ID) uRole = models.FindRoleByUserId(info.ID)
return info,uRole,true return info, uRole, true
} }
func AuthLocal(username string, password string) string { func AuthLocal(username string, password string) string {
account := config.GetAccount() account := config.GetAccount()

@ -9,19 +9,21 @@ import (
"sort" "sort"
"time" "time"
) )
type vistor struct{
conn *websocket.Conn type vistor struct {
name string conn *websocket.Conn
id string name string
id string
avator string avator string
to_id string to_id string
} }
type Message struct{ type Message struct {
conn *websocket.Conn conn *websocket.Conn
c *gin.Context c *gin.Context
content []byte content []byte
messageType int messageType int
} }
var clientList = make(map[string]*vistor) var clientList = make(map[string]*vistor)
var kefuList = make(map[string][]*websocket.Conn) var kefuList = make(map[string][]*websocket.Conn)
var message = make(chan *Message) var message = make(chan *Message)
@ -31,21 +33,22 @@ type TypeMessage struct {
Data interface{} `json:"data"` Data interface{} `json:"data"`
} }
type ClientMessage struct { type ClientMessage struct {
Name string `json:"name"` Name string `json:"name"`
Avator string `json:"avator"` Avator string `json:"avator"`
Id string `json:"id"` Id string `json:"id"`
VisitorId string `json:"visitor_id"` VisitorId string `json:"visitor_id"`
Group string `json:"group"` Group string `json:"group"`
Time string `json:"time"` Time string `json:"time"`
ToId string `json:"to_id"` ToId string `json:"to_id"`
Content string `json:"content"` Content string `json:"content"`
City string `json:"city"` City string `json:"city"`
ClientIp string `json:"client_ip"` ClientIp string `json:"client_ip"`
Refer string `json:"refer"` Refer string `json:"refer"`
} }
//定时检测客户端是否在线 //定时检测客户端是否在线
func init() { func init() {
upgrader=websocket.Upgrader{ upgrader = websocket.Upgrader{
ReadBufferSize: 1024, ReadBufferSize: 1024,
WriteBufferSize: 1024, WriteBufferSize: 1024,
} }
@ -55,8 +58,8 @@ func init() {
//sendPingToClient() //sendPingToClient()
} }
func NewChatServer(c *gin.Context){ func NewChatServer(c *gin.Context) {
conn,err:=upgrader.Upgrade(c.Writer,c.Request,nil) conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
log.Print("upgrade:", err) log.Print("upgrade:", err)
return return
@ -67,11 +70,11 @@ func NewChatServer(c *gin.Context){
var recevString string var recevString string
messageType, receive, err := conn.ReadMessage() messageType, receive, err := conn.ReadMessage()
if err != nil { if err != nil {
for uid,visitor :=range clientList{ for uid, visitor := range clientList {
if visitor.conn==conn{ if visitor.conn == conn {
log.Println("删除用户",uid) log.Println("删除用户", uid)
delete(clientList,uid) delete(clientList, uid)
models.UpdateVisitorStatus(uid,0) models.UpdateVisitorStatus(uid, 0)
userInfo := make(map[string]string) userInfo := make(map[string]string)
userInfo["uid"] = uid userInfo["uid"] = uid
userInfo["name"] = visitor.name userInfo["name"] = visitor.name
@ -80,10 +83,10 @@ func NewChatServer(c *gin.Context){
Data: userInfo, Data: userInfo,
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
kefuConns:=kefuList[visitor.to_id] kefuConns := kefuList[visitor.to_id]
if kefuConns!=nil{ if kefuConns != nil {
for _,kefuConn:=range kefuConns{ for _, kefuConn := range kefuConns {
kefuConn.WriteMessage(websocket.TextMessage,str) kefuConn.WriteMessage(websocket.TextMessage, str)
} }
} }
sendPingOnlineUsers() sendPingOnlineUsers()
@ -92,13 +95,13 @@ func NewChatServer(c *gin.Context){
log.Println(err) log.Println(err)
return return
} }
recevString=string(receive) recevString = string(receive)
log.Println("客户端:", recevString) log.Println("客户端:", recevString)
message<-&Message{ message <- &Message{
conn:conn, conn: conn,
content: receive, content: receive,
c:c, c: c,
messageType:messageType, messageType: messageType,
} }
} }
} }
@ -108,17 +111,18 @@ func SendKefuOnline(clientMsg ClientMessage, conn *websocket.Conn) {
sendMsg := TypeMessage{ sendMsg := TypeMessage{
Type: "kfOnline", Type: "kfOnline",
Data: ClientMessage{ Data: ClientMessage{
Name: clientMsg.Name, Name: clientMsg.Name,
Avator: clientMsg.Avator, Avator: clientMsg.Avator,
Id: clientMsg.Id, Id: clientMsg.Id,
Group: clientMsg.Group, Group: clientMsg.Group,
Time: time.Now().Format("2006-01-02 15:04:05"), Time: time.Now().Format("2006-01-02 15:04:05"),
Content: "客服上线", Content: "客服上线",
}, },
} }
jsonStrByte, _ := json.Marshal(sendMsg) jsonStrByte, _ := json.Marshal(sendMsg)
conn.WriteMessage(websocket.TextMessage,jsonStrByte) conn.WriteMessage(websocket.TextMessage, jsonStrByte)
} }
//发送通知 //发送通知
func SendNotice(msg string, conn *websocket.Conn) { func SendNotice(msg string, conn *websocket.Conn) {
sendMsg := TypeMessage{ sendMsg := TypeMessage{
@ -126,7 +130,7 @@ func SendNotice(msg string, conn *websocket.Conn) {
Data: msg, Data: msg,
} }
jsonStrByte, _ := json.Marshal(sendMsg) jsonStrByte, _ := json.Marshal(sendMsg)
conn.WriteMessage(websocket.TextMessage,jsonStrByte) conn.WriteMessage(websocket.TextMessage, jsonStrByte)
} }
//定时给客户端发送消息判断客户端是否在线 //定时给客户端发送消息判断客户端是否在线
@ -138,28 +142,28 @@ func sendPingToClient() {
for { for {
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
for uid, user := range clientList { for uid, user := range clientList {
err := user.conn.WriteMessage(websocket.TextMessage,str) err := user.conn.WriteMessage(websocket.TextMessage, str)
if err != nil { if err != nil {
delete(clientList, uid) delete(clientList, uid)
models.UpdateVisitorStatus(uid,0) models.UpdateVisitorStatus(uid, 0)
} }
} }
for kefuId, kfConns := range kefuList { for kefuId, kfConns := range kefuList {
var newkfConns =make([]*websocket.Conn,0) var newkfConns = make([]*websocket.Conn, 0)
for _,kefuConn:=range kfConns{ for _, kefuConn := range kfConns {
if(kefuConn==nil){ if kefuConn == nil {
continue continue
} }
err:=kefuConn.WriteMessage(websocket.TextMessage,str) err := kefuConn.WriteMessage(websocket.TextMessage, str)
if err == nil { if err == nil {
newkfConns=append(newkfConns,kefuConn) newkfConns = append(newkfConns, kefuConn)
} }
} }
if newkfConns == nil { if newkfConns == nil {
delete(kefuList, kefuId) delete(kefuList, kefuId)
}else{ } else {
kefuList[kefuId]=newkfConns kefuList[kefuId] = newkfConns
} }
} }
time.Sleep(15 * time.Second) time.Sleep(15 * time.Second)
@ -167,37 +171,39 @@ func sendPingToClient() {
}() }()
} }
//定时给更新数据库状态 //定时给更新数据库状态
func sendPingUpdateStatus() { func sendPingUpdateStatus() {
for { for {
visitors:=models.FindVisitorsOnline() visitors := models.FindVisitorsOnline()
for _,visitor :=range visitors{ for _, visitor := range visitors {
_,ok:=clientList[visitor.VisitorId] _, ok := clientList[visitor.VisitorId]
if !ok{ if !ok {
models.UpdateVisitorStatus(visitor.VisitorId,0) models.UpdateVisitorStatus(visitor.VisitorId, 0)
} }
} }
time.Sleep(20 * time.Second) time.Sleep(20 * time.Second)
} }
} }
//定时推送当前在线用户 //定时推送当前在线用户
func sendPingOnlineUsers() { func sendPingOnlineUsers() {
var visitorIds []string var visitorIds []string
for visitorId, _ := range clientList { for visitorId, _ := range clientList {
visitorIds=append(visitorIds,visitorId) visitorIds = append(visitorIds, visitorId)
} }
sort.Strings(visitorIds) sort.Strings(visitorIds)
for kefuId, kfConns := range kefuList { for kefuId, kfConns := range kefuList {
result := make([]map[string]string, 0) result := make([]map[string]string, 0)
for _,visitorId:=range visitorIds{ for _, visitorId := range visitorIds {
user:=clientList[visitorId] user := clientList[visitorId]
userInfo := make(map[string]string) userInfo := make(map[string]string)
userInfo["uid"] = user.id userInfo["uid"] = user.id
userInfo["username"] = user.name userInfo["username"] = user.name
userInfo["avator"] = user.avator userInfo["avator"] = user.avator
if user.to_id==kefuId{ if user.to_id == kefuId {
result = append(result, userInfo) result = append(result, userInfo)
} }
} }
@ -206,31 +212,31 @@ func sendPingOnlineUsers() {
Data: result, Data: result,
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
var newkfConns =make([]*websocket.Conn,0) var newkfConns = make([]*websocket.Conn, 0)
for _,kefuConn:=range kfConns{ for _, kefuConn := range kfConns {
err:=kefuConn.WriteMessage(websocket.TextMessage,str) err := kefuConn.WriteMessage(websocket.TextMessage, str)
if err == nil { if err == nil {
newkfConns=append(newkfConns,kefuConn) newkfConns = append(newkfConns, kefuConn)
} }
} }
if len(newkfConns) == 0 { if len(newkfConns) == 0 {
delete(kefuList, kefuId) delete(kefuList, kefuId)
}else{ } else {
kefuList[kefuId]=newkfConns kefuList[kefuId] = newkfConns
} }
} }
} }
//后端广播发送消息 //后端广播发送消息
func singleBroadcaster(){ func singleBroadcaster() {
for { for {
message:=<-message message := <-message
//log.Println("debug:",message) //log.Println("debug:",message)
var typeMsg TypeMessage var typeMsg TypeMessage
var clientMsg ClientMessage var clientMsg ClientMessage
json.Unmarshal(message.content, &typeMsg) json.Unmarshal(message.content, &typeMsg)
conn:=message.conn conn := message.conn
if typeMsg.Type == nil || typeMsg.Data == nil { if typeMsg.Type == nil || typeMsg.Data == nil {
continue continue
} }
@ -240,22 +246,22 @@ func singleBroadcaster(){
//用户上线 //用户上线
case "userInit": case "userInit":
json.Unmarshal(msgData, &clientMsg) json.Unmarshal(msgData, &clientMsg)
vistorInfo:=models.FindVisitorByVistorId(clientMsg.VisitorId) vistorInfo := models.FindVisitorByVistorId(clientMsg.VisitorId)
if vistorInfo.VisitorId==""{ if vistorInfo.VisitorId == "" {
SendNotice("访客数据不存在",conn) SendNotice("访客数据不存在", conn)
continue continue
} }
//用户id对应的连接 //用户id对应的连接
user:=&vistor{ user := &vistor{
conn:conn, conn: conn,
name: clientMsg.Name, name: clientMsg.Name,
avator: clientMsg.Avator, avator: clientMsg.Avator,
id:clientMsg.VisitorId, id: clientMsg.VisitorId,
to_id:clientMsg.ToId, to_id: clientMsg.ToId,
} }
clientList[clientMsg.VisitorId] = user clientList[clientMsg.VisitorId] = user
//插入数据表 //插入数据表
models.UpdateVisitor(clientMsg.VisitorId,1,clientMsg.ClientIp,message.c.ClientIP(),clientMsg.Refer) models.UpdateVisitor(clientMsg.VisitorId, 1, clientMsg.ClientIp, message.c.ClientIP(), clientMsg.Refer)
//models.CreateVisitor(clientMsg.Name,clientMsg.Avator,message.c.ClientIP(),clientMsg.ToId,clientMsg.VisitorId,clientMsg.Refer,clientMsg.City,clientMsg.ClientIp) //models.CreateVisitor(clientMsg.Name,clientMsg.Avator,message.c.ClientIP(),clientMsg.ToId,clientMsg.VisitorId,clientMsg.Refer,clientMsg.City,clientMsg.ClientIp)
userInfo := make(map[string]string) userInfo := make(map[string]string)
userInfo["uid"] = user.id userInfo["uid"] = user.id
@ -266,11 +272,11 @@ func singleBroadcaster(){
Data: userInfo, Data: userInfo,
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
kefuConns:=kefuList[user.to_id] kefuConns := kefuList[user.to_id]
if kefuConns!=nil{ if kefuConns != nil {
for k,kefuConn:=range kefuConns{ for k, kefuConn := range kefuConns {
log.Println(k,"xxxxxxxx") log.Println(k, "xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage,str) kefuConn.WriteMessage(websocket.TextMessage, str)
} }
} }
//客户上线发微信通知 //客户上线发微信通知
@ -280,10 +286,10 @@ func singleBroadcaster(){
case "kfOnline": case "kfOnline":
json.Unmarshal(msgData, &clientMsg) json.Unmarshal(msgData, &clientMsg)
//客服id对应的连接 //客服id对应的连接
var newKefuConns =[]*websocket.Conn{conn} var newKefuConns = []*websocket.Conn{conn}
kefuConns:=kefuList[clientMsg.Id] kefuConns := kefuList[clientMsg.Id]
if kefuConns!=nil{ if kefuConns != nil {
newKefuConns=append(newKefuConns,kefuConns...) newKefuConns = append(newKefuConns, kefuConns...)
} }
log.Println(newKefuConns) log.Println(newKefuConns)
kefuList[clientMsg.Id] = newKefuConns kefuList[clientMsg.Id] = newKefuConns
@ -295,8 +301,8 @@ func singleBroadcaster(){
//客服接手 //客服接手
case "kfConnect": case "kfConnect":
json.Unmarshal(msgData, &clientMsg) json.Unmarshal(msgData, &clientMsg)
visitor,ok := clientList[clientMsg.ToId] visitor, ok := clientList[clientMsg.ToId]
if visitor==nil||!ok{ if visitor == nil || !ok {
continue continue
} }
SendKefuOnline(clientMsg, visitor.conn) SendKefuOnline(clientMsg, visitor.conn)
@ -306,11 +312,8 @@ func singleBroadcaster(){
Type: "pong", Type: "pong",
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
conn.WriteMessage(websocket.TextMessage,str) conn.WriteMessage(websocket.TextMessage, str)
} }
} }
} }

@ -13,6 +13,7 @@ import (
) )
const PageSize = 20 const PageSize = 20
func GetFolders(c *gin.Context) { func GetFolders(c *gin.Context) {
fid := c.Query("fid") fid := c.Query("fid")
currentPage, _ := strconv.Atoi(c.Query("page")) currentPage, _ := strconv.Atoi(c.Query("page"))
@ -44,9 +45,9 @@ func GetFolders(c *gin.Context) {
result["fid"] = fid result["fid"] = fid
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":result, "result": result,
}) })
} }
func GetFolderList(c *gin.Context) { func GetFolderList(c *gin.Context) {
@ -64,11 +65,12 @@ func GetFolderList(c *gin.Context) {
result["fid"] = fid result["fid"] = fid
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":result, "result": result,
}) })
} }
//输出列表 //输出列表
func ActionFolder(w http.ResponseWriter, r *http.Request) { func ActionFolder(w http.ResponseWriter, r *http.Request) {
fid := tools.GetUrlArg(r, "fid") fid := tools.GetUrlArg(r, "fid")

@ -5,9 +5,11 @@ import (
"github.com/taoshihan1991/imaptool/tools" "github.com/taoshihan1991/imaptool/tools"
"net/http" "net/http"
) )
func Index(c *gin.Context) { func Index(c *gin.Context) {
c.Redirect(302,"/index") c.Redirect(302, "/index")
} }
//首页跳转 //首页跳转
func ActionIndex(w http.ResponseWriter, r *http.Request) { func ActionIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.RequestURI() == "/favicon.ico" { if r.URL.RequestURI() == "/favicon.ico" {

@ -9,7 +9,7 @@ import (
func PostIpblack(c *gin.Context) { func PostIpblack(c *gin.Context) {
ip := c.PostForm("ip") ip := c.PostForm("ip")
if ip==""{ if ip == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "请输入IP!", "msg": "请输入IP!",
@ -17,7 +17,7 @@ func PostIpblack(c *gin.Context) {
return return
} }
kefuId, _ := c.Get("kefu_name") kefuId, _ := c.Get("kefu_name")
models.CreateIpblack(ip,kefuId.(string)) models.CreateIpblack(ip, kefuId.(string))
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "添加黑名单成功!", "msg": "添加黑名单成功!",
@ -25,7 +25,7 @@ func PostIpblack(c *gin.Context) {
} }
func DelIpblack(c *gin.Context) { func DelIpblack(c *gin.Context) {
ip := c.Query("ip") ip := c.Query("ip")
if ip==""{ if ip == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "请输入IP!", "msg": "请输入IP!",
@ -39,19 +39,19 @@ func DelIpblack(c *gin.Context) {
}) })
} }
func GetIpblacks(c *gin.Context) { func GetIpblacks(c *gin.Context) {
page,_:=strconv.Atoi(c.Query("page")) page, _ := strconv.Atoi(c.Query("page"))
if page==0{ if page == 0 {
page=1 page = 1
} }
count:=models.CountIps(nil,nil) count := models.CountIps(nil, nil)
list:=models.FindIps(nil,nil,uint(page),config.VisitorPageSize) list := models.FindIps(nil, nil, uint(page), config.VisitorPageSize)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":gin.H{ "result": gin.H{
"list":list, "list": list,
"count":count, "count": count,
"pagesize":config.PageSize, "pagesize": config.PageSize,
}, },
}) })
} }

@ -7,36 +7,36 @@ import (
"strconv" "strconv"
) )
func GetKefuInfo(c *gin.Context){ func GetKefuInfo(c *gin.Context) {
kefuId, _ := c.Get("kefu_id") kefuId, _ := c.Get("kefu_id")
user:=models.FindUserById(kefuId) user := models.FindUserById(kefuId)
info:=make(map[string]interface{}) info := make(map[string]interface{})
info["name"]=user.Nickname info["name"] = user.Nickname
info["id"]=user.Name info["id"] = user.Name
info["avator"]=user.Avator info["avator"] = user.Avator
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":info, "result": info,
}) })
} }
func GetKefuInfoSetting(c *gin.Context){ func GetKefuInfoSetting(c *gin.Context) {
kefuId := c.Query("kefu_id") kefuId := c.Query("kefu_id")
user:=models.FindUserById(kefuId) user := models.FindUserById(kefuId)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":user, "result": user,
}) })
} }
func PostKefuInfo(c *gin.Context){ func PostKefuInfo(c *gin.Context) {
id:=c.PostForm("id") id := c.PostForm("id")
name:=c.PostForm("name") name := c.PostForm("name")
password:=c.PostForm("password") password := c.PostForm("password")
avator:=c.PostForm("avator") avator := c.PostForm("avator")
nickname:=c.PostForm("nickname") nickname := c.PostForm("nickname")
roleId:=c.PostForm("role_id") roleId := c.PostForm("role_id")
if roleId==""{ if roleId == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "请选择角色!", "msg": "请选择角色!",
@ -44,51 +44,51 @@ func PostKefuInfo(c *gin.Context){
return return
} }
//插入新用户 //插入新用户
if id==""{ if id == "" {
uid:=models.CreateUser(name,tools.Md5(password),avator,nickname) uid := models.CreateUser(name, tools.Md5(password), avator, nickname)
if uid==0{ if uid == 0 {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "增加用户失败", "msg": "增加用户失败",
"result":"", "result": "",
}) })
return return
} }
roleIdInt,_:=strconv.Atoi(roleId) roleIdInt, _ := strconv.Atoi(roleId)
models.CreateUserRole(uid,uint(roleIdInt)) models.CreateUserRole(uid, uint(roleIdInt))
}else{ } else {
//更新用户 //更新用户
if password!=""{ if password != "" {
password=tools.Md5(password) password = tools.Md5(password)
} }
models.UpdateUser(id,name,password,avator,nickname) models.UpdateUser(id, name, password, avator, nickname)
roleIdInt,_:=strconv.Atoi(roleId) roleIdInt, _ := strconv.Atoi(roleId)
uid,_:=strconv.Atoi(id) uid, _ := strconv.Atoi(id)
models.DeleteRoleByUserId(uid) models.DeleteRoleByUserId(uid)
models.CreateUserRole(uint(uid),uint(roleIdInt)) models.CreateUserRole(uint(uid), uint(roleIdInt))
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":"", "result": "",
}) })
} }
func GetKefuList(c *gin.Context){ func GetKefuList(c *gin.Context) {
users:=models.FindUsers() users := models.FindUsers()
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "获取成功", "msg": "获取成功",
"result":users, "result": users,
}) })
} }
func DeleteKefuInfo(c *gin.Context){ func DeleteKefuInfo(c *gin.Context) {
kefuId := c.Query("id") kefuId := c.Query("id")
models.DeleteUserById(kefuId) models.DeleteUserById(kefuId)
models.DeleteRoleByUserId(kefuId) models.DeleteRoleByUserId(kefuId)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "删除成功", "msg": "删除成功",
"result":"", "result": "",
}) })
} }

@ -5,6 +5,7 @@ import (
"github.com/taoshihan1991/imaptool/tools" "github.com/taoshihan1991/imaptool/tools"
"time" "time"
) )
// @Summary 登陆验证接口 // @Summary 登陆验证接口
// @Produce json // @Produce json
// @Accept multipart/form-data // @Accept multipart/form-data
@ -19,35 +20,35 @@ func LoginCheckPass(c *gin.Context) {
password := c.PostForm("password") password := c.PostForm("password")
username := c.PostForm("username") username := c.PostForm("username")
info,uRole,ok:=CheckKefuPass(username, password) info, uRole, ok := CheckKefuPass(username, password)
userinfo:= make(map[string]interface{}) userinfo := make(map[string]interface{})
if !ok{ if !ok {
c.JSON(200, gin.H{
"code": 400,
"msg": "验证失败",
})
return
}
userinfo["name"] = info.Name
userinfo["kefu_id"] = info.ID
userinfo["type"] = "kefu"
if uRole.RoleId!=0 {
userinfo["role_id"] =uRole.RoleId
}else{
userinfo["role_id"]=2
}
userinfo["create_time"] = time.Now().Unix()
token, _ := tools.MakeToken(userinfo)
userinfo["ref_token"]=true
refToken, _ := tools.MakeToken(userinfo)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 400,
"msg": "验证成功,正在跳转", "msg": "验证失败",
"result": gin.H{
"token": token,
"ref_token":refToken,
"create_time":userinfo["create_time"],
},
}) })
return
}
userinfo["name"] = info.Name
userinfo["kefu_id"] = info.ID
userinfo["type"] = "kefu"
if uRole.RoleId != 0 {
userinfo["role_id"] = uRole.RoleId
} else {
userinfo["role_id"] = 2
}
userinfo["create_time"] = time.Now().Unix()
token, _ := tools.MakeToken(userinfo)
userinfo["ref_token"] = true
refToken, _ := tools.MakeToken(userinfo)
c.JSON(200, gin.H{
"code": 200,
"msg": "验证成功,正在跳转",
"result": gin.H{
"token": token,
"ref_token": refToken,
"create_time": userinfo["create_time"],
},
})
} }

@ -19,29 +19,29 @@ func ActionMain(w http.ResponseWriter, r *http.Request) {
render.Display("main", render) render.Display("main", render)
} }
func MainCheckAuth(c *gin.Context) { func MainCheckAuth(c *gin.Context) {
id,_:=c.Get("kefu_id") id, _ := c.Get("kefu_id")
userinfo:=models.FindUserRole("user.avator,user.name,user.id, role.name role_name",id) userinfo := models.FindUserRole("user.avator,user.name,user.id, role.name role_name", id)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "验证成功", "msg": "验证成功",
"result":gin.H{ "result": gin.H{
"avator":userinfo.Avator, "avator": userinfo.Avator,
"name":userinfo.Name, "name": userinfo.Name,
"role_name":userinfo.RoleName, "role_name": userinfo.RoleName,
}, },
}) })
} }
func GetStatistics(c *gin.Context) { func GetStatistics(c *gin.Context) {
visitors:=models.CountVisitors() visitors := models.CountVisitors()
message:=models.CountMessage() message := models.CountMessage()
session:=len(clientList) session := len(clientList)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":gin.H{ "result": gin.H{
"visitors":visitors, "visitors": visitors,
"message":message, "message": message,
"session":session, "session": session,
}, },
}) })
} }

@ -13,6 +13,7 @@ import (
"strings" "strings"
"time" "time"
) )
// @Summary 发送消息接口 // @Summary 发送消息接口
// @Produce json // @Produce json
// @Accept multipart/form-data // @Accept multipart/form-data
@ -28,7 +29,7 @@ func SendMessage(c *gin.Context) {
toId := c.PostForm("to_id") toId := c.PostForm("to_id")
content := c.PostForm("content") content := c.PostForm("content")
cType := c.PostForm("type") cType := c.PostForm("type")
if content==""{ if content == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "内容不能为空", "msg": "内容不能为空",
@ -38,26 +39,26 @@ func SendMessage(c *gin.Context) {
var kefuInfo models.User var kefuInfo models.User
var vistorInfo models.Visitor var vistorInfo models.Visitor
if cType=="kefu"{ if cType == "kefu" {
kefuInfo=models.FindUser(fromId) kefuInfo = models.FindUser(fromId)
vistorInfo=models.FindVisitorByVistorId(toId) vistorInfo = models.FindVisitorByVistorId(toId)
}else if cType=="visitor"{ } else if cType == "visitor" {
vistorInfo=models.FindVisitorByVistorId(fromId) vistorInfo = models.FindVisitorByVistorId(fromId)
kefuInfo=models.FindUser(toId) kefuInfo = models.FindUser(toId)
} }
if kefuInfo.ID==0 ||vistorInfo.ID==0{ if kefuInfo.ID == 0 || vistorInfo.ID == 0 {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "用户不存在", "msg": "用户不存在",
}) })
return return
} }
models.CreateMessage(kefuInfo.Name,vistorInfo.VisitorId,content,cType) models.CreateMessage(kefuInfo.Name, vistorInfo.VisitorId, content, cType)
if cType=="kefu"{ if cType == "kefu" {
guest,ok:=clientList[vistorInfo.VisitorId] guest, ok := clientList[vistorInfo.VisitorId]
if guest==nil||!ok{ if guest == nil || !ok {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
@ -69,21 +70,21 @@ func SendMessage(c *gin.Context) {
msg := TypeMessage{ msg := TypeMessage{
Type: "message", Type: "message",
Data: ClientMessage{ Data: ClientMessage{
Name: kefuInfo.Nickname, Name: kefuInfo.Nickname,
Avator: kefuInfo.Avator, Avator: kefuInfo.Avator,
Id: kefuInfo.Name, Id: kefuInfo.Name,
Time: time.Now().Format("2006-01-02 15:04:05"), Time: time.Now().Format("2006-01-02 15:04:05"),
ToId: vistorInfo.VisitorId, ToId: vistorInfo.VisitorId,
Content: content, Content: content,
}, },
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
PushServerTcp(str) PushServerTcp(str)
conn.WriteMessage(websocket.TextMessage,str) conn.WriteMessage(websocket.TextMessage, str)
} }
if cType=="visitor"{ if cType == "visitor" {
kefuConns,ok := kefuList[kefuInfo.Name] kefuConns, ok := kefuList[kefuInfo.Name]
if kefuConns==nil||!ok{ if kefuConns == nil || !ok {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
@ -93,18 +94,18 @@ func SendMessage(c *gin.Context) {
msg := TypeMessage{ msg := TypeMessage{
Type: "message", Type: "message",
Data: ClientMessage{ Data: ClientMessage{
Avator: vistorInfo.Avator, Avator: vistorInfo.Avator,
Id: vistorInfo.VisitorId, Id: vistorInfo.VisitorId,
Name: vistorInfo.Name, Name: vistorInfo.Name,
ToId: kefuInfo.Name, ToId: kefuInfo.Name,
Content: content, Content: content,
Time: time.Now().Format("2006-01-02 15:04:05"), Time: time.Now().Format("2006-01-02 15:04:05"),
}, },
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
PushServerTcp(str) PushServerTcp(str)
for _,kefuConn:=range kefuConns{ for _, kefuConn := range kefuConns {
kefuConn.WriteMessage(websocket.TextMessage,str) kefuConn.WriteMessage(websocket.TextMessage, str)
} }
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
@ -114,7 +115,7 @@ func SendMessage(c *gin.Context) {
} }
func SendVisitorNotice(c *gin.Context) { func SendVisitorNotice(c *gin.Context) {
notice := c.Query("msg") notice := c.Query("msg")
if notice==""{ if notice == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "msg不能为空", "msg": "msg不能为空",
@ -126,16 +127,16 @@ func SendVisitorNotice(c *gin.Context) {
Data: notice, Data: notice,
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
for _,visitor :=range clientList{ for _, visitor := range clientList {
visitor.conn.WriteMessage(websocket.TextMessage,str) visitor.conn.WriteMessage(websocket.TextMessage, str)
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
}) })
} }
func UploadImg(c *gin.Context){ func UploadImg(c *gin.Context) {
config:=config.CreateConfig() config := config.CreateConfig()
f, err := c.FormFile("imgfile") f, err := c.FormFile("imgfile")
if err != nil { if err != nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
@ -145,27 +146,27 @@ func UploadImg(c *gin.Context){
return return
} else { } else {
fileExt:=strings.ToLower(path.Ext(f.Filename)) fileExt := strings.ToLower(path.Ext(f.Filename))
if fileExt!=".png"&&fileExt!=".jpg"&&fileExt!=".gif"&&fileExt!=".jpeg"{ if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "上传失败!只允许png,jpg,gif,jpeg文件", "msg": "上传失败!只允许png,jpg,gif,jpeg文件",
}) })
return return
} }
fileName:=tools.Md5(fmt.Sprintf("%s%s",f.Filename,time.Now().String())) fileName := tools.Md5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
fildDir:=fmt.Sprintf("%s%d%s/",config.Upload,time.Now().Year(),time.Now().Month().String()) fildDir := fmt.Sprintf("%s%d%s/", config.Upload, time.Now().Year(), time.Now().Month().String())
isExist,_:=tools.IsFileExist(fildDir) isExist, _ := tools.IsFileExist(fildDir)
if !isExist{ if !isExist {
os.Mkdir(fildDir,os.ModePerm) os.Mkdir(fildDir, os.ModePerm)
} }
filepath:=fmt.Sprintf("%s%s%s",fildDir,fileName,fileExt) filepath := fmt.Sprintf("%s%s%s", fildDir, fileName, fileExt)
c.SaveUploadedFile(f, filepath) c.SaveUploadedFile(f, filepath)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "上传成功!", "msg": "上传成功!",
"result":gin.H{ "result": gin.H{
"path":filepath, "path": filepath,
}, },
}) })
} }

@ -8,29 +8,30 @@ import (
"github.com/taoshihan1991/imaptool/tools" "github.com/taoshihan1991/imaptool/tools"
"os" "os"
) )
func MysqlGetConf(c *gin.Context) { func MysqlGetConf(c *gin.Context) {
mysqlInfo:=config.GetMysql() mysqlInfo := config.GetMysql()
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "验证成功", "msg": "验证成功",
"result":mysqlInfo, "result": mysqlInfo,
}) })
} }
func MysqlSetConf(c *gin.Context) { func MysqlSetConf(c *gin.Context) {
mysqlServer:=c.PostForm("server") mysqlServer := c.PostForm("server")
mysqlPort:=c.PostForm("port") mysqlPort := c.PostForm("port")
mysqlDb:=c.PostForm("database") mysqlDb := c.PostForm("database")
mysqlUsername:=c.PostForm("username") mysqlUsername := c.PostForm("username")
mysqlPassword:=c.PostForm("password") mysqlPassword := c.PostForm("password")
dsn:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", mysqlUsername,mysqlPassword, mysqlServer, mysqlPort, mysqlDb) dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", mysqlUsername, mysqlPassword, mysqlServer, mysqlPort, mysqlDb)
mysql:=database.NewMysql() mysql := database.NewMysql()
mysql.Dsn=dsn mysql.Dsn = dsn
err:=mysql.Ping() err := mysql.Ping()
if err!=nil{ if err != nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 403, "code": 403,
"msg": "数据库连接失败:"+err.Error(), "msg": "数据库连接失败:" + err.Error(),
}) })
return return
} }
@ -49,7 +50,7 @@ func MysqlSetConf(c *gin.Context) {
"Password":"%s" "Password":"%s"
} }
` `
data := fmt.Sprintf(format, mysqlServer,mysqlPort,mysqlDb,mysqlUsername,mysqlPassword) data := fmt.Sprintf(format, mysqlServer, mysqlPort, mysqlDb, mysqlUsername, mysqlPassword)
file.WriteString(data) file.WriteString(data)
c.JSON(200, gin.H{ c.JSON(200, gin.H{

@ -11,56 +11,58 @@ import (
"net/http" "net/http"
"time" "time"
) )
func GetNotice(c *gin.Context) { func GetNotice(c *gin.Context) {
kefuId:=c.Query("kefu_id") kefuId := c.Query("kefu_id")
welcomes:=models.FindWelcomesByUserId(kefuId) welcomes := models.FindWelcomesByUserId(kefuId)
user:=models.FindUser(kefuId) user := models.FindUser(kefuId)
result:=make([]gin.H,0) result := make([]gin.H, 0)
for _,welcome:=range welcomes{ for _, welcome := range welcomes {
h:=gin.H{ h := gin.H{
"name":user.Nickname, "name": user.Nickname,
"avator":user.Avator, "avator": user.Avator,
"is_kefu":false, "is_kefu": false,
"content":welcome.Content, "content": welcome.Content,
"time":time.Now().Format("2006-01-02 15:04:05"), "time": time.Now().Format("2006-01-02 15:04:05"),
} }
result=append(result,h) result = append(result, h)
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":result, "result": result,
}) })
} }
func GetNotices(c *gin.Context) { func GetNotices(c *gin.Context) {
kefuId,_:=c.Get("kefu_name") kefuId, _ := c.Get("kefu_name")
welcomes:=models.FindWelcomesByUserId(kefuId) welcomes := models.FindWelcomesByUserId(kefuId)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":welcomes, "result": welcomes,
}) })
} }
func PostNotice(c *gin.Context) { func PostNotice(c *gin.Context) {
kefuId,_:=c.Get("kefu_name") kefuId, _ := c.Get("kefu_name")
content:=c.PostForm("content") content := c.PostForm("content")
models.CreateWelcome(fmt.Sprintf("%s",kefuId),content) models.CreateWelcome(fmt.Sprintf("%s", kefuId), content)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":"", "result": "",
}) })
} }
func DelNotice(c *gin.Context) { func DelNotice(c *gin.Context) {
kefuId,_:=c.Get("kefu_name") kefuId, _ := c.Get("kefu_name")
id:=c.Query("id") id := c.Query("id")
models.DeleteWelcome(kefuId,id) models.DeleteWelcome(kefuId, id)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":"", "result": "",
}) })
} }
var upgrader = websocket.Upgrader{} var upgrader = websocket.Upgrader{}
var oldFolders map[string]int var oldFolders map[string]int

@ -1,6 +1,7 @@
package controller package controller
type Response struct { type Response struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"msg"` Msg string `json:"msg"`
result interface{} `json:"result"` result interface{} `json:"result"`
} }

@ -5,27 +5,27 @@ import (
"github.com/taoshihan1991/imaptool/models" "github.com/taoshihan1991/imaptool/models"
) )
func GetRoleList(c *gin.Context){ func GetRoleList(c *gin.Context) {
roles:=models.FindRoles() roles := models.FindRoles()
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "获取成功", "msg": "获取成功",
"result":roles, "result": roles,
}) })
} }
func PostRole(c *gin.Context){ func PostRole(c *gin.Context) {
roleId:=c.PostForm("id") roleId := c.PostForm("id")
method:=c.PostForm("method") method := c.PostForm("method")
name:=c.PostForm("name") name := c.PostForm("name")
path:=c.PostForm("path") path := c.PostForm("path")
if roleId==""||method==""||name==""||path==""{ if roleId == "" || method == "" || name == "" || path == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "参数不能为空", "msg": "参数不能为空",
}) })
return return
} }
models.SaveRole(roleId,name,method,path) models.SaveRole(roleId, name, method, path)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "修改成功", "msg": "修改成功",

@ -6,28 +6,28 @@ import (
) )
func GetConfigs(c *gin.Context) { func GetConfigs(c *gin.Context) {
configs:=models.FindConfigs() configs := models.FindConfigs()
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":configs, "result": configs,
}) })
} }
func PostConfig(c *gin.Context){ func PostConfig(c *gin.Context) {
key:=c.PostForm("key") key := c.PostForm("key")
value:=c.PostForm("value") value := c.PostForm("value")
if key==""||value==""{ if key == "" || value == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "error", "msg": "error",
}) })
return return
} }
models.UpdateConfig(key,value) models.UpdateConfig(key, value)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":"", "result": "",
}) })
} }

@ -8,17 +8,17 @@ import (
"strconv" "strconv"
) )
func SendServerJiang(content string)string{ func SendServerJiang(content string) string {
noticeServerJiang,err:=strconv.ParseBool(models.FindConfig("NoticeServerJiang")) noticeServerJiang, err := strconv.ParseBool(models.FindConfig("NoticeServerJiang"))
serverJiangAPI:=models.FindConfig("ServerJiangAPI") serverJiangAPI := models.FindConfig("ServerJiangAPI")
if err!=nil || !noticeServerJiang || serverJiangAPI==""{ if err != nil || !noticeServerJiang || serverJiangAPI == "" {
log.Println("do not notice serverjiang:",serverJiangAPI,noticeServerJiang) log.Println("do not notice serverjiang:", serverJiangAPI, noticeServerJiang)
return "" return ""
} }
sendStr:=fmt.Sprintf("%s,访客来了",content) sendStr := fmt.Sprintf("%s,访客来了", content)
desp:="[登录](https://gofly.sopans.com/main)"; desp := "[登录](https://gofly.sopans.com/main)"
url:=serverJiangAPI+"?text="+sendStr+"&desp="+desp url := serverJiangAPI + "?text=" + sendStr + "&desp=" + desp
//log.Println(url) //log.Println(url)
res:=tools.Get(url) res := tools.Get(url)
return res return res
} }

@ -5,8 +5,10 @@ import (
"log" "log"
"net" "net"
) )
var clientTcpList = make(map[string]net.Conn) var clientTcpList = make(map[string]net.Conn)
func NewTcpServer(tcpBaseServer string){
func NewTcpServer(tcpBaseServer string) {
listener, err := net.Listen("tcp", tcpBaseServer) listener, err := net.Listen("tcp", tcpBaseServer)
if err != nil { if err != nil {
log.Println("Error listening", err.Error()) log.Println("Error listening", err.Error())
@ -20,33 +22,33 @@ func NewTcpServer(tcpBaseServer string){
return // 终止程序 return // 终止程序
} }
var remoteIpAddress = conn.RemoteAddr() var remoteIpAddress = conn.RemoteAddr()
clientTcpList[remoteIpAddress.String()]=conn clientTcpList[remoteIpAddress.String()] = conn
log.Println(remoteIpAddress,clientTcpList) log.Println(remoteIpAddress, clientTcpList)
//clientTcpList=append(clientTcpList,conn) //clientTcpList=append(clientTcpList,conn)
} }
} }
func PushServerTcp(str []byte){ func PushServerTcp(str []byte) {
for ip,conn:=range clientTcpList{ for ip, conn := range clientTcpList {
line:=append(str,[]byte("\r\n")...) line := append(str, []byte("\r\n")...)
_,err:=conn.Write(line) _, err := conn.Write(line)
log.Println(ip,err) log.Println(ip, err)
if err!=nil{ if err != nil {
conn.Close() conn.Close()
delete(clientTcpList,ip) delete(clientTcpList, ip)
//clientTcpList=append(clientTcpList[:index],clientTcpList[index+1:]...) //clientTcpList=append(clientTcpList[:index],clientTcpList[index+1:]...)
} }
} }
} }
func DeleteOnlineTcp(c *gin.Context) { func DeleteOnlineTcp(c *gin.Context) {
ip:=c.Query("ip") ip := c.Query("ip")
for ipkey,conn :=range clientTcpList{ for ipkey, conn := range clientTcpList {
if ip==ipkey{ if ip == ipkey {
conn.Close() conn.Close()
delete(clientTcpList,ip) delete(clientTcpList, ip)
} }
if ip=="all"{ if ip == "all" {
conn.Close() conn.Close()
delete(clientTcpList,ipkey) delete(clientTcpList, ipkey)
} }
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{

@ -12,6 +12,7 @@ import (
"math/rand" "math/rand"
"strconv" "strconv"
) )
func PostVisitor(c *gin.Context) { func PostVisitor(c *gin.Context) {
name := c.PostForm("name") name := c.PostForm("name")
avator := c.PostForm("avator") avator := c.PostForm("avator")
@ -20,22 +21,22 @@ func PostVisitor(c *gin.Context) {
refer := c.PostForm("refer") refer := c.PostForm("refer")
city := c.PostForm("city") city := c.PostForm("city")
client_ip := c.PostForm("client_ip") client_ip := c.PostForm("client_ip")
if name==""||avator==""||toId==""||id==""||refer==""||city==""||client_ip==""{ if name == "" || avator == "" || toId == "" || id == "" || refer == "" || city == "" || client_ip == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "error", "msg": "error",
}) })
return return
} }
kefuInfo:=models.FindUser(toId) kefuInfo := models.FindUser(toId)
if kefuInfo.ID==0{ if kefuInfo.ID == 0 {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "用户不存在", "msg": "用户不存在",
}) })
return return
} }
models.CreateVisitor(name,avator,c.ClientIP(),toId,id,refer,city,client_ip) models.CreateVisitor(name, avator, c.ClientIP(), toId, id, refer, city, client_ip)
userInfo := make(map[string]string) userInfo := make(map[string]string)
userInfo["uid"] = id userInfo["uid"] = id
@ -46,11 +47,11 @@ func PostVisitor(c *gin.Context) {
Data: userInfo, Data: userInfo,
} }
str, _ := json.Marshal(msg) str, _ := json.Marshal(msg)
kefuConns:=kefuList[toId] kefuConns := kefuList[toId]
if kefuConns!=nil{ if kefuConns != nil {
for k,kefuConn:=range kefuConns{ for k, kefuConn := range kefuConns {
log.Println(k,"xxxxxxxx") log.Println(k, "xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage,str) kefuConn.WriteMessage(websocket.TextMessage, str)
} }
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
@ -59,11 +60,11 @@ func PostVisitor(c *gin.Context) {
}) })
} }
func PostVisitorLogin(c *gin.Context) { func PostVisitorLogin(c *gin.Context) {
ipcity:=tools.ParseIp(c.ClientIP()) ipcity := tools.ParseIp(c.ClientIP())
avator := fmt.Sprintf("/static/images/%d.jpg",rand.Intn(14)) avator := fmt.Sprintf("/static/images/%d.jpg", rand.Intn(14))
toId := c.PostForm("to_id") toId := c.PostForm("to_id")
id := c.PostForm("id") id := c.PostForm("id")
if id==""{ if id == "" {
id = tools.Uuid() id = tools.Uuid()
} }
refer := c.PostForm("refer") refer := c.PostForm("refer")
@ -71,47 +72,48 @@ func PostVisitorLogin(c *gin.Context) {
city string city string
name string name string
) )
if ipcity!=nil{ if ipcity != nil {
city = ipcity.CountryName+ipcity.RegionName+ipcity.CityName city = ipcity.CountryName + ipcity.RegionName + ipcity.CityName
name=ipcity.CountryName+ipcity.RegionName+ipcity.CityName+"网友" name = ipcity.CountryName + ipcity.RegionName + ipcity.CityName + "网友"
}else{ } else {
city="未识别地区" city = "未识别地区"
name="匿名网友" name = "匿名网友"
} }
client_ip := c.PostForm("client_ip") client_ip := c.PostForm("client_ip")
//log.Println(name,avator,c.ClientIP(),toId,id,refer,city,client_ip) //log.Println(name,avator,c.ClientIP(),toId,id,refer,city,client_ip)
if name==""||avator==""||toId==""||id==""||refer==""||city==""||client_ip==""{ if name == "" || avator == "" || toId == "" || id == "" || refer == "" || city == "" || client_ip == "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "error", "msg": "error",
}) })
return return
} }
kefuInfo:=models.FindUser(toId) kefuInfo := models.FindUser(toId)
if kefuInfo.ID==0{ if kefuInfo.ID == 0 {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "客服不存在", "msg": "客服不存在",
}) })
return return
} }
models.CreateVisitor(name,avator,c.ClientIP(),toId,id,refer,city,client_ip) models.CreateVisitor(name, avator, c.ClientIP(), toId, id, refer, city, client_ip)
visitor:=models.FindVisitorByVistorId(id) visitor := models.FindVisitorByVistorId(id)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":visitor, "result": visitor,
}) })
} }
func GetVisitor(c *gin.Context) { func GetVisitor(c *gin.Context) {
visitorId:=c.Query("visitorId") visitorId := c.Query("visitorId")
vistor:=models.FindVisitorByVistorId(visitorId) vistor := models.FindVisitorByVistorId(visitorId)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":vistor, "result": vistor,
}) })
} }
// @Summary 获取访客列表接口 // @Summary 获取访客列表接口
// @Produce json // @Produce json
// @Accept multipart/form-data // @Accept multipart/form-data
@ -121,20 +123,21 @@ func GetVisitor(c *gin.Context) {
// @Failure 200 {object} controller.Response // @Failure 200 {object} controller.Response
// @Router /visitors [get] // @Router /visitors [get]
func GetVisitors(c *gin.Context) { func GetVisitors(c *gin.Context) {
page,_:=strconv.Atoi(c.Query("page")) page, _ := strconv.Atoi(c.Query("page"))
kefuId,_:=c.Get("kefu_name") kefuId, _ := c.Get("kefu_name")
vistors:=models.FindVisitorsByKefuId(uint(page),config.VisitorPageSize,kefuId.(string)) vistors := models.FindVisitorsByKefuId(uint(page), config.VisitorPageSize, kefuId.(string))
count:=models.CountVisitorsByKefuId(kefuId.(string)) count := models.CountVisitorsByKefuId(kefuId.(string))
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":gin.H{ "result": gin.H{
"list":vistors, "list": vistors,
"count":count, "count": count,
"pagesize":config.PageSize, "pagesize": config.PageSize,
}, },
}) })
} }
// @Summary 获取访客聊天信息接口 // @Summary 获取访客聊天信息接口
// @Produce json // @Produce json
// @Accept multipart/form-data // @Accept multipart/form-data
@ -144,53 +147,53 @@ func GetVisitors(c *gin.Context) {
// @Failure 200 {object} controller.Response // @Failure 200 {object} controller.Response
// @Router /messages [get] // @Router /messages [get]
func GetVisitorMessage(c *gin.Context) { func GetVisitorMessage(c *gin.Context) {
visitorId:=c.Query("visitorId") visitorId := c.Query("visitorId")
messages:=models.FindMessageByVisitorId(visitorId) messages := models.FindMessageByVisitorId(visitorId)
result:=make([]map[string]interface{},0) result := make([]map[string]interface{}, 0)
for _,message:=range messages{ for _, message := range messages {
item:=make(map[string]interface{}) item := make(map[string]interface{})
var visitor models.Visitor var visitor models.Visitor
var kefu models.User var kefu models.User
if visitor.Name=="" || kefu.Name==""{ if visitor.Name == "" || kefu.Name == "" {
kefu=models.FindUser(message.KefuId) kefu = models.FindUser(message.KefuId)
visitor=models.FindVisitorByVistorId(message.VisitorId) visitor = models.FindVisitorByVistorId(message.VisitorId)
} }
item["time"]=message.CreatedAt.Format("2006-01-02 15:04:05") item["time"] = message.CreatedAt.Format("2006-01-02 15:04:05")
item["content"]=message.Content item["content"] = message.Content
item["mes_type"]=message.MesType item["mes_type"] = message.MesType
item["visitor_name"]=visitor.Name item["visitor_name"] = visitor.Name
item["visitor_avator"]=visitor.Avator item["visitor_avator"] = visitor.Avator
item["kefu_name"]=kefu.Nickname item["kefu_name"] = kefu.Nickname
item["kefu_avator"]=kefu.Avator item["kefu_avator"] = kefu.Avator
result=append(result,item) result = append(result, item)
} }
models.ReadMessageByVisitorId(visitorId) models.ReadMessageByVisitorId(visitorId)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":result, "result": result,
}) })
} }
func GetVisitorOnlines(c *gin.Context) { func GetVisitorOnlines(c *gin.Context) {
users:=make([]map[string]string,0) users := make([]map[string]string, 0)
for uid,visitor :=range clientList{ for uid, visitor := range clientList {
userInfo := make(map[string]string) userInfo := make(map[string]string)
userInfo["uid"] = uid userInfo["uid"] = uid
userInfo["name"] = visitor.name userInfo["name"] = visitor.name
userInfo["avator"] = visitor.avator userInfo["avator"] = visitor.avator
users=append(users,userInfo) users = append(users, userInfo)
} }
tcps:=make([]string,0) tcps := make([]string, 0)
for ip,_ :=range clientTcpList{ for ip, _ := range clientTcpList {
tcps=append(tcps,ip) tcps = append(tcps, ip)
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"msg": "ok", "msg": "ok",
"result":gin.H{ "result": gin.H{
"ws":users, "ws": users,
"tcp":tcps, "tcp": tcps,
}, },
}) })
} }

@ -9,14 +9,14 @@ import (
"sort" "sort"
) )
func GetCheckWeixinSign(c *gin.Context){ func GetCheckWeixinSign(c *gin.Context) {
token:=models.FindConfig("WeixinToken") token := models.FindConfig("WeixinToken")
signature:=c.Query("signature") signature := c.Query("signature")
timestamp:=c.Query("timestamp") timestamp := c.Query("timestamp")
nonce:=c.Query("nonce") nonce := c.Query("nonce")
echostr:=c.Query("echostr") echostr := c.Query("echostr")
//将token、timestamp、nonce三个参数进行字典序排序 //将token、timestamp、nonce三个参数进行字典序排序
var tempArray = []string{token, timestamp, nonce} var tempArray = []string{token, timestamp, nonce}
sort.Strings(tempArray) sort.Strings(tempArray)
//将三个参数字符串拼接成一个字符串进行sha1加密 //将三个参数字符串拼接成一个字符串进行sha1加密
var sha1String string = "" var sha1String string = ""

@ -6,20 +6,22 @@ import (
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
"github.com/taoshihan1991/imaptool/config" "github.com/taoshihan1991/imaptool/config"
) )
type Mysql struct{
type Mysql struct {
SqlDB *sql.DB SqlDB *sql.DB
Dsn string Dsn string
} }
func NewMysql()*Mysql{
mysql:=config.CreateMysql() func NewMysql() *Mysql {
mysql := config.CreateMysql()
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database) dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database)
return &Mysql{ return &Mysql{
Dsn:dsn, Dsn: dsn,
} }
} }
func (db *Mysql)Ping()error{ func (db *Mysql) Ping() error {
sqlDb, _ := sql.Open("mysql", db.Dsn) sqlDb, _ := sql.Open("mysql", db.Dsn)
db.SqlDB=sqlDb db.SqlDB = sqlDb
return db.SqlDB.Ping() return db.SqlDB.Ping()
} }

@ -6,25 +6,26 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"log" "log"
) )
func CasbinACL(c *gin.Context){
roleId, _ :=c.Get("role_id") func CasbinACL(c *gin.Context) {
sub:=fmt.Sprintf("%s_%d","role",int(roleId.(float64))) roleId, _ := c.Get("role_id")
obj:=c.Request.RequestURI sub := fmt.Sprintf("%s_%d", "role", int(roleId.(float64)))
act:=c.Request.Method obj := c.Request.RequestURI
act := c.Request.Method
e, err := casbin.NewEnforcer("config/model.conf", "config/policy.csv") e, err := casbin.NewEnforcer("config/model.conf", "config/policy.csv")
log.Println(sub,obj,act,err) log.Println(sub, obj, act, err)
ok,err:=e.Enforce(sub,obj,act) ok, err := e.Enforce(sub, obj, act)
if err!=nil{ if err != nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 403, "code": 403,
"msg": "没有权限:"+err.Error(), "msg": "没有权限:" + err.Error(),
}) })
c.Abort() c.Abort()
} }
if !ok{ if !ok {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 403, "code": 403,
"msg": fmt.Sprintf("没有权限:%s,%s,%s",sub,obj,act), "msg": fmt.Sprintf("没有权限:%s,%s,%s", sub, obj, act),
}) })
c.Abort() c.Abort()
} }

@ -5,10 +5,10 @@ import (
"github.com/taoshihan1991/imaptool/models" "github.com/taoshihan1991/imaptool/models"
) )
func Ipblack(c *gin.Context){ func Ipblack(c *gin.Context) {
ip:=c.ClientIP() ip := c.ClientIP()
ipblack:=models.FindIp(ip) ipblack := models.FindIp(ip)
if ipblack.IP!=""{ if ipblack.IP != "" {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "IP已被加入黑名单", "msg": "IP已被加入黑名单",

@ -5,7 +5,8 @@ import (
"github.com/taoshihan1991/imaptool/tools" "github.com/taoshihan1991/imaptool/tools"
"time" "time"
) )
func JwtPageMiddleware(c *gin.Context){
func JwtPageMiddleware(c *gin.Context) {
//暂时不处理 //暂时不处理
//token := c.Query("token") //token := c.Query("token")
//userinfo := tools.ParseToken(token) //userinfo := tools.ParseToken(token)
@ -14,10 +15,10 @@ func JwtPageMiddleware(c *gin.Context){
// c.Abort() // c.Abort()
//} //}
} }
func JwtApiMiddleware(c *gin.Context){ func JwtApiMiddleware(c *gin.Context) {
token := c.GetHeader("token") token := c.GetHeader("token")
userinfo := tools.ParseToken(token) userinfo := tools.ParseToken(token)
if userinfo == nil||userinfo["name"]==nil||userinfo["create_time"]==nil { if userinfo == nil || userinfo["name"] == nil || userinfo["create_time"] == nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 400, "code": 400,
"msg": "验证失败", "msg": "验证失败",
@ -25,21 +26,21 @@ func JwtApiMiddleware(c *gin.Context){
c.Abort() c.Abort()
return return
} }
createTime:=int64(userinfo["create_time"].(float64)) createTime := int64(userinfo["create_time"].(float64))
var expire int64=24*60*60 var expire int64 = 24 * 60 * 60
nowTime:=time.Now().Unix(); nowTime := time.Now().Unix()
if (nowTime-createTime) >=expire{ if (nowTime - createTime) >= expire {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 401, "code": 401,
"msg": "token失效", "msg": "token失效",
}) })
c.Abort() c.Abort()
} }
c.Set("user",userinfo["name"]) c.Set("user", userinfo["name"])
//log.Println(userinfo) //log.Println(userinfo)
//if userinfo["type"]=="kefu"{ //if userinfo["type"]=="kefu"{
c.Set("kefu_id",userinfo["kefu_id"]) c.Set("kefu_id", userinfo["kefu_id"])
c.Set("kefu_name",userinfo["name"]) c.Set("kefu_name", userinfo["name"])
c.Set("role_id",userinfo["role_id"]) c.Set("role_id", userinfo["role_id"])
//} //}
} }

@ -4,11 +4,10 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func SetLanguage(c *gin.Context){ func SetLanguage(c *gin.Context) {
lang := c.Query("lang") lang := c.Query("lang")
if lang == "" ||lang!="cn"{ if lang == "" || lang != "cn" {
lang = "en" lang = "en"
} }
c.Set("lang",lang) c.Set("lang", lang)
} }

@ -6,45 +6,44 @@ import (
"strings" "strings"
) )
func RbacAuth(c *gin.Context){ func RbacAuth(c *gin.Context) {
roleId, _ :=c.Get("role_id") roleId, _ := c.Get("role_id")
role:=models.FindRole(roleId) role := models.FindRole(roleId)
var methodFlag bool var methodFlag bool
rPaths:=strings.Split(c.Request.RequestURI,"?") rPaths := strings.Split(c.Request.RequestURI, "?")
if role.Method!="*"{ if role.Method != "*" {
methods:=strings.Split(role.Method,",") methods := strings.Split(role.Method, ",")
for _,m:=range methods{ for _, m := range methods {
if c.Request.Method==m{ if c.Request.Method == m {
methodFlag=true methodFlag = true
break break
} }
} }
if !methodFlag{ if !methodFlag {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 403, "code": 403,
"msg": "没有权限:"+c.Request.Method+","+rPaths[0], "msg": "没有权限:" + c.Request.Method + "," + rPaths[0],
}) })
c.Abort() c.Abort()
return return
} }
} }
var flag bool var flag bool
if role.Path!="*"{ if role.Path != "*" {
paths:=strings.Split(role.Path,",") paths := strings.Split(role.Path, ",")
for _,p:=range paths{ for _, p := range paths {
if rPaths[0]==p{ if rPaths[0] == p {
flag=true flag = true
break break
} }
} }
if !flag{ if !flag {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 403, "code": 403,
"msg": "没有权限:"+rPaths[0], "msg": "没有权限:" + rPaths[0],
}) })
c.Abort() c.Abort()
return return
} }
} }
} }

@ -1,29 +1,31 @@
package models package models
var CustomConfigs []Config var CustomConfigs []Config
type Config struct{
ID uint `gorm:"primary_key" json:"id"` type Config struct {
ConfName string `json:"conf_name"` ID uint `gorm:"primary_key" json:"id"`
ConfKey string `json:"conf_key"` ConfName string `json:"conf_name"`
ConfKey string `json:"conf_key"`
ConfValue string `json:"conf_value"` ConfValue string `json:"conf_value"`
} }
func UpdateConfig(key string,value string){
c:=&Config{ func UpdateConfig(key string, value string) {
c := &Config{
ConfValue: value, ConfValue: value,
} }
DB.Model(c).Where("conf_key = ?",key).Update(c) DB.Model(c).Where("conf_key = ?", key).Update(c)
} }
func FindConfigs()[]Config{ func FindConfigs() []Config {
var config []Config var config []Config
DB.Find(&config) DB.Find(&config)
return config return config
} }
func InitConfig(){ func InitConfig() {
CustomConfigs=FindConfigs() CustomConfigs = FindConfigs()
} }
func FindConfig(key string)string{ func FindConfig(key string) string {
for _,config:=range CustomConfigs{ for _, config := range CustomConfigs {
if key==config.ConfKey{ if key == config.ConfKey {
return config.ConfValue return config.ConfValue
} }
} }

@ -2,48 +2,50 @@ package models
import "time" import "time"
type Ipblack struct{ type Ipblack struct {
ID uint `gorm:"primary_key" json:"id"` ID uint `gorm:"primary_key" json:"id"`
IP string `json:"ip"` IP string `json:"ip"`
KefuId string `json:"kefu_id"` KefuId string `json:"kefu_id"`
CreateAt time.Time `json:"create_at"` CreateAt time.Time `json:"create_at"`
} }
func CreateIpblack(ip string,kefuId string)uint{
black:=&Ipblack{ func CreateIpblack(ip string, kefuId string) uint {
IP:ip, black := &Ipblack{
KefuId: kefuId, IP: ip,
KefuId: kefuId,
CreateAt: time.Now(), CreateAt: time.Now(),
} }
DB.Create(black) DB.Create(black)
return black.ID return black.ID
} }
func DeleteIpblackByIp(ip string){ func DeleteIpblackByIp(ip string) {
DB.Where("ip = ?",ip).Delete(Ipblack{}) DB.Where("ip = ?", ip).Delete(Ipblack{})
} }
func FindIp(ip string)Ipblack{ func FindIp(ip string) Ipblack {
var ipblack Ipblack var ipblack Ipblack
DB.Where("ip = ?", ip).First(&ipblack) DB.Where("ip = ?", ip).First(&ipblack)
return ipblack return ipblack
} }
func FindIps(query interface{},args []interface{},page uint,pagesize uint)[]Ipblack{ func FindIps(query interface{}, args []interface{}, page uint, pagesize uint) []Ipblack {
offset:=(page-1)*pagesize offset := (page - 1) * pagesize
if offset<0{ if offset < 0 {
offset=0 offset = 0
} }
var ipblacks []Ipblack var ipblacks []Ipblack
if query!=nil{ if query != nil {
DB.Where(query, args...).Offset(offset).Limit(pagesize).Find(&ipblacks) DB.Where(query, args...).Offset(offset).Limit(pagesize).Find(&ipblacks)
}else{ } else {
DB.Offset(offset).Limit(pagesize).Find(&ipblacks) DB.Offset(offset).Limit(pagesize).Find(&ipblacks)
} }
return ipblacks return ipblacks
} }
//查询条数 //查询条数
func CountIps(query interface{},args []interface{})uint{ func CountIps(query interface{}, args []interface{}) uint {
var count uint var count uint
if query!=nil{ if query != nil {
DB.Model(&Visitor{}).Where(query,args...).Count(&count) DB.Model(&Visitor{}).Where(query, args...).Count(&count)
}else{ } else {
DB.Model(&Visitor{}).Count(&count) DB.Model(&Visitor{}).Count(&count)
} }
return count return count

@ -1,42 +1,47 @@
package models package models
type Message struct { type Message struct {
Model Model
KefuId string `json:"kefu_id"` KefuId string `json:"kefu_id"`
VisitorId string `json:"visitor_id"` VisitorId string `json:"visitor_id"`
Content string `json:"content"` Content string `json:"content"`
MesType string `json:"mes_type"` MesType string `json:"mes_type"`
Status string `json:"status"` Status string `json:"status"`
} }
func CreateMessage(kefu_id string,visitor_id string,content string,mes_type string){
v:=&Message{ func CreateMessage(kefu_id string, visitor_id string, content string, mes_type string) {
KefuId: kefu_id, v := &Message{
KefuId: kefu_id,
VisitorId: visitor_id, VisitorId: visitor_id,
Content: content, Content: content,
MesType: mes_type, MesType: mes_type,
Status: "unread", Status: "unread",
} }
DB.Create(v) DB.Create(v)
} }
func FindMessageByVisitorId(visitor_id string)[]Message{ func FindMessageByVisitorId(visitor_id string) []Message {
var messages []Message var messages []Message
DB.Where("visitor_id=?",visitor_id).Order("id asc").Find(&messages) DB.Where("visitor_id=?", visitor_id).Order("id asc").Find(&messages)
return messages return messages
} }
//修改消息状态 //修改消息状态
func ReadMessageByVisitorId(visitor_id string){ func ReadMessageByVisitorId(visitor_id string) {
message:=&Message{ message := &Message{
Status:"read", Status: "read",
} }
DB.Model(&message).Where("visitor_id=?",visitor_id).Update(message) DB.Model(&message).Where("visitor_id=?", visitor_id).Update(message)
} }
//获取未读数 //获取未读数
func FindUnreadMessageNumByVisitorId(visitor_id string)uint{ func FindUnreadMessageNumByVisitorId(visitor_id string) uint {
var count uint var count uint
DB.Where("visitor_id=? and status=?",visitor_id,"unread").Count(&count) DB.Where("visitor_id=? and status=?", visitor_id, "unread").Count(&count)
return count return count
} }
//查询条数 //查询条数
func CountMessage()uint{ func CountMessage() uint {
var count uint var count uint
DB.Model(&Message{}).Count(&count) DB.Model(&Message{}).Count(&count)
return count return count

@ -6,19 +6,22 @@ import (
"github.com/taoshihan1991/imaptool/config" "github.com/taoshihan1991/imaptool/config"
"time" "time"
) )
var DB *gorm.DB var DB *gorm.DB
type Model struct { type Model struct {
ID uint `gorm:"primary_key" json:"id"` ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `sql:"index" json:"deleted_at"` DeletedAt *time.Time `sql:"index" json:"deleted_at"`
} }
func init(){
mysql:=config.CreateMysql() func init() {
mysql := config.CreateMysql()
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database) dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database)
var err error var err error
DB,err=gorm.Open("mysql",dsn) DB, err = gorm.Open("mysql", dsn)
if err!=nil{ if err != nil {
panic("数据库连接失败!") panic("数据库连接失败!")
} }
DB.SingularTable(true) DB.SingularTable(true)
@ -28,7 +31,7 @@ func init(){
InitConfig() InitConfig()
} }
func Execute(sql string){ func Execute(sql string) {
DB.Exec(sql) DB.Exec(sql)
} }
func CloseDB() { func CloseDB() {

@ -1,25 +1,27 @@
package models package models
type Role struct{
Id string `json:"role_id"` type Role struct {
Name string `json:"role_name"` Id string `json:"role_id"`
Name string `json:"role_name"`
Method string `json:"method"` Method string `json:"method"`
Path string `json:"path"` Path string `json:"path"`
} }
func FindRoles()[]Role{
func FindRoles() []Role {
var roles []Role var roles []Role
DB.Order("id desc").Find(&roles) DB.Order("id desc").Find(&roles)
return roles return roles
} }
func FindRole(id interface{})Role{ func FindRole(id interface{}) Role {
var role Role var role Role
DB.Where("id = ?", id).First(&role) DB.Where("id = ?", id).First(&role)
return role return role
} }
func SaveRole(id string,name string,method string,path string){ func SaveRole(id string, name string, method string, path string) {
role:=&Role{ role := &Role{
Method: method, Method: method,
Name: name, Name: name,
Path: path, Path: path,
} }
DB.Model(role).Where("id=?",id).Update(role) DB.Model(role).Where("id=?", id).Update(role)
} }

@ -4,23 +4,24 @@ import (
"strconv" "strconv"
) )
type User_role struct{ type User_role struct {
ID uint `gorm:"primary_key" json:"id"` ID uint `gorm:"primary_key" json:"id"`
UserId string `json:"user_id"` UserId string `json:"user_id"`
RoleId uint `json:"role_id"` RoleId uint `json:"role_id"`
} }
func FindRoleByUserId(userId interface{})User_role{
func FindRoleByUserId(userId interface{}) User_role {
var uRole User_role var uRole User_role
DB.Where("user_id = ?", userId).First(&uRole) DB.Where("user_id = ?", userId).First(&uRole)
return uRole return uRole
} }
func CreateUserRole(userId uint,roleId uint){ func CreateUserRole(userId uint, roleId uint) {
uRole:=&User_role{ uRole := &User_role{
UserId:strconv.Itoa(int(userId)), UserId: strconv.Itoa(int(userId)),
RoleId: roleId, RoleId: roleId,
} }
DB.Create(uRole) DB.Create(uRole)
} }
func DeleteRoleByUserId(userId interface{}){ func DeleteRoleByUserId(userId interface{}) {
DB.Where("user_id = ?", userId).Delete(User_role{}) DB.Where("user_id = ?", userId).Delete(User_role{})
} }

@ -3,55 +3,57 @@ package models
import ( import (
_ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/mysql"
) )
type User struct { type User struct {
Model Model
Name string `json:"name"` Name string `json:"name"`
Password string `json:"password"` Password string `json:"password"`
Nickname string `json:"nickname"` Nickname string `json:"nickname"`
Avator string `json:"avator"` Avator string `json:"avator"`
RoleName string `json:"role_name" sql:"-"` RoleName string `json:"role_name" sql:"-"`
RoleId string `json:"role_id" sql:"-"` RoleId string `json:"role_id" sql:"-"`
} }
func CreateUser(name string,password string,avator string,nickname string)uint{
user:=&User{ func CreateUser(name string, password string, avator string, nickname string) uint {
Name:name, user := &User{
Name: name,
Password: password, Password: password,
Avator:avator, Avator: avator,
Nickname: nickname, Nickname: nickname,
} }
DB.Create(user) DB.Create(user)
return user.ID return user.ID
} }
func UpdateUser(id string,name string,password string,avator string,nickname string){ func UpdateUser(id string, name string, password string, avator string, nickname string) {
user:=&User{ user := &User{
Name:name, Name: name,
Avator:avator, Avator: avator,
Nickname: nickname, Nickname: nickname,
} }
if password!=""{ if password != "" {
user.Password=password user.Password = password
} }
DB.Model(&User{}).Where("id = ?",id).Update(user) DB.Model(&User{}).Where("id = ?", id).Update(user)
} }
func FindUser(username string)User{ func FindUser(username string) User {
var user User var user User
DB.Where("name = ?", username).First(&user) DB.Where("name = ?", username).First(&user)
return user return user
} }
func FindUserById(id interface{})User{ func FindUserById(id interface{}) User {
var user User var user User
DB.Select("user.*,role.name role_name,role.id role_id").Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").Where("user.id = ?", id).First(&user) DB.Select("user.*,role.name role_name,role.id role_id").Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").Where("user.id = ?", id).First(&user)
return user return user
} }
func DeleteUserById(id string){ func DeleteUserById(id string) {
DB.Where("id = ?",id).Delete(User{}) DB.Where("id = ?", id).Delete(User{})
} }
func FindUsers()[]User{ func FindUsers() []User {
var users []User var users []User
DB.Select("user.*,role.name role_name").Joins("left join user_role on user.id=user_role.user_id").Joins("left join role on user_role.role_id=role.id").Order("user.id desc").Find(&users) DB.Select("user.*,role.name role_name").Joins("left join user_role on user.id=user_role.user_id").Joins("left join role on user_role.role_id=role.id").Order("user.id desc").Find(&users)
return users return users
} }
func FindUserRole(query interface{},id interface{})User{ func FindUserRole(query interface{}, id interface{}) User {
var user User var user User
DB.Select(query).Where("user.id = ?", id).Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").First(&user) DB.Select(query).Where("user.id = ?", id).Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").First(&user)
return user return user

@ -2,88 +2,89 @@ package models
type Visitor struct { type Visitor struct {
Model Model
Name string `json:"name"` Name string `json:"name"`
Avator string `json:"avator"` Avator string `json:"avator"`
SourceIp string `json:"source_ip"` SourceIp string `json:"source_ip"`
ToId string `json:"to_id"` ToId string `json:"to_id"`
VisitorId string `json:"visitor_id"` VisitorId string `json:"visitor_id"`
Status uint `json:"status"` Status uint `json:"status"`
Refer string `json:"refer"` Refer string `json:"refer"`
City string `json:"city"` City string `json:"city"`
ClientIp string `json:"client_ip"` ClientIp string `json:"client_ip"`
} }
func CreateVisitor(name string,avator string,sourceIp string,toId string,visitorId string,refer string,city string,clientIp string){
old:=FindVisitorByVistorId(visitorId) func CreateVisitor(name string, avator string, sourceIp string, toId string, visitorId string, refer string, city string, clientIp string) {
if old.Name!=""{ old := FindVisitorByVistorId(visitorId)
if old.Name != "" {
//更新状态上线 //更新状态上线
UpdateVisitor(visitorId,1,clientIp,sourceIp,refer) UpdateVisitor(visitorId, 1, clientIp, sourceIp, refer)
return return
} }
v:=&Visitor{ v := &Visitor{
Name:name, Name: name,
Avator: avator, Avator: avator,
SourceIp:sourceIp, SourceIp: sourceIp,
ToId:toId, ToId: toId,
VisitorId: visitorId, VisitorId: visitorId,
Status:1, Status: 1,
Refer:refer, Refer: refer,
City:city, City: city,
ClientIp:clientIp, ClientIp: clientIp,
} }
DB.Create(v) DB.Create(v)
} }
func FindVisitorByVistorId(visitorId string)Visitor{ func FindVisitorByVistorId(visitorId string) Visitor {
var v Visitor var v Visitor
DB.Where("visitor_id = ?", visitorId).First(&v) DB.Where("visitor_id = ?", visitorId).First(&v)
return v return v
} }
func FindVisitors(page uint,pagesize uint)[]Visitor{ func FindVisitors(page uint, pagesize uint) []Visitor {
offset:=(page-1)*pagesize offset := (page - 1) * pagesize
if offset<0{ if offset < 0 {
offset=0 offset = 0
} }
var visitors []Visitor var visitors []Visitor
DB.Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors) DB.Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
return visitors return visitors
} }
func FindVisitorsByKefuId(page uint,pagesize uint,kefuId string)[]Visitor{ func FindVisitorsByKefuId(page uint, pagesize uint, kefuId string) []Visitor {
offset:=(page-1)*pagesize offset := (page - 1) * pagesize
if offset<0{ if offset < 0 {
offset=0 offset = 0
} }
var visitors []Visitor var visitors []Visitor
DB.Where("to_id=?",kefuId).Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors) DB.Where("to_id=?", kefuId).Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
return visitors return visitors
} }
func FindVisitorsOnline()[]Visitor{ func FindVisitorsOnline() []Visitor {
var visitors []Visitor var visitors []Visitor
DB.Where("status = ?",1).Find(&visitors) DB.Where("status = ?", 1).Find(&visitors)
return visitors return visitors
} }
func UpdateVisitorStatus(visitorId string,status uint){ func UpdateVisitorStatus(visitorId string, status uint) {
visitor:=Visitor{ visitor := Visitor{}
} DB.Model(&visitor).Where("visitor_id = ?", visitorId).Update("status", status)
DB.Model(&visitor).Where("visitor_id = ?",visitorId).Update("status", status)
} }
func UpdateVisitor(visitorId string,status uint,clientIp string,sourceIp string,refer string){ func UpdateVisitor(visitorId string, status uint, clientIp string, sourceIp string, refer string) {
visitor:=&Visitor{ visitor := &Visitor{
Status: status, Status: status,
ClientIp: clientIp, ClientIp: clientIp,
SourceIp: sourceIp, SourceIp: sourceIp,
Refer: refer, Refer: refer,
} }
DB.Model(visitor).Where("visitor_id = ?",visitorId).Update(visitor) DB.Model(visitor).Where("visitor_id = ?", visitorId).Update(visitor)
} }
//查询条数 //查询条数
func CountVisitors()uint{ func CountVisitors() uint {
var count uint var count uint
DB.Model(&Visitor{}).Count(&count) DB.Model(&Visitor{}).Count(&count)
return count return count
} }
//查询条数 //查询条数
func CountVisitorsByKefuId(kefuId string)uint{ func CountVisitorsByKefuId(kefuId string) uint {
var count uint var count uint
DB.Model(&Visitor{}).Where("to_id=?",kefuId).Count(&count) DB.Model(&Visitor{}).Where("to_id=?", kefuId).Count(&count)
return count return count
} }

@ -3,34 +3,35 @@ package models
import "time" import "time"
type Welcome struct { type Welcome struct {
ID uint `gorm:"primary_key" json:"id"` ID uint `gorm:"primary_key" json:"id"`
UserId string `json:"user_id"` UserId string `json:"user_id"`
Content string `json:"content"` Content string `json:"content"`
IsDefault uint `json:"is_default"` IsDefault uint `json:"is_default"`
Ctime time.Time `json:"ctime"` Ctime time.Time `json:"ctime"`
} }
func CreateWelcome(userId string,content string)uint{
if userId==""||content==""{ func CreateWelcome(userId string, content string) uint {
if userId == "" || content == "" {
return 0 return 0
} }
w:=&Welcome{ w := &Welcome{
UserId: userId, UserId: userId,
Content: content, Content: content,
Ctime: time.Now(), Ctime: time.Now(),
} }
DB.Create(w) DB.Create(w)
return w.ID return w.ID
} }
func FindWelcomeByUserId(userId interface{})Welcome{ func FindWelcomeByUserId(userId interface{}) Welcome {
var w Welcome var w Welcome
DB.Where("user_id = ? and is_default=?", userId,1).First(&w) DB.Where("user_id = ? and is_default=?", userId, 1).First(&w)
return w return w
} }
func FindWelcomesByUserId(userId interface{})[]Welcome{ func FindWelcomesByUserId(userId interface{}) []Welcome {
var w []Welcome var w []Welcome
DB.Where("user_id = ?", userId).Find(&w) DB.Where("user_id = ?", userId).Find(&w)
return w return w
} }
func DeleteWelcome(userId interface{},id string){ func DeleteWelcome(userId interface{}, id string) {
DB.Where("user_id = ? and id = ?", userId,id).Delete(Welcome{}) DB.Where("user_id = ? and id = ?", userId, id).Delete(Welcome{})
} }

@ -6,56 +6,56 @@ import (
"github.com/taoshihan1991/imaptool/middleware" "github.com/taoshihan1991/imaptool/middleware"
) )
func InitApiRouter(engine *gin.Engine){ func InitApiRouter(engine *gin.Engine) {
//首页 //首页
engine.GET("/", controller.Index) engine.GET("/", controller.Index)
engine.POST("/check", controller.LoginCheckPass) engine.POST("/check", controller.LoginCheckPass)
engine.POST("/check_auth",middleware.JwtApiMiddleware, controller.MainCheckAuth) engine.POST("/check_auth", middleware.JwtApiMiddleware, controller.MainCheckAuth)
//前后聊天 //前后聊天
engine.GET("/chat_server",middleware.Ipblack, controller.NewChatServer) engine.GET("/chat_server", middleware.Ipblack, controller.NewChatServer)
//获取消息 //获取消息
engine.GET("/messages", controller.GetVisitorMessage) engine.GET("/messages", controller.GetVisitorMessage)
engine.GET("/message_notice", controller.SendVisitorNotice) engine.GET("/message_notice", controller.SendVisitorNotice)
//发送单条消息 //发送单条消息
engine.POST("/message",middleware.Ipblack,controller.SendMessage) engine.POST("/message", middleware.Ipblack, controller.SendMessage)
//上传文件 //上传文件
engine.POST("/uploadimg",middleware.Ipblack,controller.UploadImg) engine.POST("/uploadimg", middleware.Ipblack, controller.UploadImg)
//获取未读消息数 //获取未读消息数
engine.GET("/message_status",controller.GetVisitorMessage) engine.GET("/message_status", controller.GetVisitorMessage)
//设置消息已读 //设置消息已读
engine.POST("/message_status",controller.GetVisitorMessage) engine.POST("/message_status", controller.GetVisitorMessage)
//获取客服信息 //获取客服信息
engine.GET("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuInfo) engine.GET("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuInfo)
engine.GET("/kefuinfo_setting",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuInfoSetting) engine.GET("/kefuinfo_setting", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuInfoSetting)
engine.POST("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.PostKefuInfo) engine.POST("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostKefuInfo)
engine.DELETE("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.DeleteKefuInfo) engine.DELETE("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.DeleteKefuInfo)
engine.GET("/kefulist",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuList) engine.GET("/kefulist", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuList)
//角色列表 //角色列表
engine.GET("/roles",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetRoleList) engine.GET("/roles", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetRoleList)
engine.POST("/role",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.PostRole) engine.POST("/role", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostRole)
//邮件夹列表 //邮件夹列表
engine.GET("/folders", controller.GetFolders) engine.GET("/folders", controller.GetFolders)
engine.GET("/mysql",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.MysqlGetConf) engine.GET("/mysql", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.MysqlGetConf)
engine.POST("/mysql",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.MysqlSetConf) engine.POST("/mysql", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.MysqlSetConf)
engine.GET("/visitors_online", controller.GetVisitorOnlines) engine.GET("/visitors_online", controller.GetVisitorOnlines)
engine.GET("/clear_online_tcp", controller.DeleteOnlineTcp) engine.GET("/clear_online_tcp", controller.DeleteOnlineTcp)
engine.POST("/visitor_login",middleware.Ipblack,controller.PostVisitorLogin) engine.POST("/visitor_login", middleware.Ipblack, controller.PostVisitorLogin)
engine.POST("/visitor",controller.PostVisitor) engine.POST("/visitor", controller.PostVisitor)
engine.GET("/visitor",middleware.JwtApiMiddleware, controller.GetVisitor) engine.GET("/visitor", middleware.JwtApiMiddleware, controller.GetVisitor)
engine.GET("/visitors",middleware.JwtApiMiddleware, controller.GetVisitors) engine.GET("/visitors", middleware.JwtApiMiddleware, controller.GetVisitors)
engine.GET("/statistics",middleware.JwtApiMiddleware, controller.GetStatistics) engine.GET("/statistics", middleware.JwtApiMiddleware, controller.GetStatistics)
//前台接口 //前台接口
engine.GET("/notice",middleware.SetLanguage, controller.GetNotice) engine.GET("/notice", middleware.SetLanguage, controller.GetNotice)
engine.POST("/notice",middleware.JwtApiMiddleware, controller.PostNotice) engine.POST("/notice", middleware.JwtApiMiddleware, controller.PostNotice)
engine.DELETE("/notice",middleware.JwtApiMiddleware, controller.DelNotice) engine.DELETE("/notice", middleware.JwtApiMiddleware, controller.DelNotice)
engine.GET("/notices",middleware.JwtApiMiddleware, controller.GetNotices) engine.GET("/notices", middleware.JwtApiMiddleware, controller.GetNotices)
engine.POST("/ipblack",middleware.JwtApiMiddleware,controller.PostIpblack) engine.POST("/ipblack", middleware.JwtApiMiddleware, controller.PostIpblack)
engine.DELETE("/ipblack",middleware.JwtApiMiddleware,controller.DelIpblack) engine.DELETE("/ipblack", middleware.JwtApiMiddleware, controller.DelIpblack)
engine.GET("/ipblacks_all",middleware.JwtApiMiddleware,controller.GetIpblacks) engine.GET("/ipblacks_all", middleware.JwtApiMiddleware, controller.GetIpblacks)
engine.GET("/configs",middleware.JwtApiMiddleware,middleware.RbacAuth,controller.GetConfigs) engine.GET("/configs", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetConfigs)
engine.POST("/config",middleware.JwtApiMiddleware,middleware.RbacAuth,controller.PostConfig) engine.POST("/config", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostConfig)
//微信接口 //微信接口
engine.GET("/micro_program",controller.GetCheckWeixinSign) engine.GET("/micro_program", controller.GetCheckWeixinSign)
} }

@ -6,21 +6,21 @@ import (
"github.com/taoshihan1991/imaptool/tmpl" "github.com/taoshihan1991/imaptool/tmpl"
) )
func InitViewRouter(engine *gin.Engine){ func InitViewRouter(engine *gin.Engine) {
engine.GET("/index", tmpl.PageIndex) engine.GET("/index", tmpl.PageIndex)
engine.GET("/login", tmpl.PageLogin) engine.GET("/login", tmpl.PageLogin)
engine.GET("/chat_page",middleware.SetLanguage, tmpl.PageChat) engine.GET("/chat_page", middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatIndex",middleware.SetLanguage, tmpl.PageChat) engine.GET("/chatIndex", middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatKfIndex",tmpl.PageKfChat) engine.GET("/chatKfIndex", tmpl.PageKfChat)
engine.GET("/main",middleware.JwtPageMiddleware,tmpl.PageMain) engine.GET("/main", middleware.JwtPageMiddleware, tmpl.PageMain)
engine.GET("/chat_main",middleware.JwtPageMiddleware,tmpl.PageChatMain) engine.GET("/chat_main", middleware.JwtPageMiddleware, tmpl.PageChatMain)
engine.GET("/setting", tmpl.PageSetting) engine.GET("/setting", tmpl.PageSetting)
engine.GET("/setting_mysql", tmpl.PageSettingMysql) engine.GET("/setting_mysql", tmpl.PageSettingMysql)
engine.GET("/setting_welcome", tmpl.PageSettingWelcome) engine.GET("/setting_welcome", tmpl.PageSettingWelcome)
engine.GET("/setting_deploy", tmpl.PageSettingDeploy) engine.GET("/setting_deploy", tmpl.PageSettingDeploy)
engine.GET("/setting_kefu_list",tmpl.PageKefuList) engine.GET("/setting_kefu_list", tmpl.PageKefuList)
engine.GET("/setting_ipblack",tmpl.PageIpblack) engine.GET("/setting_ipblack", tmpl.PageIpblack)
engine.GET("/setting_config",tmpl.PageConfig) engine.GET("/setting_config", tmpl.PageConfig)
engine.GET("/mail_list", tmpl.PageMailList) engine.GET("/mail_list", tmpl.PageMailList)
engine.GET("/roles_list", tmpl.PageRoleList) engine.GET("/roles_list", tmpl.PageRoleList)
engine.GET("/webjs", tmpl.PageWebJs) engine.GET("/webjs", tmpl.PageWebJs)

@ -9,26 +9,26 @@ import (
//咨询界面 //咨询界面
func PageChat(c *gin.Context) { func PageChat(c *gin.Context) {
kefuId := c.Query("kefu_id") kefuId := c.Query("kefu_id")
lang,_ := c.Get("lang") lang, _ := c.Get("lang")
language:=config.CreateLanguage(lang.(string)) language := config.CreateLanguage(lang.(string))
refer := c.Query("refer") refer := c.Query("refer")
if refer==""{ if refer == "" {
refer=c.Request.Referer() refer = c.Request.Referer()
} }
c.HTML(http.StatusOK, "chat_page.html", gin.H{ c.HTML(http.StatusOK, "chat_page.html", gin.H{
"KEFU_ID":kefuId, "KEFU_ID": kefuId,
"SendBtn":language.Send, "SendBtn": language.Send,
"Lang":lang.(string), "Lang": lang.(string),
"Refer":refer, "Refer": refer,
}) })
} }
func PageKfChat(c *gin.Context) { func PageKfChat(c *gin.Context) {
kefuId := c.Query("kefu_id") kefuId := c.Query("kefu_id")
visitorId:=c.Query("visitor_id") visitorId := c.Query("visitor_id")
token:=c.Query("token") token := c.Query("token")
c.HTML(http.StatusOK, "chat_kf_page.html", gin.H{ c.HTML(http.StatusOK, "chat_kf_page.html", gin.H{
"KefuId":kefuId, "KefuId": kefuId,
"VisitorId":visitorId, "VisitorId": visitorId,
"Token":token, "Token": token,
}) })
} }

@ -41,23 +41,24 @@ func (obj *CommonHtml) Display(file string, data interface{}) {
t, _ := template.New(file).Parse(main) t, _ := template.New(file).Parse(main)
t.Execute(obj.Rw, data) t.Execute(obj.Rw, data)
} }
//首页 //首页
func PageIndex(c *gin.Context) { func PageIndex(c *gin.Context) {
lang := c.Query("lang") lang := c.Query("lang")
if lang == "" ||lang!="cn"{ if lang == "" || lang != "cn" {
lang = "en" lang = "en"
} }
language:=config.CreateLanguage(lang) language := config.CreateLanguage(lang)
c.HTML(http.StatusOK, "index.html", gin.H{ c.HTML(http.StatusOK, "index.html", gin.H{
"Copyright":language.WebCopyRight, "Copyright": language.WebCopyRight,
"WebDesc":language.MainIntro, "WebDesc": language.MainIntro,
"SubIntro":language.IndexSubIntro, "SubIntro": language.IndexSubIntro,
"Document":language.IndexDocument, "Document": language.IndexDocument,
"VisitorBtn":language.IndexVisitors, "VisitorBtn": language.IndexVisitors,
"AgentBtn":language.IndexAgent, "AgentBtn": language.IndexAgent,
"OnlineChat":language.IndexOnlineChat, "OnlineChat": language.IndexOnlineChat,
"IndexSend":language.Send, "IndexSend": language.Send,
"Lang":lang, "Lang": lang,
}) })
} }

@ -9,6 +9,3 @@ import (
func PageLogin(c *gin.Context) { func PageLogin(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil) c.HTML(http.StatusOK, "login.html", nil)
} }

@ -4,68 +4,75 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
) )
//设置界面 //设置界面
func PageSetting(c *gin.Context) { func PageSetting(c *gin.Context) {
c.HTML(http.StatusOK, "setting.html", gin.H{ c.HTML(http.StatusOK, "setting.html", gin.H{
"tab_index":"1-1", "tab_index": "1-1",
"action":"setting", "action": "setting",
}) })
} }
//设置欢迎 //设置欢迎
func PageSettingWelcome(c *gin.Context) { func PageSettingWelcome(c *gin.Context) {
c.HTML(http.StatusOK, "setting_welcome.html", gin.H{ c.HTML(http.StatusOK, "setting_welcome.html", gin.H{
"tab_index":"1-2", "tab_index": "1-2",
"action":"setting_welcome", "action": "setting_welcome",
}) })
} }
//设置mysql //设置mysql
func PageSettingMysql(c *gin.Context) { func PageSettingMysql(c *gin.Context) {
c.HTML(http.StatusOK, "setting_mysql.html", gin.H{ c.HTML(http.StatusOK, "setting_mysql.html", gin.H{
"tab_index":"2-4", "tab_index": "2-4",
"action":"setting_mysql", "action": "setting_mysql",
}) })
} }
//设置部署 //设置部署
func PageSettingDeploy(c *gin.Context) { func PageSettingDeploy(c *gin.Context) {
c.HTML(http.StatusOK, "setting_deploy.html", gin.H{ c.HTML(http.StatusOK, "setting_deploy.html", gin.H{
"tab_index":"2-5", "tab_index": "2-5",
"action":"setting_deploy", "action": "setting_deploy",
}) })
} }
//前台js部署 //前台js部署
func PageWebJs(c *gin.Context){ func PageWebJs(c *gin.Context) {
c.HTML(http.StatusOK, "chat_web.js",nil) c.HTML(http.StatusOK, "chat_web.js", nil)
} }
//前台css部署 //前台css部署
func PageWebCss(c *gin.Context){ func PageWebCss(c *gin.Context) {
c.HTML(http.StatusOK, "chat_web.css",nil) c.HTML(http.StatusOK, "chat_web.css", nil)
} }
func PageKefuList(c *gin.Context) { func PageKefuList(c *gin.Context) {
c.HTML(http.StatusOK, "setting_kefu_list.html", gin.H{ c.HTML(http.StatusOK, "setting_kefu_list.html", gin.H{
"tab_index":"3-2", "tab_index": "3-2",
"action":"setting_kefu_list", "action": "setting_kefu_list",
}) })
} }
//角色列表 //角色列表
func PageRoleList(c *gin.Context) { func PageRoleList(c *gin.Context) {
c.HTML(http.StatusOK, "setting_role_list.html", gin.H{ c.HTML(http.StatusOK, "setting_role_list.html", gin.H{
"tab_index":"3-1", "tab_index": "3-1",
"action":"roles_list", "action": "roles_list",
}) })
} }
//角色列表 //角色列表
func PageIpblack(c *gin.Context) { func PageIpblack(c *gin.Context) {
c.HTML(http.StatusOK, "setting_ipblack.html", gin.H{ c.HTML(http.StatusOK, "setting_ipblack.html", gin.H{
"tab_index":"4-5", "tab_index": "4-5",
"action":"setting_ipblack", "action": "setting_ipblack",
}) })
} }
//配置项列表 //配置项列表
func PageConfig(c *gin.Context) { func PageConfig(c *gin.Context) {
c.HTML(http.StatusOK, "setting_config.html", gin.H{ c.HTML(http.StatusOK, "setting_config.html", gin.H{
"tab_index":"4-6", "tab_index": "4-6",
"action":"setting_config", "action": "setting_config",
}) })
} }

@ -5,8 +5,8 @@ import (
"net/http" "net/http"
) )
func Get(url string)string{ func Get(url string) string {
res, err :=http.Get(url) res, err := http.Get(url)
if err != nil { if err != nil {
return "" return ""
} }

@ -4,13 +4,13 @@ import (
"github.com/ipipdotnet/ipdb-go" "github.com/ipipdotnet/ipdb-go"
) )
func ParseIp(myip string)(*ipdb.CityInfo) { func ParseIp(myip string) *ipdb.CityInfo {
db, err := ipdb.NewCity("./config/city.free.ipdb") db, err := ipdb.NewCity("./config/city.free.ipdb")
if err != nil { if err != nil {
return nil return nil
} }
db.Reload("./config/city.free.ipdb") db.Reload("./config/city.free.ipdb")
c,err :=db.FindInfo(myip, "CN") c, err := db.FindInfo(myip, "CN")
if err != nil { if err != nil {
return nil return nil
} }

@ -1,147 +1,153 @@
package tools package tools
//划分 //划分
func partition(arr *[]int,left int,right int)int{ func partition(arr *[]int, left int, right int) int {
privot:=(*arr)[right] privot := (*arr)[right]
i:=left-1 i := left - 1
for j:=left;j<right;j++{ for j := left; j < right; j++ {
if (*arr)[j]<privot{ if (*arr)[j] < privot {
i++ i++
temp:=(*arr)[i] temp := (*arr)[i]
(*arr)[i]=(*arr)[j] (*arr)[i] = (*arr)[j]
(*arr)[j]=temp (*arr)[j] = temp
} }
} }
temp:=(*arr)[i+1] temp := (*arr)[i+1]
(*arr)[i+1]=(*arr)[right] (*arr)[i+1] = (*arr)[right]
(*arr)[right]=temp (*arr)[right] = temp
return i+1 return i + 1
} }
//递归 //递归
func QuickSort(arr *[]int,left int,right int){ func QuickSort(arr *[]int, left int, right int) {
if left>= right{ if left >= right {
return return
} }
privot:=partition(arr,left,right) privot := partition(arr, left, right)
QuickSort(arr,left,privot-1) QuickSort(arr, left, privot-1)
QuickSort(arr,privot+1,right) QuickSort(arr, privot+1, right)
} }
//快速排序2 //快速排序2
//找到一个基准,左边是所有比它小的,右边是比它大的,分别递归左右 //找到一个基准,左边是所有比它小的,右边是比它大的,分别递归左右
func QuickSort2(arr *[]int,left int,right int){ func QuickSort2(arr *[]int, left int, right int) {
if left>= right{ if left >= right {
return return
} }
privot:=(*arr)[left] privot := (*arr)[left]
i:=left i := left
j:=right j := right
for i<j{ for i < j {
for i<j && (*arr)[j]>privot{ for i < j && (*arr)[j] > privot {
j-- j--
} }
for i<j && (*arr)[i]<=privot{ for i < j && (*arr)[i] <= privot {
i++ i++
} }
temp:=(*arr)[i] temp := (*arr)[i]
(*arr)[i]=(*arr)[j] (*arr)[i] = (*arr)[j]
(*arr)[j]=temp (*arr)[j] = temp
} }
(*arr)[left]=(*arr)[i] (*arr)[left] = (*arr)[i]
(*arr)[i]=privot (*arr)[i] = privot
QuickSort(arr,left,i-1) QuickSort(arr, left, i-1)
QuickSort(arr,i+1,right) QuickSort(arr, i+1, right)
} }
//冒泡排序 //冒泡排序
//比较相邻元素,较大的往右移 //比较相邻元素,较大的往右移
func BubbleSort(arr *[]int){ func BubbleSort(arr *[]int) {
flag:=true flag := true
lastSwapIndex:=0 lastSwapIndex := 0
for i:=0;i<len(*arr)-1;i++{ for i := 0; i < len(*arr)-1; i++ {
sortBorder:=len(*arr)-1-i sortBorder := len(*arr) - 1 - i
for j:=0;j<sortBorder;j++{ for j := 0; j < sortBorder; j++ {
if (*arr)[j]>(*arr)[j+1]{ if (*arr)[j] > (*arr)[j+1] {
temp:=(*arr)[j] temp := (*arr)[j]
(*arr)[j]=(*arr)[j+1] (*arr)[j] = (*arr)[j+1]
(*arr)[j+1]=temp (*arr)[j+1] = temp
flag=false flag = false
lastSwapIndex=j lastSwapIndex = j
} }
} }
sortBorder=lastSwapIndex sortBorder = lastSwapIndex
if flag{ if flag {
break break
} }
} }
} }
//插入排序 //插入排序
//将未排序部分插入到已排序部分的适当位置 //将未排序部分插入到已排序部分的适当位置
func InsertionSort(arr *[]int){ func InsertionSort(arr *[]int) {
for i:=1;i<len(*arr);i++{ for i := 1; i < len(*arr); i++ {
curKey:=(*arr)[i] curKey := (*arr)[i]
j:=i-1 j := i - 1
for curKey<(*arr)[j]{ for curKey < (*arr)[j] {
(*arr)[j+1]=(*arr)[j] (*arr)[j+1] = (*arr)[j]
j-- j--
if j<0 { if j < 0 {
break break
} }
} }
(*arr)[j+1]=curKey (*arr)[j+1] = curKey
} }
} }
//选择排序 //选择排序
//选择一个最小值,再寻找比它还小的进行交换 //选择一个最小值,再寻找比它还小的进行交换
func SelectionSort(arr *[]int){ func SelectionSort(arr *[]int) {
for i:=0;i<len(*arr);i++{ for i := 0; i < len(*arr); i++ {
minIndex:=i minIndex := i
for j:=i+1;j<len(*arr);j++{ for j := i + 1; j < len(*arr); j++ {
if (*arr)[j]<(*arr)[minIndex]{ if (*arr)[j] < (*arr)[minIndex] {
minIndex=j minIndex = j
} }
} }
temp:=(*arr)[i] temp := (*arr)[i]
(*arr)[i]=(*arr)[minIndex] (*arr)[i] = (*arr)[minIndex]
(*arr)[minIndex]=temp (*arr)[minIndex] = temp
} }
} }
//归并排序 //归并排序
//合久必分,分久必合,利用临时数组合并两个有序数组 //合久必分,分久必合,利用临时数组合并两个有序数组
func MergeSort(arr *[]int,left int,right int){ func MergeSort(arr *[]int, left int, right int) {
if left >= right{ if left >= right {
return return
} }
mid:=(left+right)/2 mid := (left + right) / 2
MergeSort(arr,left,mid) MergeSort(arr, left, mid)
MergeSort(arr,mid+1,right) MergeSort(arr, mid+1, right)
i:=left i := left
j:=mid+1 j := mid + 1
p:=0 p := 0
temp :=make([]int,right-left+1) temp := make([]int, right-left+1)
for i<=mid && j<=right{ for i <= mid && j <= right {
if (*arr)[i]<=(*arr)[j]{ if (*arr)[i] <= (*arr)[j] {
temp[p]=(*arr)[i] temp[p] = (*arr)[i]
i++ i++
}else{ } else {
temp[p]=(*arr)[j] temp[p] = (*arr)[j]
j++ j++
} }
p++ p++
} }
for i<=mid{ for i <= mid {
temp[p]=(*arr)[i] temp[p] = (*arr)[i]
i++ i++
p++ p++
} }
for j<=right{ for j <= right {
temp[p]=(*arr)[j] temp[p] = (*arr)[j]
j++ j++
p++ p++
} }
for i=0;i<len(temp);i++{ for i = 0; i < len(temp); i++ {
(*arr)[left+i]=temp[i] (*arr)[left+i] = temp[i]
} }
} }

@ -5,38 +5,38 @@ import (
) )
func TestQuickSort(t *testing.T) { func TestQuickSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
QuickSort(&arr,0,len(arr)-1) QuickSort(&arr, 0, len(arr)-1)
t.Log(arr) t.Log(arr)
} }
func TestQuickSort2(t *testing.T) { func TestQuickSort2(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
QuickSort2(&arr,0,len(arr)-1) QuickSort2(&arr, 0, len(arr)-1)
t.Log(arr) t.Log(arr)
} }
func TestBubbleSort(t *testing.T){ func TestBubbleSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
BubbleSort(&arr) BubbleSort(&arr)
t.Log(arr) t.Log(arr)
} }
func TestInsertionSort(t *testing.T){ func TestInsertionSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
InsertionSort(&arr) InsertionSort(&arr)
t.Log(arr) t.Log(arr)
} }
func TestSelectionSort(t *testing.T) { func TestSelectionSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
SelectionSort(&arr) SelectionSort(&arr)
t.Log(arr) t.Log(arr)
} }
func TestMergeSort(t *testing.T) { func TestMergeSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7} arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr) t.Log(arr)
MergeSort(&arr,0,len(arr)-1) MergeSort(&arr, 0, len(arr)-1)
t.Log(arr) t.Log(arr)
} }

@ -1,8 +1,10 @@
package tools package tools
import ( import (
"github.com/satori/go.uuid" "github.com/satori/go.uuid"
) )
func Uuid()string {
func Uuid() string {
u2 := uuid.NewV4() u2 := uuid.NewV4()
return u2.String() return u2.String()
} }

Loading…
Cancel
Save