Compare commits

...

10 Commits

13 changed files with 325 additions and 108 deletions

View File

@ -24,3 +24,6 @@
18 | uuid不存在
19 | Token解析错误
20 | 获取redis错误
30 | 撤销
31 | 撤销延迟操作失败、
32 | 撤销操作失败

View File

@ -4,12 +4,13 @@ import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"videoplayer/proto"
)
var DB *gorm.DB
func Init() {
dsn := "video_t2:2t2SKHmWEYj2xFKF@tcp(127.0.0.1:3306)/video_t2?charset=utf8mb4&parseTime=True&loc=Local"
dsn := proto.MYSQL_DSN
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {

View File

@ -92,3 +92,19 @@ func DelayAllVideo(id, day int) int {
}
return int(res.RowsAffected)
}
func QuashOneDelay(id, user_id int, day int) int {
res := DB.Debug().Exec("update videos set delete_time = date_sub(delete_time, interval ? day) where id = ? and auth_id = ? and isdelete=0", day, id, user_id)
if res.Error != nil {
return 0
}
return int(res.RowsAffected)
}
func QuashAllDelay(user_id int, day int) int {
res := DB.Debug().Exec("update videos set delete_time = date_sub(delete_time, interval ? day) where auth_id = ? and isdelete=0", day, user_id)
if res.Error != nil {
return 0
}
return int(res.RowsAffected)
}

2
go.mod
View File

@ -6,6 +6,7 @@ require (
github.com/gin-gonic/gin v1.10.0
github.com/go-redis/redis/v8 v8.11.5
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/google/uuid v1.6.0
gorm.io/driver/mysql v1.5.6
gorm.io/gorm v1.25.7
)
@ -24,7 +25,6 @@ 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/google/uuid v1.6.0 // 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

View File

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"videoplayer/proto"
"videoplayer/service"
)
@ -60,12 +61,12 @@ func DeleteDevice(c *gin.Context) {
var req DeviceDelReq
if err := c.ShouldBindJSON(&req); err == nil {
if service.DeleteDevice(req.ID, int(id.(float64))) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(200, gin.H{"code": 17, "message": "failed"})
c.JSON(200, gin.H{"code": proto.OperationFailed, "message": "failed"})
}
} else {
c.JSON(200, gin.H{"code": 9, "message": "failed"})
c.JSON(200, gin.H{"code": proto.ParameterError, "message": "failed"})
}
}
@ -81,13 +82,13 @@ func UpdateDevice(c *gin.Context) {
})
} else {
c.JSON(200, gin.H{
"code": 16,
"code": proto.DeviceUpdateFailed,
"message": "failed",
})
}
} else {
c.JSON(200, gin.H{
"code": 9,
"code": proto.ParameterError,
"message": "failed",
})
}
@ -98,13 +99,13 @@ func SetDeviceStatus(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err == nil {
if req.IP != "" {
if service.SetDeviceStatus(req.Status, req.ID, int(id.(float64))) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}
} else {
c.JSON(200, gin.H{"code": 9, "message": "failed", "data": err.Error()})
c.JSON(200, gin.H{"code": proto.ParameterError, "message": "failed", "data": err.Error()})
}
}
@ -117,20 +118,20 @@ func AddDevice(c *gin.Context) {
device_id := service.AddDevice(req.DeviceName, req.DeviceIP, req.DeviceStatus, req.DeviceInfo, req.DeviceType, req.DeviceLocation, user_id)
if device_id != 0 {
c.JSON(200, gin.H{
"code": 0,
"code": proto.SuccessCode,
"message": "success",
"data": device_id,
})
} else {
c.JSON(200, gin.H{
"code": 15,
"code": proto.DeviceAddFailed,
"message": "failed",
"data": "device add failed",
})
}
} else {
c.JSON(200, gin.H{
"code": 9,
"code": proto.ParameterError,
"message": "failed",
"data": err.Error(),
})
@ -141,7 +142,7 @@ func GetDeviceList(c *gin.Context) {
id, _ := c.Get("id")
devices := service.GetDeviceList(int(id.(float64)))
c.JSON(200, gin.H{
"code": 0,
"code": proto.SuccessCode,
"message": "success",
"data": devices,
})
@ -151,7 +152,7 @@ func RestartDevice(c *gin.Context) {
user_id, _ := c.Get("id")
var req DeviceRestartReq
if err := c.ShouldBind(&req); err != nil {
c.JSON(200, gin.H{"code": 9, "message": "failed", "data": err.Error()})
c.JSON(200, gin.H{"code": proto.ParameterError, "message": "failed", "data": err.Error()})
return
}
device_id := req.ID
@ -160,13 +161,13 @@ func RestartDevice(c *gin.Context) {
if device.ID != 0 {
if device.DeviceIP != "" {
if Restart(device.DeviceIP) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(200, gin.H{"code": 13, "message": "failed"})
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": "failed"})
}
}
} else {
c.JSON(200, gin.H{"code": 14, "message": "failed", "data": string(device_id) + ": device not found"})
c.JSON(200, gin.H{"code": proto.DataNotFound, "message": "failed", "data": string(device_id) + ": device not found"})
}
} else if req.Option == "all" {
devices := service.GetDeviceList(int(user_id.(float64)))
@ -174,15 +175,15 @@ func RestartDevice(c *gin.Context) {
for _, device := range devices {
if device.DeviceIP != "" {
if !Restart(device.DeviceIP) {
c.JSON(200, gin.H{"code": 13, "message": "failed"})
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": "failed"})
return
}
}
}
} else {
c.JSON(200, gin.H{"code": 14, "message": "failed", "data": "device not found"})
c.JSON(200, gin.H{"code": proto.DataNotFound, "message": "failed", "data": "device not found"})
}
c.JSON(200, gin.H{"code": 0, "message": "success"})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success"})
}
}

View File

@ -3,16 +3,18 @@ package handler
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"time"
"videoplayer/proto"
"videoplayer/service"
"videoplayer/worker"
)
var signingKey = []byte("aadafcvretmoi9")
var signingKey = []byte(proto.TOKEN_SECRET)
func SetUpUserGroup(router *gin.Engine) {
userGroup := router.Group("/user")
@ -41,16 +43,26 @@ type QRReq struct {
func GetScanUUID(c *gin.Context) {
var ReqData QRReq
if err := c.ShouldBind(&ReqData); err != nil {
c.JSON(200, gin.H{"code": 9, "message": err, "data": "2"})
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err, "data": "2"})
return
}
data := map[string]interface{}{"status": "0", "address": ReqData.Address, "ip": c.ClientIP()}
jsonData, err := json.Marshal(data)
if err != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err, "data": "2"})
return
}
id := uuid.New()
res := worker.SetHash(id.String(), map[string]interface{}{"status": "0", "address": ReqData.Address, "ip": c.ClientIP()})
res := worker.SetRedisWithExpire(id.String(), string(jsonData), time.Minute*30)
if res {
data := worker.GetHashAll(id.String())
c.JSON(200, gin.H{"code": 0, "message": data, "data": id.String()})
var retrievedData map[string]interface{}
if err2 := json.Unmarshal([]byte(worker.GetRedis(id.String())), &retrievedData); err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": retrievedData, "data": id.String()})
} else {
c.JSON(200, gin.H{"code": 8, "message": "qr code invalid", "data": "1"})
c.JSON(200, gin.H{"code": proto.RedisSetError, "message": "qr code invalid", "data": "1"})
}
}
@ -58,18 +70,28 @@ func SetQRStatus(c *gin.Context) {
var qrsetReq QRReq
if err := c.ShouldBind(&qrsetReq); err == nil && qrsetReq.UUID != "" {
if worker.IsContainKey(qrsetReq.UUID) == false {
c.JSON(200, gin.H{"code": 18, "message": "uuid not found in server", "data": "0"})
c.JSON(200, gin.H{"code": proto.UUIDNotFound, "message": "uuid not found in server", "data": "0"})
return
}
res := worker.SetHashWithField(qrsetReq.UUID, "status", "1")
var retrievedData map[string]interface{}
if err2 := json.Unmarshal([]byte(worker.GetRedis(qrsetReq.UUID)), &retrievedData); err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
retrievedData["status"] = "1"
jsonData, err2 := json.Marshal(retrievedData)
if err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
res := worker.SetRedisWithExpire(qrsetReq.UUID, string(jsonData), time.Minute*30)
if res {
data := worker.GetHashAll(qrsetReq.UUID)
c.JSON(200, gin.H{"code": 0, "message": "success", "data": data})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": retrievedData})
} else {
c.JSON(200, gin.H{"code": 8, "message": "qr code invalid", "data": "1"})
c.JSON(200, gin.H{"code": proto.RedisSetError, "message": "qr code invalid", "data": "1"})
}
} else {
c.JSON(200, gin.H{"code": 9, "message": err, "data": "2"})
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err, "data": "2"})
}
}
@ -83,49 +105,59 @@ func ConfirmQRLogin(c *gin.Context) {
key := "user_" + user_name.(string)
token := worker.GetRedis(key)
if token == "" {
c.JSON(200, gin.H{"code": 20, "message": "Token不存在", "data": "20"})
c.JSON(200, gin.H{"code": proto.RedisGetError, "message": "Token不存在", "data": "20"})
}
if worker.IsContainKey(qrsetReq.UUID) == false {
c.JSON(200, gin.H{"code": 18, "message": "uuid not found in server", "data": "0"})
c.JSON(200, gin.H{"code": proto.UUIDNotFound, "message": "uuid not found in server", "data": "0"})
return
}
if worker.SetHashWithField(qrsetReq.UUID, "status", token) {
var retrievedData map[string]interface{}
if err2 := json.Unmarshal([]byte(worker.GetRedis(qrsetReq.UUID)), &retrievedData); err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
retrievedData["status"] = token
jsonData, err2 := json.Marshal(retrievedData)
if err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
if worker.SetRedisWithExpire(qrsetReq.UUID, string(jsonData), time.Minute*10) {
c.JSON(200, gin.H{"code": 0, "message": "success", "data": "0"})
} else {
c.JSON(200, gin.H{"code": 8, "message": "设置Token失败", "data": "8"})
c.JSON(200, gin.H{"code": proto.RedisSetError, "message": "设置Token失败", "data": "8"})
}
} else {
c.JSON(200, gin.H{"code": 20, "message": "failed", "data": "20"})
c.JSON(200, gin.H{"code": proto.RedisGetError, "message": "failed", "data": "20"})
}
} else {
c.JSON(200, gin.H{"code": 9, "message": err, "data": "3"})
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err, "data": "3"})
}
}
func GetQRStatus(c *gin.Context) {
var qrReq QRReq
if err := c.ShouldBind(&qrReq); err == nil {
end := worker.SetHashWithField(qrReq.UUID, "address", qrReq.Address)
end_ := worker.SetHashWithField(qrReq.UUID, "ip", qrReq.IP)
if !end || !end_ {
c.JSON(200, gin.H{"code": 8, "message": "set redis failed", "data": "8"})
var retrievedData map[string]interface{}
if err2 := json.Unmarshal([]byte(worker.GetRedis(qrReq.UUID)), &retrievedData); err2 != nil {
c.JSON(200, gin.H{"code": proto.DeviceRestartFailed, "message": err2, "data": "2"})
return
}
str := worker.GetHash(qrReq.UUID, "status")
str := retrievedData["status"].(string)
switch str {
case "":
c.JSON(200, gin.H{"code": 18, "message": "uuid not found", "data": "0"}) //空值
c.JSON(200, gin.H{"code": proto.UUIDNotFound, "message": "uuid not found", "data": "0"}) //空值
case "0":
c.JSON(200, gin.H{"code": 0, "message": "success", "data": "0"}) //空值
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "0"}) //空值
case "1":
c.JSON(200, gin.H{"code": 0, "message": "success", "data": "1"}) //已扫描待确认
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "1"}) //已扫描待确认
default:
// 解析 JWT 令牌
token, err := jwt.Parse(str, func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
})
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": 19, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenParseError, "message": "error"})
return
}
// 返回令牌
@ -134,10 +166,10 @@ func GetQRStatus(c *gin.Context) {
data["username"] = token.Claims.(jwt.MapClaims)["username"]
data["email"] = token.Claims.(jwt.MapClaims)["email"]
data["token"] = str
c.JSON(200, gin.H{"code": 0, "message": "success", "data": data}) //确认返回token数据
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": data}) //确认返回token数据
}
} else {
c.JSON(200, gin.H{"error": err.Error(), "code": 9, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.DeviceRestartFailed, "message": "error"})
}
}
@ -163,7 +195,7 @@ func loginHandler(c *gin.Context) {
})
tokenString, err = token.SignedString(signingKey)
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": 5, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
return
}
@ -183,13 +215,13 @@ func loginHandler(c *gin.Context) {
data["username"] = user.Name
data["email"] = user.Email
data["token"] = tokenString
c.JSON(200, gin.H{"code": 0, "message": "success", "data": data})
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": data})
} else {
//用户名或密码错误
c.JSON(200, gin.H{"error": "用户名或密码错误", "code": 6, "message": "error"})
c.JSON(200, gin.H{"error": "用户名或密码错误", "code": proto.UsernameOrPasswordError, "message": "error"})
}
} else {
c.JSON(200, gin.H{"error": err.Error(), "code": 9, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.DeviceRestartFailed, "message": "error"})
}
}
@ -203,7 +235,7 @@ func registerHandler(c *gin.Context) {
req_data.Password = hex.EncodeToString(hasher.Sum(nil)) // 生成密码的 MD5 散列值
}
if service.ContainsUser(req_data.User, req_data.Email) == true {
c.JSON(200, gin.H{"error": "user already exists", "code": 7, "message": "error"})
c.JSON(200, gin.H{"error": "user already exists", "code": proto.UsernameExists, "message": "error"})
return
}
id := service.CreateUser(req_data.User, req_data.Password, req_data.Email)
@ -215,17 +247,17 @@ func registerHandler(c *gin.Context) {
})
tokenString, err = token.SignedString(signingKey)
if err != nil {
c.JSON(200, gin.H{"error": err.Error(), "code": 5, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.TokenGenerationError, "message": "error"})
}
} else {
c.JSON(200, gin.H{"error": err.Error(), "code": 9, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": proto.DeviceRestartFailed, "message": "error"})
}
fmt.Println(req_data)
res := worker.SetRedisWithExpire(tokenString, tokenString, time.Hour*10) // 设置过期时间为10分钟
if !res {
c.JSON(200, gin.H{"error": "set token error", "code": 8, "message": "error"})
c.JSON(200, gin.H{"error": "set token error", "code": proto.RedisSetError, "message": "error"})
return
}
// 返回令牌
c.JSON(200, gin.H{"token": tokenString, "username": req_data.User, "code": 0, "message": "success"})
c.JSON(200, gin.H{"token": tokenString, "username": req_data.User, "code": proto.SuccessCode, "message": "success"})
}

View File

@ -1,13 +1,16 @@
package handler
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"os"
"strconv"
"time"
"videoplayer/proto"
"videoplayer/service"
"videoplayer/worker"
)
// video获取视频列表请求
@ -77,12 +80,13 @@ func SetUpVideoGroup(router *gin.Engine) {
videoGroup.POST("/delay", DelayVideo)
videoGroup.POST("/delete", DeleteVideo)
videoGroup.POST("/update", UpdateVideo)
videoGroup.POST("/quash_option", QuashOption)
}
func GetWillDelVideoList(c *gin.Context) {
id, _ := c.Get("id")
videos := service.GetWillDelVideoList(int(id.(float64)))
c.JSON(http.StatusOK, gin.H{"videos": videos, "code": 0, "message": "success"})
c.JSON(http.StatusOK, gin.H{"videos": videos, "code": proto.SuccessCode, "message": "success"})
}
@ -92,12 +96,12 @@ func UpdateVideo(c *gin.Context) {
if err := c.ShouldBind(&video_req); err == nil {
res := service.UpdateVideo(video_req.VideoPath, video_req.VideoName, video_req.CameraID, video_req.ID, int(user_id.(float64)), video_req.Human, video_req.IsDelete, video_req.CreateTime, video_req.EndTime, video_req.FileSize)
if !res {
c.JSON(http.StatusOK, gin.H{"error": "update video failed", "code": 17, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": "update video failed", "code": proto.OperationFailed, "message": "failed"})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": "update success"})
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success", "data": "update success"})
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 9, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}
@ -139,33 +143,35 @@ func CreateVideo(c *gin.Context) {
fmt.Println(video_req)
id := service.CreateVideo(video_req.VideoPath, video_req.VideoName, video_req.CameraID, int(user_id.(float64)), video_req.Human, video_req.IsDelete, video_req.CreateTime, video_req.EndTime, video_req.DeleteTime, video_req.FileSize)
if id == 0 {
c.JSON(http.StatusOK, gin.H{"error": "create video failed", "code": 14, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": "create video failed", "code": proto.DataNotFound, "message": "failed"})
return
}
c.JSON(http.StatusOK, gin.H{"id": id, "code": 0, "message": "success"})
c.JSON(http.StatusOK, gin.H{"id": id, "code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 9, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}
func GetVideoList(c *gin.Context) {
var gvl_req gvlReq
gvl_req.Hour = "33"
id, _ := c.Get("id")
if err := c.ShouldBind(&gvl_req); err == nil {
videos := service.GetVideoList(int(id.(float64)), gvl_req.StartTime, gvl_req.EndTime)
c.JSON(http.StatusOK, gin.H{"data": videos, "code": 0, "message": "success"})
videos := service.GetVideoList(int(id.(float64)), gvl_req.StartTime, gvl_req.EndTime, gvl_req.Hour)
c.JSON(http.StatusOK, gin.H{"data": videos, "code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 9, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}
func DelayVideo(c *gin.Context) {
var delay_req delayReq
id, _ := c.Get("id")
user, _ := c.Get("username")
cnt := 0
if err := c.ShouldBind(&delay_req); err == nil {
if delay_req.Day > 30 || delay_req.Day < 1 {
c.JSON(http.StatusOK, gin.H{"code": 11, "data": "延迟天数过大或过小", "message": "failed"})
c.JSON(http.StatusOK, gin.H{"code": proto.VideoDelayOperationFailed, "data": "延迟天数过大或过小", "message": "failed"})
return
}
if delay_req.Option == "all" {
@ -175,22 +181,53 @@ func DelayVideo(c *gin.Context) {
cnt = service.DelayVideo(delay_req.ID, int(id.(float64)), delay_req.Day)
}
if cnt == 0 {
c.JSON(http.StatusOK, gin.H{"code": 17, "data": "延迟失败影响数据", "message": "failed,cnt:" + strconv.Itoa(cnt)})
c.JSON(http.StatusOK, gin.H{"code": proto.OperationFailed, "data": "延迟失败数据", "message": "failed,cnt:" + strconv.Itoa(cnt)})
} else {
c.JSON(http.StatusOK, gin.H{"code": 0, "data": "延迟成功,影响记录:" + strconv.Itoa(cnt), "message": "success cnt:" + strconv.Itoa(cnt)})
data := map[string]interface{}{"auth_id": int(id.(float64)), "method": "delay", "delay_time": time.Now().Format("2006-01-02 15:04:05"), "delay_day": delay_req.Day, "option": delay_req.Option, "id": delay_req.ID}
str, _ := json.Marshal(data)
worker.PushRedisList(user.(string)+"-"+strconv.Itoa(int(id.(float64)))+"-option", string(str))
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "data": "延迟成功,影响记录:" + strconv.Itoa(cnt), "message": "success cnt:" + strconv.Itoa(cnt)})
}
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 9, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}
func DeleteVideo(c *gin.Context) {
var video_req VideoDelReq
id, _ := c.Get("id")
user, _ := c.Get("username")
if err := c.ShouldBind(&video_req); err == nil {
service.DeleteVideo(video_req.ID, int(id.(float64)))
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success"})
res := service.DeleteVideo(video_req.ID, int(id.(float64)))
if res != 0 {
data := map[string]interface{}{"id": video_req.ID, "auth_id": int(id.(float64)), "delete_time": time.Now().Format("2006-01-02 15:04:05"), "method": "delete"}
str, _ := json.Marshal(data)
worker.PushRedisList(user.(string)+"-"+strconv.Itoa(int(id.(float64)))+"-option", string(str))
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success"})
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 9, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"code": proto.ParameterError, "message": "failed"})
}
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}
func QuashOption(c *gin.Context) {
id, _ := c.Get("id")
user, _ := c.Get("username")
res := worker.PopRedisList(user.(string) + "-" + strconv.Itoa(int(id.(float64))) + "-option")
if res != "" {
var retrievedData map[string]interface{}
err2 := json.Unmarshal([]byte(res), &retrievedData)
if err2 == nil {
code, msg := service.QuashVideo(int(id.(float64)), retrievedData)
c.JSON(http.StatusOK, gin.H{"code": code, "message": msg, "data": msg})
} else {
worker.PushRedisList(user.(string)+"-"+strconv.Itoa(int(id.(float64)))+"-option", res) //未操作成功重新添加到队列
c.JSON(http.StatusOK, gin.H{"code": proto.ParameterError, "message": err2, "data": "json解析错误"})
return
}
} else {
c.JSON(http.StatusOK, gin.H{"code": proto.ParameterError, "message": "redis data not found", "data": "error"})
}
}

15
main.go
View File

@ -1,17 +1,17 @@
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"io"
"strings"
"videoplayer/dao"
"videoplayer/handler"
"videoplayer/proto"
"videoplayer/worker"
)
var signingKey = []byte("aadafcvretmoi9")
var signingKey = []byte(proto.TOKEN_SECRET)
func main() {
@ -45,10 +45,7 @@ func writeLogger(c *gin.Context) {
params = string(bodyBytes)
}
}
res := dao.InsertLogToDB(path, ip, method, params)
if res == 0 {
fmt.Println("insert log failed")
}
go dao.InsertLogToDB(path, ip, method, params)
}
func JWTAuthMiddleware() gin.HandlerFunc {
@ -72,7 +69,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
c.JSON(200, gin.H{
"message": "Unauthorized",
"error": "token is empty",
"code": "3",
"code": proto.TokenIsNull,
})
return
}
@ -83,7 +80,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "server token is empty",
"code": "3",
"code": proto.TokenIsNull,
})
return
}
@ -99,7 +96,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "Invalid token",
"code": "4",
"code": proto.TokenExpired,
})
return
}

16
proto/conf.go Normal file
View File

@ -0,0 +1,16 @@
package proto
const (
MYSQL_USER = "video_t2"
MYSQL_DB = "video_t2"
MYSQL_PASSWORD = "2t2SKHmWEYj2xFKF"
MYSQL_PORT = "3306"
MYSQL_HOST = "127.0.0.1"
MYSQL_DSN = MYSQL_USER + ":" + MYSQL_PASSWORD + "@tcp(" + MYSQL_HOST + ":" + MYSQL_PORT + ")/" + MYSQL_DB + "?charset=utf8mb4&parseTime=True&loc=Local"
REDIS_ADDR = "127.0.0.1:6379"
REDIS_PASSWORD = "lj502138"
REIDS_DB = 2
TOKEN_SECRET = "mfjurnc_32ndj9dfhj"
)

44
proto/status.go Normal file
View File

@ -0,0 +1,44 @@
package proto
const (
SuccessCode = 0 // 成功
// 通用错误码
ErrorCode = 1 // 未知错误或服务器内部错误
ParameterError = 9 // 请求参数解析错误
OperationFailed = 17 // 数据库数据操作失败
DataNotFound = 14 // 查询数据失败
InternalServerError = 10 // 服务器内部错误
// Token相关错误码
TokenInvalid = 2 // Token失效未登录
TokenIsNull = 3 // Token为空
TokenExpired = 4 // Token已过期
TokenGenerationError = 5 // Token生成错误
TokenParseError = 19 // Token解析错误
// 用户名密码相关错误码
UsernameOrPasswordError = 6 // 用户名或密码错误
UsernameExists = 7 // 用户名已存在
// Redis相关错误码
RedisSetError = 8 // 设置redis错误
RedisGetError = 20 // 获取redis错误
// 视频操作相关错误码
VideoDelayOperationFailed = 11 // 视频延迟操作失败
VideoDeleteFailed = 12 // 视频删除失败
// 设备操作相关错误码
DeviceRestartFailed = 13 // 设备重启失败
DeviceAddFailed = 15 // 设备添加失败
DeviceUpdateFailed = 16 // 设备修改失败
// 撤销操作相关错误码
RevokeOperation = 30 // 撤销
RevokeDelayOperationFailed = 31 // 撤销延迟操作失败
RevokeOperationFailed = 32 // 撤销操作失败
// UUID相关错误码
UUIDNotFound = 18 // uuid不存在
)

View File

@ -2,8 +2,9 @@ package service
import (
"fmt"
"time"
"strings"
"videoplayer/dao"
"videoplayer/proto"
)
func GetVideo(id, auth_id int) dao.Video {
@ -14,23 +15,39 @@ func GetWillDelVideoList(id int) []dao.Video {
return dao.FindWillDelVideoList(id)
}
func GetVideoList(auth_id int, start, end string) []dao.Video {
func GetVideoList(auth_id int, start, end, hour string) []dao.Video {
if start == "" {
return dao.FindVideoListsByAuthID(auth_id)
} else {
s, err := time.Parse("2006/1/02 15:04:05", start)
if err != nil {
s, err = time.Parse("2006/01/02 15:04:05", start)
}
e, err2 := time.Parse("2006/1/02 15:04:05", end)
if err2 != nil {
e, err2 = time.Parse("2006/01/02 15:04:05", end)
}
if s.After(e) || err != nil || err2 != nil {
fmt.Println(err)
fmt.Println(err2)
return []dao.Video{}
//s, err := time.Parse("2006/1/02 15:04:05", start)
//if err != nil {
// s, err = time.Parse("2006/01/02 15:04:05", start)
//}
//e, err2 := time.Parse("2006/1/02 15:04:05", end)
//if err2 != nil {
// e, err2 = time.Parse("2006/01/02 15:04:05", end)
//}
//if s.After(e) || err != nil || err2 != nil {
// fmt.Println(err)
// fmt.Println(err2)
// return []dao.Video{}
//}
start = strings.Replace(start, "/", "-", -1)
end = strings.Replace(end, "/", "-", -1)
start = strings.Replace(start, " ", " ", -1)
end = strings.Replace(end, " ", " ", -1)
start = start[0:5] + "0" + start[5:]
end = end[0:5] + "0" + end[5:]
if hour != "33" {
ss := strings.Split(start, " ")
ss1 := strings.Split(ss[1], ":")
start = ss[0] + " " + hour + ":" + ss1[1] + ":" + ss1[2]
es := strings.Split(end, " ")
es1 := strings.Split(es[1], ":")
end = es[0] + " " + hour + ":" + es1[1] + ":" + es1[2]
}
return dao.FindVideoListByTime(auth_id, start, end)
}
}
@ -50,6 +67,44 @@ func DeleteVideo(id, user int) int {
return dao.DeleteVideoByID(id, user)
}
func QuashVideo(user int, data map[string]interface{}) (int, string) {
var res int
var msg string
defer func() {
if r := recover(); r != nil {
fmt.Println("error:", r)
}
}()
switch data["method"] {
case "delete":
case "delay":
if data["option"] == "all" {
if dao.QuashAllDelay(user, data["delay_day"].(int)) == 0 {
res = proto.RevokeDelayOperationFailed
msg = "quash all video delay error"
} else {
res = proto.SuccessCode
msg = "success"
}
} else if data["option"] == "one" {
if dao.QuashOneDelay(int(data["id"].(float64)), user, int(data["delay_day"].(float64))) == 0 {
res = proto.RevokeDelayOperationFailed
msg = "quash one video error"
} else {
res = proto.SuccessCode
msg = "success"
}
} else {
res = proto.RevokeOperationFailed
msg = "option error,no such delay option"
}
default:
res = proto.RevokeOperationFailed
msg = "method error,no such method"
}
return res, msg
}
func UpdateVideo(videoPath, videoName string, cameraID, videoID, authID, human, isDelete int, createTime, endTime string, fileSize int) bool {
video := GetVideo(videoID, authID)
if video.ID == 0 {

11
test/conf_test.go Normal file
View File

@ -0,0 +1,11 @@
package test
import (
"fmt"
"testing"
"videoplayer/proto"
)
func TestConf(t *testing.T) {
fmt.Println(proto.MYSQL_DSN)
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
"strconv"
"time"
"videoplayer/proto"
)
import (
"context"
@ -16,9 +17,9 @@ func InitRedis() {
ctx := context.Background()
// 连接redis
redisClient = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379", // Redis 服务器地址
Password: "lj502138", // 如果 Redis 设置了密码
DB: 2, // 使用的数据库编号
Addr: proto.REDIS_ADDR, // Redis 服务器地址
Password: proto.REDIS_PASSWORD, // 如果 Redis 设置了密码
DB: proto.REIDS_DB, // 使用的数据库编号
})
// 验证 Redis 客户端是否可以正常工作
@ -148,29 +149,32 @@ func GetRedis(key string) string {
ctx := context.Background()
val, err := redisClient.Get(ctx, key).Result() // 从 Redis 读取键值, 如果键不存在则返回空字符串, 如果出现错误则返回错误
if err != nil {
fmt.Println("Error getting key: %v", err)
fmt.Println(key, " Error getting key: %v", err)
return ""
}
return val
}
// pop redis list from left
func popRedisList(key string) string {
// pop redis list from right,as stack
func PopRedisList(key string) string {
ctx := context.Background()
val, err := redisClient.LPop(ctx, key).Result() // 从 Redis 读取键值, 如果键不存在则返回空字符串, 如果出现错误则返回错误
val, err := redisClient.RPop(ctx, key).Result() // 从 Redis 读取键值, 如果键不存在则返回空字符串, 如果出现错误则返回错误
if err != nil {
fmt.Println("Error reading from Redis: %v", err)
fmt.Println(key, " Error reading from Redis: %v", err)
return ""
}
return val
}
// push redis list from right
func pushRedisList(key string, value string) {
func PushRedisList(key string, value string) bool {
ctx := context.Background()
err := redisClient.RPush(ctx, key, value).Err()
if err != nil {
fmt.Println("Error setting key: %v", err)
return false
}
return true
}
// delete redis key