Compare commits
No commits in common. "27cd64640f56de5791eff4a5b840b6e75ed49eb9" and "ea6a87bb3310a90d3221953ba8e3eafefe9d579d" have entirely different histories.
27cd64640f
...
ea6a87bb33
18
dao/db.go
18
dao/db.go
|
|
@ -3,7 +3,6 @@ package dao
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"gorm.io/driver/mysql"
|
"gorm.io/driver/mysql"
|
||||||
"gorm.io/driver/postgres"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"videoplayer/proto"
|
"videoplayer/proto"
|
||||||
)
|
)
|
||||||
|
|
@ -11,17 +10,9 @@ import (
|
||||||
var DB *gorm.DB
|
var DB *gorm.DB
|
||||||
|
|
||||||
func Init() error {
|
func Init() error {
|
||||||
var db *gorm.DB
|
dsn := proto.MYSQL_DSN
|
||||||
var err error
|
|
||||||
var dsn string
|
|
||||||
if proto.Config.DB == 0 {
|
|
||||||
dsn = proto.Config.MYSQL_DSN
|
|
||||||
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
||||||
} else if proto.Config.DB == 1 {
|
|
||||||
dsn = proto.Config.PG_DSN
|
|
||||||
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("failed to connect database")
|
panic("failed to connect database")
|
||||||
return err
|
return err
|
||||||
|
|
@ -60,11 +51,6 @@ func Init() error {
|
||||||
fmt.Println("message table:", err)
|
fmt.Println("message table:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = db.AutoMigrate(&File{})
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("file table:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = db.AutoMigrate(&Group{})
|
err = db.AutoMigrate(&Group{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("usergroup table:", err)
|
fmt.Println("usergroup table:", err)
|
||||||
|
|
|
||||||
77
dao/file.go
77
dao/file.go
|
|
@ -1,77 +0,0 @@
|
||||||
package dao
|
|
||||||
|
|
||||||
import "gorm.io/gorm"
|
|
||||||
|
|
||||||
type File struct {
|
|
||||||
gorm.Model
|
|
||||||
// 存储文件名
|
|
||||||
FileStoreName string `gorm:"column:file_store_name;uniqueIndex:idx_file_name"`
|
|
||||||
FileName string `gorm:"column:file_name"`
|
|
||||||
FileSize int `gorm:"column:file_size"`
|
|
||||||
FileType string `gorm:"column:file_type"`
|
|
||||||
FilePath string `gorm:"column:file_path"`
|
|
||||||
AuthID int `gorm:"column:auth_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateFile(fileStoreName, fileName, fileType, filePath string, fileSize, authID int) uint {
|
|
||||||
file := File{FileStoreName: fileStoreName, FileName: fileName, FileType: fileType, FilePath: filePath, FileSize: fileSize, AuthID: authID}
|
|
||||||
result := DB.Debug().Create(&file)
|
|
||||||
if result.Error != nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return file.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
func DeleteFileByID(id, user int) bool {
|
|
||||||
res := DB.Debug().Model(&File{}).Where("id = ? and auth_id = ?", id, user).Delete(&File{})
|
|
||||||
if res.Error != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindFileByID(id, auth_id int) File {
|
|
||||||
var file File
|
|
||||||
DB.Debug().Where("id = ? and auth_id = ?", id, auth_id).First(&file)
|
|
||||||
return file
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindFileByNames(fileName string, auth_id int) File {
|
|
||||||
var file File
|
|
||||||
DB.Debug().Where("file_name = ? and auth_id = ?", fileName, auth_id).First(&file)
|
|
||||||
return file
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindFileByAuthID(auth_id int) []File {
|
|
||||||
var files []File
|
|
||||||
DB.Debug().Where("auth_id = ?", auth_id).Find(&files)
|
|
||||||
return files
|
|
||||||
}
|
|
||||||
|
|
||||||
func UpdateFileByID(id, auth_id int, fileStoreName, fileName, fileType, filePath string, fileSize int) bool {
|
|
||||||
pd := FindFileByID(id, auth_id)
|
|
||||||
if pd.ID == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
result := DB.Debug().Model(&File{}).Where("id = ? and auth_id = ?", id, auth_id).Updates(File{FileStoreName: fileStoreName, FileName: fileName, FileType: fileType, FilePath: filePath, FileSize: fileSize})
|
|
||||||
if result.Error != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func DeleteFileByAuthID(auth_id int) bool {
|
|
||||||
res := DB.Debug().Model(&File{}).Where("auth_id = ?", auth_id).Delete(&File{})
|
|
||||||
if res.Error != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func DeleteFileById(id int) bool {
|
|
||||||
res := DB.Debug().Model(&File{}).Where("id = ?", id).Delete(&File{})
|
|
||||||
if res.Error != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
@ -236,12 +236,6 @@ type FriendRet struct {
|
||||||
Email string `json:"email"` //邮箱
|
Email string `json:"email"` //邮箱
|
||||||
}
|
}
|
||||||
|
|
||||||
func FindFriendsIDs(user_id int) []Friend {
|
|
||||||
var friends []Friend
|
|
||||||
DB.Debug().Where("user_id = ?", user_id).Find(&friends)
|
|
||||||
return friends
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindFriends(user_id int) []FriendRet {
|
func FindFriends(user_id int) []FriendRet {
|
||||||
var friends []FriendRet
|
var friends []FriendRet
|
||||||
DB.Debug().Raw("select users.id, users.name, users.email from users join friends on users.id = friends.friend_id where friends.user_id = ? and friends.deleted_at is null", user_id).Scan(&friends)
|
DB.Debug().Raw("select users.id, users.name, users.email from users join friends on users.id = friends.friend_id where friends.user_id = ? and friends.deleted_at is null", user_id).Scan(&friends)
|
||||||
|
|
|
||||||
|
|
@ -14,9 +14,6 @@ type User struct {
|
||||||
Password string `gorm:"column:password"`
|
Password string `gorm:"column:password"`
|
||||||
Gender string `gorm:"column:gender"`
|
Gender string `gorm:"column:gender"`
|
||||||
Role string `gorm:"column:role"`
|
Role string `gorm:"column:role"`
|
||||||
Redis bool `gorm:"column:redis"`
|
|
||||||
Run bool `gorm:"column:run"`
|
|
||||||
Upload bool `gorm:"column:upload"`
|
|
||||||
CreateTime string `gorm:"column:create_time"`
|
CreateTime string `gorm:"column:create_time"`
|
||||||
UpdateTime string `gorm:"column:update_time"`
|
UpdateTime string `gorm:"column:update_time"`
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -65,13 +65,13 @@ func FindVideoByID(id, auth_id int) Video {
|
||||||
// 根据用户id查找视频列表,返回最新30条
|
// 根据用户id查找视频列表,返回最新30条
|
||||||
func FindVideoListsByAuthID(auth_id int) []Video {
|
func FindVideoListsByAuthID(auth_id int) []Video {
|
||||||
var videos []Video
|
var videos []Video
|
||||||
DB.Debug().Where("auth_id = ? and isdelete =? ", auth_id, 0).Order("created_at DESC").Limit(30).Find(&videos)
|
DB.Debug().Where("auth_id = ? and isdelete =? ", auth_id, 0).Order("create_time DESC").Limit(30).Find(&videos)
|
||||||
return videos
|
return videos
|
||||||
}
|
}
|
||||||
|
|
||||||
func FindVideoListByTime(auth_id int, startTime, endTime string) []Video {
|
func FindVideoListByTime(auth_id int, startTime, endTime string) []Video {
|
||||||
var videos []Video
|
var videos []Video
|
||||||
DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete=0").Where("created_at > ? and created_at < ?", startTime, endTime).Find(&videos)
|
DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete=0").Where("create_time > ? and create_time < ?", startTime, endTime).Find(&videos)
|
||||||
return videos
|
return videos
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -112,6 +112,6 @@ func QuashAllDelay(user_id int, day int) int {
|
||||||
// 获取视频列表分页
|
// 获取视频列表分页
|
||||||
func GetVideoListByPage(auth_id, page, pageSize int) []Video {
|
func GetVideoListByPage(auth_id, page, pageSize int) []Video {
|
||||||
var videos []Video
|
var videos []Video
|
||||||
DB.Debug().Where("auth_id = ? and isdelete = ?", auth_id, 0).Order("created_at DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&videos) //Offset((page - 1) * pageSize).Limit(pageSize),分页,page从1开始,pageSize每页多少条,Offset是偏移量,Limit是限制条数
|
DB.Debug().Where("auth_id = ? and isdelete = ?", auth_id, 0).Order("create_time DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&videos) //Offset((page - 1) * pageSize).Limit(pageSize),分页,page从1开始,pageSize每页多少条,Offset是偏移量,Limit是限制条数
|
||||||
return videos
|
return videos
|
||||||
}
|
}
|
||||||
|
|
|
||||||
10
go.mod
10
go.mod
|
|
@ -9,8 +9,7 @@ require (
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
gorm.io/driver/mysql v1.5.6
|
gorm.io/driver/mysql v1.5.6
|
||||||
gorm.io/driver/postgres v1.5.9
|
gorm.io/gorm v1.25.7
|
||||||
gorm.io/gorm v1.25.10
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|
@ -27,27 +26,20 @@ require (
|
||||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.2 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
|
||||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
|
||||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
github.com/jinzhu/now v1.1.5 // indirect
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||||
github.com/kr/text v0.2.0 // indirect
|
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.12.0 // indirect
|
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
golang.org/x/arch v0.8.0 // indirect
|
golang.org/x/arch v0.8.0 // indirect
|
||||||
golang.org/x/crypto v0.23.0 // indirect
|
golang.org/x/crypto v0.23.0 // indirect
|
||||||
golang.org/x/net v0.25.0 // indirect
|
golang.org/x/net v0.25.0 // indirect
|
||||||
golang.org/x/sync v0.1.0 // indirect
|
|
||||||
golang.org/x/sys v0.20.0 // indirect
|
golang.org/x/sys v0.20.0 // indirect
|
||||||
golang.org/x/text v0.15.0 // indirect
|
golang.org/x/text v0.15.0 // indirect
|
||||||
google.golang.org/protobuf v1.34.1 // indirect
|
google.golang.org/protobuf v1.34.1 // indirect
|
||||||
|
|
|
||||||
25
go.sum
25
go.sum
|
|
@ -8,7 +8,6 @@ github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/
|
||||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
|
@ -45,14 +44,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
|
||||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
|
||||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
|
||||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
|
|
@ -63,10 +54,6 @@ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
|
||||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
|
@ -86,8 +73,6 @@ github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
|
||||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
|
@ -111,8 +96,6 @@ golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||||
|
|
@ -123,9 +106,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IV
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
|
@ -135,10 +117,7 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8=
|
gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8=
|
||||||
gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||||
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
|
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
|
||||||
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
|
||||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||||
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
|
||||||
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
|
||||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||||
|
|
|
||||||
|
|
@ -50,17 +50,10 @@ func SetUpCIDGroup(router *gin.Engine) {
|
||||||
}
|
}
|
||||||
func RunCID(c *gin.Context) {
|
func RunCID(c *gin.Context) {
|
||||||
var req CIDRunReq
|
var req CIDRunReq
|
||||||
id, _ := c.Get("id")
|
|
||||||
authID := int(id.(float64))
|
|
||||||
//获取权限
|
|
||||||
user := dao.FindUserByUserID(authID)
|
|
||||||
if user.Run == false {
|
|
||||||
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "no run Permissions"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.ShouldBind(&req); err == nil {
|
if err := c.ShouldBind(&req); err == nil {
|
||||||
// 获取用户ID
|
// 获取用户ID
|
||||||
|
id, _ := c.Get("id")
|
||||||
|
authID := int(id.(float64))
|
||||||
username, _ := c.Get("username")
|
username, _ := c.Get("username")
|
||||||
cid := dao.FindCIDByID(req.ID, authID)
|
cid := dao.FindCIDByID(req.ID, authID)
|
||||||
if cid.ID == 0 {
|
if cid.ID == 0 {
|
||||||
|
|
@ -172,22 +165,11 @@ func CIDCallback(c *gin.Context) {
|
||||||
fmt.Println("token:", token, "cid_id:", cid_id)
|
fmt.Println("token:", token, "cid_id:", cid_id)
|
||||||
//将cid转换为int
|
//将cid转换为int
|
||||||
cid, _ := strconv.Atoi(cid_id)
|
cid, _ := strconv.Atoi(cid_id)
|
||||||
|
|
||||||
if token == "" || cid == 0 {
|
if token == "" || cid == 0 {
|
||||||
c.JSON(200, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
|
c.JSON(200, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
res := dao.FindCIDByIDAndToken(cid, token)
|
res := dao.FindCIDByIDAndToken(cid, token)
|
||||||
if res.ID == 0 {
|
|
||||||
c.JSON(200, gin.H{"error": "CID not found by id and token", "code": proto.OperationFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user := dao.FindUserByUserID(res.Auth_id)
|
|
||||||
if user.Run == false {
|
|
||||||
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "the user has no run Permissions"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.ID != 0 {
|
if res.ID != 0 {
|
||||||
user := dao.FindUserByID(res.Auth_id)
|
user := dao.FindUserByID(res.Auth_id)
|
||||||
go RunShell(user[0].Name, res.Url, res.Script, int(res.ID), res.Auth_id)
|
go RunShell(user[0].Name, res.Url, res.Script, int(res.ID), res.Auth_id)
|
||||||
|
|
|
||||||
|
|
@ -1,23 +1,23 @@
|
||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
//"net/http"
|
//"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 跨域访问:cross origin resource share
|
//跨域访问:cross origin resource share
|
||||||
func CrosHandler() gin.HandlerFunc {
|
func CrosHandler() gin.HandlerFunc {
|
||||||
return func(context *gin.Context) {
|
return func(context *gin.Context) {
|
||||||
//method := context.Request.Method
|
//method := context.Request.Method
|
||||||
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
|
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
|
||||||
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
|
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
|
||||||
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
|
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
|
||||||
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
|
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
|
||||||
context.Header("Access-Control-Max-Age", "172800")
|
context.Header("Access-Control-Max-Age", "172800")
|
||||||
context.Header("Access-Control-Allow-Credentials", "false")
|
context.Header("Access-Control-Allow-Credentials", "false")
|
||||||
context.Set("content-type", "application/json") //设置返回格式是json
|
context.Set("content-type", "application/json") //设置返回格式是json
|
||||||
|
|
||||||
// if method == "OPTIONS" {
|
// if method == "OPTIONS" {
|
||||||
// context.JSON(http.StatusOK, gin.H{
|
// context.JSON(http.StatusOK, gin.H{
|
||||||
// "code":1,
|
// "code":1,
|
||||||
|
|
@ -25,8 +25,8 @@ func CrosHandler() gin.HandlerFunc {
|
||||||
// "data":"request error",
|
// "data":"request error",
|
||||||
// })
|
// })
|
||||||
// }
|
// }
|
||||||
|
|
||||||
//处理请求
|
//处理请求
|
||||||
context.Next()
|
context.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -57,7 +57,6 @@ func SetUpDeviceGroup(router *gin.Engine) {
|
||||||
deviceGroup.POST("/set_device_status", SetDeviceStatus)
|
deviceGroup.POST("/set_device_status", SetDeviceStatus)
|
||||||
deviceGroup.POST("/update_device", UpdateDevice)
|
deviceGroup.POST("/update_device", UpdateDevice)
|
||||||
deviceGroup.POST("/delete_device", DeleteDevice)
|
deviceGroup.POST("/delete_device", DeleteDevice)
|
||||||
deviceGroup.GET("/get_real_time_image", GetRealTimeImage)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -234,7 +233,6 @@ func GetRealTimeImage(c *gin.Context) {
|
||||||
go func(ws *websocket.Conn, device_id int) {
|
go func(ws *websocket.Conn, device_id int) {
|
||||||
|
|
||||||
}(ws, device_id_int)
|
}(ws, device_id_int)
|
||||||
var check_cnt int
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
if v := clients[ws]; v == true {
|
if v := clients[ws]; v == true {
|
||||||
|
|
@ -249,19 +247,12 @@ func GetRealTimeImage(c *gin.Context) {
|
||||||
res3, _ = json.Marshal(msg)
|
res3, _ = json.Marshal(msg)
|
||||||
} else {
|
} else {
|
||||||
//若无消息则发送心跳包
|
//若无消息则发送心跳包
|
||||||
if check_cnt < 5 {
|
|
||||||
check_cnt++
|
|
||||||
time.Sleep(time.Millisecond * 200) //设置延时200ms
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
check_cnt = 0
|
|
||||||
msg.Type = "check"
|
msg.Type = "check"
|
||||||
msg.Msg = "check"
|
msg.Msg = "check"
|
||||||
msg.From_user_id = -1
|
msg.From_user_id = -1
|
||||||
res3, _ = json.Marshal(msg)
|
res3, _ = json.Marshal(msg)
|
||||||
}
|
}
|
||||||
err2 := ws.WriteMessage(websocket.TextMessage, res3)
|
err2 := ws.WriteMessage(websocket.TextMessage, res3)
|
||||||
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "1", time.Minute*5) //设置播放状态
|
|
||||||
if err2 != nil {
|
if err2 != nil {
|
||||||
clientsMux.Lock()
|
clientsMux.Lock()
|
||||||
clients[ws] = false
|
clients[ws] = false
|
||||||
|
|
@ -270,7 +261,7 @@ func GetRealTimeImage(c *gin.Context) {
|
||||||
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "0", time.Minute*5) //设置播放状态
|
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "0", time.Minute*5) //设置播放状态
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
time.Sleep(time.Millisecond * 200) //设置延时200ms
|
time.Sleep(time.Millisecond * 100) //设置延时100ms
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
185
handler/tool.go
185
handler/tool.go
|
|
@ -1,185 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"videoplayer/dao"
|
|
||||||
"videoplayer/proto"
|
|
||||||
"videoplayer/service"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SetRedisReq struct {
|
|
||||||
Option string `json:"option" form:"option"`
|
|
||||||
Key string `json:"key" form:"key"`
|
|
||||||
Value string `json:"value" form:"value"`
|
|
||||||
Expire int `json:"expire" form:"expire"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetUpToolGroup(router *gin.Engine) {
|
|
||||||
toolGroup := router.Group("/tool")
|
|
||||||
toolGroup.POST("/set_redis", SetRedis)
|
|
||||||
toolGroup.POST("/get_redis", GetRedis)
|
|
||||||
|
|
||||||
//文件上传、下载
|
|
||||||
toolGroup.POST("/upload", UploadFile)
|
|
||||||
toolGroup.GET("/download", DownloadFile)
|
|
||||||
//文件管理
|
|
||||||
toolGroup.POST("/file_del", DelFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func DelFile(c *gin.Context) {
|
|
||||||
//先查看是否有权限
|
|
||||||
id, _ := c.Get("id")
|
|
||||||
id1 := int(id.(float64))
|
|
||||||
|
|
||||||
file_id, _ := strconv.Atoi(c.PostForm("id"))
|
|
||||||
|
|
||||||
file_ := dao.FindFileByID(file_id, id1)
|
|
||||||
if file_.ID == 0 {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "file not found", "code": proto.FileNotFound, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//删除文件
|
|
||||||
err := os.Remove(file_.FilePath + "/" + file_.FileStoreName)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "delete file failed", "code": proto.DeleteFileFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//删除文件信息
|
|
||||||
if res := dao.DeleteFileById(file_id); !res {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "delete file info failed", "code": proto.DeleteFileInfoFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success"})
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func UploadFile(c *gin.Context) {
|
|
||||||
//先查看是否有权限
|
|
||||||
id, _ := c.Get("id")
|
|
||||||
id1 := int(id.(float64))
|
|
||||||
//从请求头获取upload_type
|
|
||||||
uploadType := c.PostForm("upload_type")
|
|
||||||
if uploadType == "" {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "upload_type is empty", "code": proto.ParameterError, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user := dao.FindUserByUserID(id1)
|
|
||||||
if user.Upload == false {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "no upload Permissions", "code": proto.NoUploadPermissions, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//上传文件
|
|
||||||
file, err := c.FormFile("file")
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "upload file failed", "code": proto.UploadFileFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//保存文件
|
|
||||||
filePath, fileStoreName, err := service.SaveFile(c, file, uploadType)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "save file failed", "code": proto.SaveFileFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//保存文件信息
|
|
||||||
fileSize := int(file.Size)
|
|
||||||
fileName := file.Filename
|
|
||||||
fileType := file.Header.Get("file_type")
|
|
||||||
fileID := dao.CreateFile(fileStoreName, fileName, fileType, filePath, fileSize, id1)
|
|
||||||
if fileID == 0 {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "save file info failed", "code": proto.SaveFileInfoFailed, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success", "data": fileID})
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DownloadFile(c *gin.Context) {
|
|
||||||
//参数
|
|
||||||
//filename := c.Param("filename")
|
|
||||||
file_id, _ := strconv.Atoi(c.Query("id"))
|
|
||||||
id, _ := c.Get("id")
|
|
||||||
//查询文件信息
|
|
||||||
//file := dao.FindFileByNames(file_id, int(id.(float64)))
|
|
||||||
file_ := dao.FindFileByID(file_id, int(id.(float64)))
|
|
||||||
if file_.ID == 0 {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "file not found", "code": proto.FileNotFound, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//下载文件
|
|
||||||
// 打开文件
|
|
||||||
file, err := os.Open(file_.FilePath + "/" + file_.FileStoreName)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error", "message": "Failed to open file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
// 设置响应头
|
|
||||||
c.Writer.Header().Set("Content-Type", "application/octet-stream")
|
|
||||||
c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", file_.FileName))
|
|
||||||
|
|
||||||
// 发送文件内容
|
|
||||||
_, err = io.Copy(c.Writer, file)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error", "message": "Failed to send file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Status(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetRedis(c *gin.Context) {
|
|
||||||
//先查看是否有权限
|
|
||||||
id, _ := c.Get("id")
|
|
||||||
id1 := int(id.(float64))
|
|
||||||
user := dao.FindUserByUserID(id1)
|
|
||||||
if user.Redis == false {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//解析请求参数
|
|
||||||
var req SetRedisReq
|
|
||||||
if err := c.ShouldBind(&req); err == nil {
|
|
||||||
var code int
|
|
||||||
var message string
|
|
||||||
if req.Option == "list" {
|
|
||||||
code, message = service.SetToolRedisList(req.Key, req.Value, req.Expire)
|
|
||||||
} else if req.Option == "set" {
|
|
||||||
code, message = service.SetToolRedisSet(req.Key, req.Value, req.Expire)
|
|
||||||
} else if req.Option == "kv" {
|
|
||||||
code, message = service.SetToolRedisKV(req.Key, req.Value, req.Expire)
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"code": code, "message": message})
|
|
||||||
} else {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetRedis(c *gin.Context) {
|
|
||||||
//先查看是否有权限
|
|
||||||
id, _ := c.Get("id")
|
|
||||||
id1 := int(id.(float64))
|
|
||||||
user := dao.FindUserByUserID(id1)
|
|
||||||
if user.Redis == false {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//解析请求参数
|
|
||||||
var req SetRedisReq
|
|
||||||
if err := c.ShouldBind(&req); err == nil {
|
|
||||||
code, message := service.GetToolRedis(req.Key)
|
|
||||||
req.Value = message
|
|
||||||
c.JSON(http.StatusOK, gin.H{"code": code, "message": message, "data": req})
|
|
||||||
} else {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -15,6 +15,8 @@ import (
|
||||||
"videoplayer/worker"
|
"videoplayer/worker"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var signingKey = []byte(proto.TOKEN_SECRET)
|
||||||
|
|
||||||
func SetUpUserGroup(router *gin.Engine) {
|
func SetUpUserGroup(router *gin.Engine) {
|
||||||
userGroup := router.Group("/user")
|
userGroup := router.Group("/user")
|
||||||
userGroup.POST("/register", registerHandler)
|
userGroup.POST("/register", registerHandler)
|
||||||
|
|
@ -168,7 +170,7 @@ func GetQRStatus(c *gin.Context) {
|
||||||
default:
|
default:
|
||||||
// 解析 JWT 令牌
|
// 解析 JWT 令牌
|
||||||
token, err := jwt.Parse(str, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(str, func(token *jwt.Token) (interface{}, error) {
|
||||||
return proto.SigningKey, nil
|
return signingKey, nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenParseError, "message": "error"})
|
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenParseError, "message": "error"})
|
||||||
|
|
@ -228,7 +230,7 @@ func loginHandler(c *gin.Context) {
|
||||||
"id": user.ID,
|
"id": user.ID,
|
||||||
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 10小时后过期
|
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 10小时后过期
|
||||||
})
|
})
|
||||||
tokenString, err = token.SignedString(proto.SigningKey)
|
tokenString, err = token.SignedString(signingKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
|
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
|
||||||
return
|
return
|
||||||
|
|
@ -285,7 +287,7 @@ func registerHandler(c *gin.Context) {
|
||||||
"id": id,
|
"id": id,
|
||||||
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 1分钟后过期
|
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 1分钟后过期
|
||||||
})
|
})
|
||||||
tokenString, err = token.SignedString(proto.SigningKey)
|
tokenString, err = token.SignedString(signingKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
|
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
|
||||||
return
|
return
|
||||||
|
|
|
||||||
47
main.go
47
main.go
|
|
@ -12,9 +12,12 @@ import (
|
||||||
"videoplayer/worker"
|
"videoplayer/worker"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var signingKey = []byte(proto.TOKEN_SECRET)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
gin.SetMode(gin.ReleaseMode)
|
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
err := dao.Init()
|
err := dao.Init()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("failed to connect database:" + err.Error())
|
panic("failed to connect database:" + err.Error())
|
||||||
|
|
@ -30,24 +33,15 @@ func main() {
|
||||||
handler.SetUpDeviceGroup(r) // Device
|
handler.SetUpDeviceGroup(r) // Device
|
||||||
handler.SetUpIMGroup(r) // IM
|
handler.SetUpIMGroup(r) // IM
|
||||||
handler.SetUpCIDGroup(r) // CID,持续集成、部署
|
handler.SetUpCIDGroup(r) // CID,持续集成、部署
|
||||||
handler.SetUpToolGroup(r) // Tool
|
r.Run(":8083") // listen and serve on 0.0.0.0:8082
|
||||||
defer dao.Close()
|
defer dao.Close()
|
||||||
defer worker.CloseRedis()
|
defer worker.CloseRedis()
|
||||||
r.Run(":8083") // listen and serve on 0.0.0.0:8083
|
|
||||||
}
|
}
|
||||||
func init() {
|
func init() {
|
||||||
// 创建cid的目录
|
// 创建cid的目录
|
||||||
os.MkdirAll(proto.CID_BASE_DIR, os.ModePerm)
|
os.MkdirAll(proto.CID_BASE_DIR, os.ModePerm)
|
||||||
os.MkdirAll(proto.CID_BASE_DIR+"script", os.ModePerm)
|
os.MkdirAll(proto.CID_BASE_DIR+"script", os.ModePerm)
|
||||||
os.MkdirAll(proto.CID_BASE_DIR+"workspace", os.ModePerm)
|
os.MkdirAll(proto.CID_BASE_DIR+"workspace", os.ModePerm)
|
||||||
//读取配置文件
|
|
||||||
//文件地址/home/videoplayer/vp.conf
|
|
||||||
configPath := "/home/videoplayer/vp.conf"
|
|
||||||
//读取配置文件
|
|
||||||
err := proto.ReadConfig(configPath)
|
|
||||||
if err != nil {
|
|
||||||
panic("failed to read config file:" + err.Error())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeLogger(c *gin.Context) {
|
func writeLogger(c *gin.Context) {
|
||||||
|
|
@ -55,11 +49,10 @@ func writeLogger(c *gin.Context) {
|
||||||
method := c.Request.Method
|
method := c.Request.Method
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
params := ""
|
params := ""
|
||||||
|
|
||||||
if method == "GET" {
|
if method == "GET" {
|
||||||
params = c.Request.URL.RawQuery
|
params = c.Request.URL.RawQuery
|
||||||
}
|
}
|
||||||
if method == "POST" && !strings.Contains(c.Request.URL.Path, "/upload") {
|
if method == "POST" {
|
||||||
params = c.Request.PostForm.Encode()
|
params = c.Request.PostForm.Encode()
|
||||||
if params == "" {
|
if params == "" {
|
||||||
// 请求体
|
// 请求体
|
||||||
|
|
@ -68,9 +61,6 @@ func writeLogger(c *gin.Context) {
|
||||||
params = string(bodyBytes)
|
params = string(bodyBytes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.Contains(c.Request.URL.Path, "/upload") {
|
|
||||||
params = "upload file"
|
|
||||||
}
|
|
||||||
go dao.InsertLogToDB(path, ip, method, params)
|
go dao.InsertLogToDB(path, ip, method, params)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -99,22 +89,21 @@ func JWTAuthMiddleware() gin.HandlerFunc {
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if proto.Config.TOKEN_USE_REDIS {
|
redisToken := worker.GetRedis(tokenString)
|
||||||
redisToken := worker.GetRedis(tokenString)
|
|
||||||
if redisToken == "" {
|
if redisToken == "" {
|
||||||
c.AbortWithStatus(200)
|
c.AbortWithStatus(200)
|
||||||
c.JSON(200, gin.H{
|
c.JSON(200, gin.H{
|
||||||
"message": "NOT_LOGIN",
|
"message": "NOT_LOGIN",
|
||||||
"error": "server token is empty",
|
"error": "server token is empty",
|
||||||
"code": proto.TokenIsNull,
|
"code": proto.TokenIsNull,
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用加密secret 解析 JWT 令牌
|
// 解析 JWT 令牌
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||||
return proto.SigningKey, nil
|
return signingKey, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
// 验证令牌
|
// 验证令牌
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,6 @@
|
||||||
package proto
|
package proto
|
||||||
|
|
||||||
import (
|
import "gorm.io/gorm"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
var Config ConfigStruct
|
|
||||||
var SigningKey = []byte{}
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MYSQL_USER = "video_t2"
|
MYSQL_USER = "video_t2"
|
||||||
|
|
@ -26,9 +18,6 @@ const (
|
||||||
|
|
||||||
// 以下是持续集成、部署的配置
|
// 以下是持续集成、部署的配置
|
||||||
CID_BASE_DIR = "/home/lijun/cid/"
|
CID_BASE_DIR = "/home/lijun/cid/"
|
||||||
|
|
||||||
// 以下是文件上传的配置
|
|
||||||
FILE_BASE_DIR = "/home/lijun/file/"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -45,13 +34,6 @@ const (
|
||||||
MSG_STATUS_UNREAD = 0 // 未读
|
MSG_STATUS_UNREAD = 0 // 未读
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
//文件上传类型
|
|
||||||
File_TYPE = 1 // 通用文件
|
|
||||||
//用于视频解析
|
|
||||||
Video_TYPE = 2 // 视频文件
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
Name string `gorm:"column:name"`
|
Name string `gorm:"column:name"`
|
||||||
|
|
@ -59,35 +41,3 @@ type User struct {
|
||||||
Email string `gorm:"column:email"`
|
Email string `gorm:"column:email"`
|
||||||
Gender string `gorm:"column:gender"`
|
Gender string `gorm:"column:gender"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigStruct struct {
|
|
||||||
DB int `json:"db"` // 0: mysql, 1: pg
|
|
||||||
MYSQL_DSN string `json:"mysql_dsn"`
|
|
||||||
PG_DSN string `json:"pg_dsn"`
|
|
||||||
REDIS_ADDR string `json:"redis_addr"`
|
|
||||||
TOKEN_USE_REDIS bool `json:"token_use_redis"`
|
|
||||||
REDIS_User_PW bool `json:"redis_user_pw"` // 是否使用密码
|
|
||||||
REDIS_PASSWORD string `json:"redis_password"`
|
|
||||||
REDIS_DB int `json:"redis_db"`
|
|
||||||
TOKEN_SECRET string `json:"token_secret"`
|
|
||||||
CID_BASE_DIR string `json:"cid_base_dir"`
|
|
||||||
FILE_BASE_DIR string `json:"file_base_dir"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// 读取配置文件
|
|
||||||
func ReadConfig(path string) error {
|
|
||||||
//读json文件
|
|
||||||
file, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error opening config file")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
decoder := json.NewDecoder(file)
|
|
||||||
err = decoder.Decode(&Config)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error decoding config")
|
|
||||||
}
|
|
||||||
SigningKey = []byte(Config.TOKEN_SECRET)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -42,21 +42,6 @@ const (
|
||||||
// UUID相关错误码
|
// UUID相关错误码
|
||||||
UUIDNotFound = 18 // uuid不存在
|
UUIDNotFound = 18 // uuid不存在
|
||||||
|
|
||||||
//Tool
|
|
||||||
NoRedisPermissions = 51
|
|
||||||
NoRunPermissions = 52
|
|
||||||
NoDevicePermissions = 53
|
|
||||||
|
|
||||||
//消息错误码
|
//消息错误码
|
||||||
MsgSendFailed = 61 // 消息发送失败
|
MsgSendFailed = 61 // 消息发送失败
|
||||||
|
|
||||||
//文件错误码
|
|
||||||
FileNotFound = 71 // 文件不存在
|
|
||||||
FileUploadFailed = 72 // 文件上传失败
|
|
||||||
SaveFileInfoFailed = 73 // 保存文件信息失败
|
|
||||||
SaveFileFailed = 74 // 保存文件失败
|
|
||||||
UploadFileFailed = 75 // 上传文件失败
|
|
||||||
NoUploadPermissions = 76 // 无上传权限
|
|
||||||
DeleteFileFailed = 77 // 删除文件失败
|
|
||||||
DeleteFileInfoFailed = 78 // 删除文件信息失败
|
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"mime/multipart"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"time"
|
|
||||||
"videoplayer/proto"
|
|
||||||
"videoplayer/worker"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 检查path是否存在当前日期文件夹如(2024-08-09),不存在则path下当前日期文件夹创建,存在则返回
|
|
||||||
func getFilePath(path string) string {
|
|
||||||
//当前日期,格式为2024-08-09
|
|
||||||
date := time.Now().Format("2006-01-02")
|
|
||||||
//拼接文件路径
|
|
||||||
filePath := path + "/" + date
|
|
||||||
//判断文件夹是否存在
|
|
||||||
_, err := os.Stat(filePath)
|
|
||||||
if err != nil {
|
|
||||||
//不存在则创建
|
|
||||||
os.MkdirAll(filePath, os.ModePerm)
|
|
||||||
}
|
|
||||||
return filePath
|
|
||||||
}
|
|
||||||
|
|
||||||
func SaveFile(c *gin.Context, file *multipart.FileHeader, uploadType string) (string, string, error) {
|
|
||||||
//获取文件后缀
|
|
||||||
fileSuffix := path.Ext(file.Filename)
|
|
||||||
//生成文件名
|
|
||||||
fileStoreName := uuid.NewString() + fileSuffix
|
|
||||||
//生成文件路径
|
|
||||||
path_ := getFilePath(proto.FILE_BASE_DIR)
|
|
||||||
filePath := path_ + "/" + fileStoreName
|
|
||||||
|
|
||||||
//保存文件
|
|
||||||
if err := c.SaveUploadedFile(file, filePath); err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
if uploadType == "2" {
|
|
||||||
worker.PushRedisList("video_need_handle", filePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
return path_, fileStoreName, nil
|
|
||||||
}
|
|
||||||
|
|
@ -15,31 +15,11 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
|
||||||
var id uint
|
var id uint
|
||||||
switch msg_type {
|
switch msg_type {
|
||||||
case proto.MSG_TYPE_SIMPLE:
|
case proto.MSG_TYPE_SIMPLE:
|
||||||
//判断是否是好友,判断是否存在缓存,不存在则设置缓存,存在则判断是否是好友
|
//判断是否是好友
|
||||||
if worker.IsContainKey("user_"+strconv.Itoa(from_id)+"_friends") == false {
|
friend := dao.FindFriend(from_id, to_id)
|
||||||
//设置好友缓存
|
if len(friend) == 0 {
|
||||||
isSuccess := SetFriendCache(from_id)
|
return errors.New("未添加好友"), 0
|
||||||
//设置失败,直接查询数据库
|
|
||||||
if !isSuccess {
|
|
||||||
friend := dao.FindFriend(from_id, to_id)
|
|
||||||
if len(friend) == 0 {
|
|
||||||
return errors.New("未添加好友"), 0
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
//判断是否是好友-redis方式
|
|
||||||
is_f := worker.IsContainSet("user_"+strconv.Itoa(from_id)+"_friends", strconv.Itoa(to_id))
|
|
||||||
if !is_f {
|
|
||||||
return errors.New("未添加好友"), 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
//判断是否是好友-redis方式
|
|
||||||
is_f := worker.IsContainSet("user_"+strconv.Itoa(from_id)+"_friends", strconv.Itoa(to_id))
|
|
||||||
if !is_f {
|
|
||||||
return errors.New("未添加好友"), 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err, id = dao.CreateSimpleMessage(from_id, to_id, content)
|
err, id = dao.CreateSimpleMessage(from_id, to_id, content)
|
||||||
res := worker.GetRedis("user_" + strconv.Itoa(to_id) + "_status_v2")
|
res := worker.GetRedis("user_" + strconv.Itoa(to_id) + "_status_v2")
|
||||||
if res == "1" {
|
if res == "1" {
|
||||||
|
|
@ -50,31 +30,11 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
|
||||||
if from_id == 0 || group_id == 0 || content == "" {
|
if from_id == 0 || group_id == 0 || content == "" {
|
||||||
return errors.New("参数错误"), 0
|
return errors.New("参数错误"), 0
|
||||||
}
|
}
|
||||||
//判断是否在群里
|
//判断该用户是否在群里
|
||||||
if worker.IsContainKey("group_"+strconv.Itoa(group_id)+"_users") == false {
|
groupUser := dao.FindGroupUser(from_id, group_id)
|
||||||
//设置群缓存
|
if len(groupUser) == 0 {
|
||||||
isSuccess := SetGroupCache(group_id)
|
return errors.New("用户不在群里"), 0
|
||||||
//设置失败,直接查询数据库
|
|
||||||
if !isSuccess {
|
|
||||||
groupUser := dao.FindGroupUser(from_id, group_id)
|
|
||||||
if len(groupUser) == 0 {
|
|
||||||
return errors.New("用户不在群里"), 0
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
//判断该用户是否在群里-redis方式
|
|
||||||
is_g := worker.IsContainSet("group_"+strconv.Itoa(group_id)+"_users", strconv.Itoa(from_id))
|
|
||||||
if !is_g {
|
|
||||||
return errors.New("用户不在群里"), 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
//判断该用户是否在群里-redis方式
|
|
||||||
is_g := worker.IsContainSet("group_"+strconv.Itoa(group_id)+"_users", strconv.Itoa(from_id))
|
|
||||||
if !is_g {
|
|
||||||
return errors.New("用户不在群里"), 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content)
|
err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content)
|
||||||
//获取群里的用户
|
//获取群里的用户
|
||||||
users := dao.FindGroupUsers(group_id)
|
users := dao.FindGroupUsers(group_id)
|
||||||
|
|
@ -104,7 +64,6 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
|
||||||
return errors.New("已有请求"), res[0].ID
|
return errors.New("已有请求"), res[0].ID
|
||||||
}
|
}
|
||||||
err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content)
|
err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content)
|
||||||
|
|
||||||
case proto.MSG_TYPE_GROUP_ADD:
|
case proto.MSG_TYPE_GROUP_ADD:
|
||||||
//加入群聊请求
|
//加入群聊请求
|
||||||
//判断是否在群里
|
//判断是否在群里
|
||||||
|
|
@ -132,13 +91,6 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
|
||||||
return errors.New("已在群里"), 0
|
return errors.New("已在群里"), 0
|
||||||
}
|
}
|
||||||
err, id = dao.JoinGroup(group_id, to_id)
|
err, id = dao.JoinGroup(group_id, to_id)
|
||||||
if err == nil {
|
|
||||||
//设置群缓存,如果存在缓存则加入
|
|
||||||
if worker.IsContainKey("group_"+strconv.Itoa(group_id)+"_users") == true {
|
|
||||||
//将用户加入群缓存
|
|
||||||
worker.SetRedisSetAdd("group_"+strconv.Itoa(group_id)+"_users", strconv.Itoa(to_id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
// 未知消息类型
|
// 未知消息类型
|
||||||
err = errors.New("unknown message type")
|
err = errors.New("unknown message type")
|
||||||
|
|
@ -178,17 +130,7 @@ func AddFriendService(id, from_user_id, to_user_id int) error {
|
||||||
return errors.New("already a friend")
|
return errors.New("already a friend")
|
||||||
}
|
}
|
||||||
dao.UpdateMessageStatus(res[0].ID, 1)
|
dao.UpdateMessageStatus(res[0].ID, 1)
|
||||||
res2 := dao.AddFriend(from_user_id, to_user_id)
|
return dao.AddFriend(from_user_id, to_user_id)
|
||||||
if res2 == nil {
|
|
||||||
//设置好友缓存
|
|
||||||
if worker.IsContainKey("user_"+strconv.Itoa(from_user_id)+"_friends") == true {
|
|
||||||
worker.SetRedisSetAdd("user_"+strconv.Itoa(from_user_id)+"_friends", strconv.Itoa(to_user_id))
|
|
||||||
}
|
|
||||||
if worker.IsContainKey("user_"+strconv.Itoa(to_user_id)+"_friends") == true {
|
|
||||||
worker.SetRedisSetAdd("user_"+strconv.Itoa(to_user_id)+"_friends", strconv.Itoa(from_user_id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res2
|
|
||||||
} else if res[0].ToUserID == from_user_id && res[0].GroupID == to_user_id {
|
} else if res[0].ToUserID == from_user_id && res[0].GroupID == to_user_id {
|
||||||
//加入群聊
|
//加入群聊
|
||||||
//查看是否已经加入
|
//查看是否已经加入
|
||||||
|
|
@ -243,20 +185,12 @@ func GetFriendRequest(user_id int) []dao.FriendRequest {
|
||||||
func DelFriendService(user_id, friend_id int) error {
|
func DelFriendService(user_id, friend_id int) error {
|
||||||
//删除好友
|
//删除好友
|
||||||
err := dao.DeleteFriend(user_id, friend_id)
|
err := dao.DeleteFriend(user_id, friend_id)
|
||||||
//删除好友缓存
|
|
||||||
if err == nil && worker.IsContainKey("user_"+strconv.Itoa(user_id)+"_friends") == true {
|
|
||||||
worker.SetRedisSetRemove("user_"+strconv.Itoa(user_id)+"_friends", strconv.Itoa(friend_id))
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func QuitGroupService(user_id, group_id int) error {
|
func QuitGroupService(user_id, group_id int) error {
|
||||||
//退出群聊
|
//退出群聊
|
||||||
err := dao.QuitGroup(group_id, user_id)
|
err := dao.QuitGroup(group_id, user_id)
|
||||||
//删除群缓存
|
|
||||||
if err == nil && worker.IsContainKey("group_"+strconv.Itoa(group_id)+"_users") == true {
|
|
||||||
worker.SetRedisSetRemove("group_"+strconv.Itoa(group_id)+"_users", strconv.Itoa(user_id))
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
func DelGroupService(user_id, group_id int) error {
|
func DelGroupService(user_id, group_id int) error {
|
||||||
|
|
@ -297,27 +231,3 @@ func GetGroupRequestUsers(user_id int) []dao.FriendRequest {
|
||||||
users := dao.GetGroupRequestUsers(user_id)
|
users := dao.GetGroupRequestUsers(user_id)
|
||||||
return users
|
return users
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置用户朋友关系缓存
|
|
||||||
func SetFriendCache(user_id int) bool {
|
|
||||||
//获取好友id
|
|
||||||
friends := dao.FindFriendsIDs(user_id)
|
|
||||||
var ids []string
|
|
||||||
for _, friend := range friends {
|
|
||||||
ids = append(ids, strconv.Itoa(friend.FriendID))
|
|
||||||
}
|
|
||||||
res := worker.SetRedisSet("user_"+strconv.Itoa(user_id)+"_friends", ids, time.Hour*12)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置用户群关系缓存
|
|
||||||
func SetGroupCache(group_id int) bool {
|
|
||||||
//获取好友id
|
|
||||||
users := dao.FindGroupUsers(group_id)
|
|
||||||
var ids []string
|
|
||||||
for _, user := range users {
|
|
||||||
ids = append(ids, strconv.Itoa(user.UserID))
|
|
||||||
}
|
|
||||||
res := worker.SetRedisSet("group_"+strconv.Itoa(group_id)+"_users", ids, time.Hour*12)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
"videoplayer/proto"
|
|
||||||
"videoplayer/worker"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetToolRedisList(key string, value string, expire int) (code int, message string) {
|
|
||||||
if expire == 0 {
|
|
||||||
if worker.PushRedisList(key, value) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "push redis list failed"
|
|
||||||
}
|
|
||||||
} else if expire > 0 {
|
|
||||||
if worker.PushRedisListWithExpire(key, value, time.Duration(expire)) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "push redis list with expire failed"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return proto.ParameterError, "expire time can not be negative"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetToolRedisSet(key string, value string, expire int) (code int, message string) {
|
|
||||||
if expire == 0 {
|
|
||||||
if worker.SetRedis(key, value) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "set redis failed"
|
|
||||||
}
|
|
||||||
} else if expire > 0 {
|
|
||||||
if worker.SetRedisWithExpire(key, value, time.Duration(expire)) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "set redis with expire failed"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return proto.ParameterError, "expire time can not be negative"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetToolRedisKV(key string, value string, expire int) (code int, message string) {
|
|
||||||
if expire == 0 {
|
|
||||||
if worker.SetRedis(key, value) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "set redis failed"
|
|
||||||
}
|
|
||||||
} else if expire > 0 {
|
|
||||||
if worker.SetRedisWithExpire(key, value, time.Duration(expire)) {
|
|
||||||
return proto.SuccessCode, "success"
|
|
||||||
} else {
|
|
||||||
return proto.OperationFailed, "set redis with expire failed"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return proto.ParameterError, "expire time can not be negative"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetToolRedis(key string) (code int, message string) {
|
|
||||||
val := worker.GetRedis(key)
|
|
||||||
if val == "" {
|
|
||||||
return proto.OperationFailed, "get redis failed"
|
|
||||||
} else {
|
|
||||||
return proto.SuccessCode, val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
13
vp.conf
13
vp.conf
|
|
@ -1,13 +0,0 @@
|
||||||
{
|
|
||||||
"db":0,
|
|
||||||
"mysql_dsn":"video_t2:2t2SKHmWEYj2xFKF@tcp(127.0.0.1:3306)/video_t2?charset=utf8mb4&parseTime=True&loc=Local",
|
|
||||||
"pg_dsn":"host=localhost user=video_t2 dbname=video_t2 password=2t2SKHmWEYj2xFKF port=5432 TimeZone=Asia/Shanghai",
|
|
||||||
"redis_addr":"127.0.0.1:6379",
|
|
||||||
"redis_db":2,
|
|
||||||
"redis_user_pw":true,
|
|
||||||
"token_use_redis":true,
|
|
||||||
"redis_password":"lj502138",
|
|
||||||
"token_secret":"mfjurnc_32ndj9dfhj",
|
|
||||||
"cid_base_dir":"/home/lijun/cid/",
|
|
||||||
"file_base_dir":"/home/lijun/file/",
|
|
||||||
}
|
|
||||||
|
|
@ -15,21 +15,12 @@ import (
|
||||||
var redisClient *redis.Client // Redis 客户端, 用于连接 Redis 服务器
|
var redisClient *redis.Client // Redis 客户端, 用于连接 Redis 服务器
|
||||||
func InitRedis() error {
|
func InitRedis() error {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// 连接redis
|
||||||
if proto.Config.REDIS_User_PW == false {
|
redisClient = redis.NewClient(&redis.Options{
|
||||||
// 连接redis
|
Addr: proto.REDIS_ADDR, // Redis 服务器地址
|
||||||
redisClient = redis.NewClient(&redis.Options{
|
Password: proto.REDIS_PASSWORD, // 如果 Redis 设置了密码
|
||||||
Addr: proto.Config.REDIS_ADDR, // Redis 服务器地址
|
DB: proto.REIDS_DB, // 使用的数据库编号
|
||||||
DB: proto.Config.REDIS_DB, // 使用的数据库编号
|
})
|
||||||
})
|
|
||||||
} else {
|
|
||||||
// 连接redis
|
|
||||||
redisClient = redis.NewClient(&redis.Options{
|
|
||||||
Addr: proto.Config.REDIS_ADDR, // Redis 服务器地址
|
|
||||||
Password: proto.Config.REDIS_PASSWORD, // 如果 Redis 设置了密码
|
|
||||||
DB: proto.Config.REDIS_DB, // 使用的数据库编号
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证 Redis 客户端是否可以正常工作
|
// 验证 Redis 客户端是否可以正常工作
|
||||||
_, err := redisClient.Ping(ctx).Result()
|
_, err := redisClient.Ping(ctx).Result()
|
||||||
|
|
@ -264,52 +255,3 @@ func hGetRedis(key string, field string) string {
|
||||||
}
|
}
|
||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置set,有过期时间
|
|
||||||
func SetRedisSet(key string, values []string, expire time.Duration) bool {
|
|
||||||
ctx := context.Background()
|
|
||||||
err := redisClient.SAdd(ctx, key, values).Err()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error setting key: %v", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
err = redisClient.Expire(ctx, key, expire).Err()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error setting key: %v", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置set,添加元素
|
|
||||||
func SetRedisSetAdd(key string, value string) bool {
|
|
||||||
ctx := context.Background()
|
|
||||||
err := redisClient.SAdd(ctx, key, value).Err()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error setting key: %v", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置set,删除元素
|
|
||||||
func SetRedisSetRemove(key string, value string) bool {
|
|
||||||
ctx := context.Background()
|
|
||||||
err := redisClient.SRem(ctx, key, value).Err()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error setting key: %v", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// 查看set是否包含元素
|
|
||||||
func IsContainSet(key string, value string) bool {
|
|
||||||
ctx := context.Background()
|
|
||||||
val, err := redisClient.SIsMember(ctx, key, value).Result()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error getting key: %v", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue