Compare commits

...

60 Commits

Author SHA1 Message Date
junleea 27cd64640f 修改跨域处理 2024-09-27 21:13:56 +08:00
junleea 56cab15a73 修改跨域处理 2024-09-27 20:52:14 +08:00
junleea 76cb556042 使用配置文件读取配置-pg 2024-09-22 14:01:31 +08:00
junleea 56514b5e0d 使用配置文件读取配置 2024-09-22 13:59:33 +08:00
junleea a7b3fc7669 视频范围搜索 2024-09-21 16:13:05 +08:00
junleea 81a2806641 视频范围搜索 2024-09-21 15:18:45 +08:00
junleea ed9a6112d9 添加消息部分用户关系及群用户缓存-修复群缓存构建 2024-09-21 13:40:26 +08:00
junleea f1534502a2 添加消息部分用户关系及群用户缓存-修复 2024-09-21 13:27:08 +08:00
junleea e3bc77697b 添加消息部分用户关系及群用户缓存 2024-09-21 13:14:20 +08:00
junleea 75fdf7c1d8 文件上传功能 2024-08-30 22:31:08 +08:00
junleea 27972c1619 文件上传功能、删除功能 2024-08-30 21:46:28 +08:00
junleea d33597766a download file 2024-08-30 15:47:57 +08:00
junleea 9e5ca5e897 download file 2024-08-30 15:41:51 +08:00
junleea 5228a4270e download file 2024-08-30 15:40:45 +08:00
junleea a295d750cc upload type 2024-08-30 15:28:39 +08:00
junleea c943ced9f6 upload type 2024-08-30 15:26:39 +08:00
junleea db726b078e upload type 2024-08-30 15:13:23 +08:00
junleea 0b503558ef upload type 2024-08-30 15:03:33 +08:00
junleea 743ac6a55f upload type 2024-08-30 14:48:19 +08:00
junleea 2c7d0d3b09 file表 2024-08-30 11:51:31 +08:00
junleea 8189048e5b 添加文件上传及下载功能 2024-08-30 11:28:27 +08:00
junleea fc9a1b3402 Merge branch 'refs/heads/feature-im-gitea' 2024-08-20 15:55:00 +08:00
junleea 4bf18347ce Merge branch 'refs/heads/feature-im-gitea' 2024-08-20 10:50:42 +08:00
junleea 44e2240637 Merge branch 'refs/heads/feature-im-gitea' 2024-08-20 10:27:51 +08:00
junleea 8e90f21a64 Merge branch 'refs/heads/feature-im-gitea' 2024-08-17 14:13:41 +08:00
junleea b726b2c8f4 Merge branch 'refs/heads/feature-im-gitea' 2024-08-16 16:03:29 +08:00
junleea 5cd0a0a208 Merge branch 'refs/heads/feature-im-gitea' 2024-08-09 20:59:15 +08:00
junleea 1a9a8ecefc Merge branch 'refs/heads/feature-im-gitea' 2024-08-09 20:53:28 +08:00
junleea 700f9a474d Merge branch 'refs/heads/fearture-realvp' 2024-08-08 20:57:48 +08:00
junleea 25e5ba0d21 修复查看实时视频问题 2024-08-08 20:57:23 +08:00
junleea 15b655f6e5 Merge branch 'refs/heads/feature-im-gitea' 2024-08-08 17:23:24 +08:00
junleea 2009d3403a Merge branch 'refs/heads/feature-im-gitea' 2024-08-08 17:11:28 +08:00
junleea a78f7a166e Merge branch 'refs/heads/feature-im-gitea' 2024-08-08 17:02:13 +08:00
junleea c17348d3ad Merge branch 'refs/heads/feature-im-gitea' 2024-08-08 16:47:20 +08:00
junleea b65234689c Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 23:18:06 +08:00
junleea f30b750cf8 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 20:29:32 +08:00
junleea f46b1915c7 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 20:25:52 +08:00
junleea bcc63631b5 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 20:19:33 +08:00
junleea a3ec4e8ac4 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 18:23:06 +08:00
junleea c772060fd2 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 18:09:44 +08:00
junleea 0d3d8face2 Merge branch 'refs/heads/feature-im-gitea' 2024-08-07 16:49:43 +08:00
junleea 093fef0245 Merge branch 'refs/heads/feature-im' 2024-08-07 15:42:13 +08:00
junleea 3fbf6bbc25 Merge branch 'refs/heads/feature-im' 2024-08-07 15:04:04 +08:00
junleea 1f85577fed Merge branch 'refs/heads/feature-im' 2024-08-05 21:17:27 +08:00
junleea 056ba827fc Merge branch 'refs/heads/feature-cid' 2024-08-04 21:27:53 +08:00
junleea edb24274e6 修复cid回调判断 2024-08-04 21:27:38 +08:00
junleea f82b3f22da Merge branch 'refs/heads/feature-im' 2024-08-04 21:08:36 +08:00
junleea 341ef95509 Merge branch 'refs/heads/feature-im'
# Conflicts:
#	proto/status.go
2024-08-04 21:05:25 +08:00
junleea 350a439f89 Merge branch 'refs/heads/feature-im' 2024-07-21 11:28:28 +08:00
junleea 766b58ae40 Merge branch 'refs/heads/feature-im' 2024-07-21 11:24:18 +08:00
junleea 16f397d507 cid添加run权限判断 2024-07-21 11:12:54 +08:00
junleea 227b9e0803 tool添加redis操作及查看,并添加请求 2024-07-21 11:00:08 +08:00
junleea ee478c105f 添加tool工具,添加用户权限 2024-07-19 09:43:17 +08:00
junleea cd3c9a30ce 增大发送sleep 2024-07-18 15:48:43 +08:00
junleea 385afc7b9c 添加实时查看监控功能 2024-07-18 10:14:38 +08:00
junleea d7f7628d3f Merge branch 'refs/heads/feature-cid' into fearture-realvp
# Conflicts:
#	handler/im.go
2024-07-18 10:11:13 +08:00
junleea 94e6a5c5ab Merge branch 'refs/heads/master' into fearture-realvp 2024-07-18 10:10:27 +08:00
junleea 2b2035b4df Merge branch 'refs/heads/feature-im' into feature-cid
# Conflicts:
#	handler/im.go
2024-07-18 09:34:00 +08:00
junleea 8e894b003f 修改im的在线检测 2024-07-16 16:27:31 +08:00
junleea 422e312b95 修改im的在线检测 2024-07-16 16:17:21 +08:00
20 changed files with 768 additions and 75 deletions

View File

@ -3,6 +3,7 @@ package dao
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"videoplayer/proto"
)
@ -10,9 +11,17 @@ import (
var DB *gorm.DB
func Init() error {
dsn := proto.MYSQL_DSN
var db *gorm.DB
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 {
panic("failed to connect database")
return err
@ -51,6 +60,11 @@ func Init() error {
fmt.Println("message table:", err)
}
err = db.AutoMigrate(&File{})
if err != nil {
fmt.Println("file table:", err)
}
err = db.AutoMigrate(&Group{})
if err != nil {
fmt.Println("usergroup table:", err)

77
dao/file.go Normal file
View File

@ -0,0 +1,77 @@
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
}

View File

@ -236,6 +236,12 @@ type FriendRet struct {
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 {
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)

View File

@ -14,6 +14,9 @@ type User struct {
Password string `gorm:"column:password"`
Gender string `gorm:"column:gender"`
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"`
UpdateTime string `gorm:"column:update_time"`
}

View File

@ -65,13 +65,13 @@ func FindVideoByID(id, auth_id int) Video {
// 根据用户id查找视频列表,返回最新30条
func FindVideoListsByAuthID(auth_id int) []Video {
var videos []Video
DB.Debug().Where("auth_id = ? and isdelete =? ", auth_id, 0).Order("create_time DESC").Limit(30).Find(&videos)
DB.Debug().Where("auth_id = ? and isdelete =? ", auth_id, 0).Order("created_at DESC").Limit(30).Find(&videos)
return videos
}
func FindVideoListByTime(auth_id int, startTime, endTime string) []Video {
var videos []Video
DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete=0").Where("create_time > ? and create_time < ?", startTime, endTime).Find(&videos)
DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete=0").Where("created_at > ? and created_at < ?", startTime, endTime).Find(&videos)
return videos
}
@ -112,6 +112,6 @@ func QuashAllDelay(user_id int, day int) int {
// 获取视频列表分页
func GetVideoListByPage(auth_id, page, pageSize int) []Video {
var videos []Video
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是限制条数
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是限制条数
return videos
}

10
go.mod
View File

@ -9,7 +9,8 @@ require (
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
gorm.io/driver/mysql v1.5.6
gorm.io/gorm v1.25.7
gorm.io/driver/postgres v1.5.9
gorm.io/gorm v1.25.10
)
require (
@ -26,20 +27,27 @@ require (
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-sql-driver/mysql v1.7.0 // 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/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // 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/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.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/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.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/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect

25
go.sum
View File

@ -8,6 +8,7 @@ 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/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
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.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -44,6 +45,14 @@ 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/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
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/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
@ -54,6 +63,10 @@ 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/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
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/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@ -73,6 +86,8 @@ 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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
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.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@ -96,6 +111,8 @@ 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/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
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.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
@ -106,8 +123,9 @@ 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=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
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 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/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
@ -117,7 +135,10 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
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/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
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.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=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@ -50,10 +50,17 @@ func SetUpCIDGroup(router *gin.Engine) {
}
func RunCID(c *gin.Context) {
var req CIDRunReq
if err := c.ShouldBind(&req); err == nil {
// 获取用户ID
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 {
// 获取用户ID
username, _ := c.Get("username")
cid := dao.FindCIDByID(req.ID, authID)
if cid.ID == 0 {
@ -165,11 +172,22 @@ func CIDCallback(c *gin.Context) {
fmt.Println("token:", token, "cid_id:", cid_id)
//将cid转换为int
cid, _ := strconv.Atoi(cid_id)
if token == "" || cid == 0 {
c.JSON(200, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
return
}
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 {
user := dao.FindUserByID(res.Auth_id)
go RunShell(user[0].Name, res.Url, res.Script, int(res.ID), res.Auth_id)

View File

@ -57,6 +57,7 @@ func SetUpDeviceGroup(router *gin.Engine) {
deviceGroup.POST("/set_device_status", SetDeviceStatus)
deviceGroup.POST("/update_device", UpdateDevice)
deviceGroup.POST("/delete_device", DeleteDevice)
deviceGroup.GET("/get_real_time_image", GetRealTimeImage)
}
@ -233,6 +234,7 @@ func GetRealTimeImage(c *gin.Context) {
go func(ws *websocket.Conn, device_id int) {
}(ws, device_id_int)
var check_cnt int
for {
if v := clients[ws]; v == true {
@ -247,12 +249,19 @@ func GetRealTimeImage(c *gin.Context) {
res3, _ = json.Marshal(msg)
} else {
//若无消息则发送心跳包
if check_cnt < 5 {
check_cnt++
time.Sleep(time.Millisecond * 200) //设置延时200ms
continue
}
check_cnt = 0
msg.Type = "check"
msg.Msg = "check"
msg.From_user_id = -1
res3, _ = json.Marshal(msg)
}
err2 := ws.WriteMessage(websocket.TextMessage, res3)
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "1", time.Minute*5) //设置播放状态
if err2 != nil {
clientsMux.Lock()
clients[ws] = false
@ -261,7 +270,7 @@ func GetRealTimeImage(c *gin.Context) {
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "0", time.Minute*5) //设置播放状态
break
}
time.Sleep(time.Millisecond * 100) //设置延时100ms
time.Sleep(time.Millisecond * 200) //设置延时200ms
}
}
}

185
handler/tool.go Normal file
View File

@ -0,0 +1,185 @@
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
}
}

View File

@ -15,8 +15,6 @@ import (
"videoplayer/worker"
)
var signingKey = []byte(proto.TOKEN_SECRET)
func SetUpUserGroup(router *gin.Engine) {
userGroup := router.Group("/user")
userGroup.POST("/register", registerHandler)
@ -170,7 +168,7 @@ func GetQRStatus(c *gin.Context) {
default:
// 解析 JWT 令牌
token, err := jwt.Parse(str, func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
return proto.SigningKey, nil
})
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenParseError, "message": "error"})
@ -230,7 +228,7 @@ func loginHandler(c *gin.Context) {
"id": user.ID,
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 10小时后过期
})
tokenString, err = token.SignedString(signingKey)
tokenString, err = token.SignedString(proto.SigningKey)
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
return
@ -287,7 +285,7 @@ func registerHandler(c *gin.Context) {
"id": id,
"exp": time.Now().Add(time.Hour * 10).Unix(), // 令牌过期时间, 1分钟后过期
})
tokenString, err = token.SignedString(signingKey)
tokenString, err = token.SignedString(proto.SigningKey)
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
return

29
main.go
View File

@ -12,12 +12,9 @@ import (
"videoplayer/worker"
)
var signingKey = []byte(proto.TOKEN_SECRET)
func main() {
r := gin.Default()
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
err := dao.Init()
if err != nil {
panic("failed to connect database:" + err.Error())
@ -33,15 +30,24 @@ func main() {
handler.SetUpDeviceGroup(r) // Device
handler.SetUpIMGroup(r) // IM
handler.SetUpCIDGroup(r) // CID,持续集成、部署
r.Run(":8083") // listen and serve on 0.0.0.0:8082
handler.SetUpToolGroup(r) // Tool
defer dao.Close()
defer worker.CloseRedis()
r.Run(":8083") // listen and serve on 0.0.0.0:8083
}
func init() {
// 创建cid的目录
os.MkdirAll(proto.CID_BASE_DIR, os.ModePerm)
os.MkdirAll(proto.CID_BASE_DIR+"script", 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) {
@ -49,10 +55,11 @@ func writeLogger(c *gin.Context) {
method := c.Request.Method
path := c.Request.URL.Path
params := ""
if method == "GET" {
params = c.Request.URL.RawQuery
}
if method == "POST" {
if method == "POST" && !strings.Contains(c.Request.URL.Path, "/upload") {
params = c.Request.PostForm.Encode()
if params == "" {
// 请求体
@ -61,6 +68,9 @@ func writeLogger(c *gin.Context) {
params = string(bodyBytes)
}
}
if strings.Contains(c.Request.URL.Path, "/upload") {
params = "upload file"
}
go dao.InsertLogToDB(path, ip, method, params)
}
@ -89,8 +99,8 @@ func JWTAuthMiddleware() gin.HandlerFunc {
})
return
}
if proto.Config.TOKEN_USE_REDIS {
redisToken := worker.GetRedis(tokenString)
if redisToken == "" {
c.AbortWithStatus(200)
c.JSON(200, gin.H{
@ -100,10 +110,11 @@ func JWTAuthMiddleware() gin.HandlerFunc {
})
return
}
}
// 解析 JWT 令牌
// 使用加密secret 解析 JWT 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
return proto.SigningKey, nil
})
// 验证令牌

View File

@ -1,6 +1,14 @@
package proto
import "gorm.io/gorm"
import (
"encoding/json"
"fmt"
"gorm.io/gorm"
"os"
)
var Config ConfigStruct
var SigningKey = []byte{}
const (
MYSQL_USER = "video_t2"
@ -18,6 +26,9 @@ const (
// 以下是持续集成、部署的配置
CID_BASE_DIR = "/home/lijun/cid/"
// 以下是文件上传的配置
FILE_BASE_DIR = "/home/lijun/file/"
)
const (
@ -34,6 +45,13 @@ const (
MSG_STATUS_UNREAD = 0 // 未读
)
const (
//文件上传类型
File_TYPE = 1 // 通用文件
//用于视频解析
Video_TYPE = 2 // 视频文件
)
type User struct {
gorm.Model
Name string `gorm:"column:name"`
@ -41,3 +59,35 @@ type User struct {
Email string `gorm:"column:email"`
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
}

View File

@ -42,6 +42,21 @@ const (
// UUID相关错误码
UUIDNotFound = 18 // uuid不存在
//Tool
NoRedisPermissions = 51
NoRunPermissions = 52
NoDevicePermissions = 53
//消息错误码
MsgSendFailed = 61 // 消息发送失败
//文件错误码
FileNotFound = 71 // 文件不存在
FileUploadFailed = 72 // 文件上传失败
SaveFileInfoFailed = 73 // 保存文件信息失败
SaveFileFailed = 74 // 保存文件失败
UploadFileFailed = 75 // 上传文件失败
NoUploadPermissions = 76 // 无上传权限
DeleteFileFailed = 77 // 删除文件失败
DeleteFileInfoFailed = 78 // 删除文件信息失败
)

47
service/fileService.go Normal file
View File

@ -0,0 +1,47 @@
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
}

View File

@ -15,11 +15,31 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
var id uint
switch msg_type {
case proto.MSG_TYPE_SIMPLE:
//判断是否是好友
//判断是否是好友,判断是否存在缓存,不存在则设置缓存,存在则判断是否是好友
if worker.IsContainKey("user_"+strconv.Itoa(from_id)+"_friends") == false {
//设置好友缓存
isSuccess := SetFriendCache(from_id)
//设置失败,直接查询数据库
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)
res := worker.GetRedis("user_" + strconv.Itoa(to_id) + "_status_v2")
if res == "1" {
@ -30,11 +50,31 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
if from_id == 0 || group_id == 0 || content == "" {
return errors.New("参数错误"), 0
}
//判断该用户是否在群里
//判断是否在群里
if worker.IsContainKey("group_"+strconv.Itoa(group_id)+"_users") == false {
//设置群缓存
isSuccess := SetGroupCache(group_id)
//设置失败,直接查询数据库
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)
//获取群里的用户
users := dao.FindGroupUsers(group_id)
@ -64,6 +104,7 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
return errors.New("已有请求"), res[0].ID
}
err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content)
case proto.MSG_TYPE_GROUP_ADD:
//加入群聊请求
//判断是否在群里
@ -91,6 +132,13 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content
return errors.New("已在群里"), 0
}
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:
// 未知消息类型
err = errors.New("unknown message type")
@ -130,7 +178,17 @@ func AddFriendService(id, from_user_id, to_user_id int) error {
return errors.New("already a friend")
}
dao.UpdateMessageStatus(res[0].ID, 1)
return dao.AddFriend(from_user_id, to_user_id)
res2 := 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 {
//加入群聊
//查看是否已经加入
@ -185,12 +243,20 @@ func GetFriendRequest(user_id int) []dao.FriendRequest {
func DelFriendService(user_id, friend_id int) error {
//删除好友
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
}
func QuitGroupService(user_id, group_id int) error {
//退出群聊
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
}
func DelGroupService(user_id, group_id int) error {
@ -231,3 +297,27 @@ func GetGroupRequestUsers(user_id int) []dao.FriendRequest {
users := dao.GetGroupRequestUsers(user_id)
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
}

70
service/toolService.go Normal file
View File

@ -0,0 +1,70 @@
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 Normal file
View File

@ -0,0 +1,13 @@
{
"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/",
}

View File

@ -15,12 +15,21 @@ import (
var redisClient *redis.Client // Redis 客户端, 用于连接 Redis 服务器
func InitRedis() error {
ctx := context.Background()
if proto.Config.REDIS_User_PW == false {
// 连接redis
redisClient = redis.NewClient(&redis.Options{
Addr: proto.REDIS_ADDR, // Redis 服务器地址
Password: proto.REDIS_PASSWORD, // 如果 Redis 设置了密码
DB: proto.REIDS_DB, // 使用的数据库编号
Addr: proto.Config.REDIS_ADDR, // Redis 服务器地址
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 客户端是否可以正常工作
_, err := redisClient.Ping(ctx).Result()
@ -255,3 +264,52 @@ func hGetRedis(key string, field string) string {
}
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
}