初始化项目文件

This commit is contained in:
2025-07-11 16:54:11 +08:00
parent 6bffd582a0
commit 39fedaac16
213 changed files with 16944 additions and 0 deletions

View File

@ -0,0 +1,313 @@
package api
import (
"errors"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"strconv"
"strings"
)
// 初始化新棋盘
var cols = 15
func getRooms(ctx iris.Context) {
db := database.GetInstance().GetMysqlDb()
var rooms []typeRoomStatus
if err := db.Model(&model.BackgammonRoom{}).Distinct("room_id").Order("room_id").Scan(&rooms).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for k, v := range rooms {
roomStatus, err := getRoomStatus(v.RoomId)
if utils.ErrHandle(ctx, err) {
return
}
rooms[k].Player = roomStatus.Player
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", rooms))
if utils.ErrHandle(ctx, err) {
return
}
}
// 删除房间
func delRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id, err := strconv.Atoi(ctx.Params().Get("id"))
if utils.ErrHandle(ctx, err) {
return
}
roomStatus, err := getRoomStatus(id)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if roomStatus.Player == username.Username {
if err1 := db.Where("room_id = ?", id).Delete(&model.BackgammonRoom{}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else if strings.Split(roomStatus.Player, ",")[0] == username.Username {
if err1 := db.Create(&model.BackgammonRoom{
RoomId: roomStatus.RoomId,
Player: strings.Split(roomStatus.Player, ",")[1],
Winner: "",
Current: strings.Split(roomStatus.Player, ",")[1],
PawnStatus: initPawns(),
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else if strings.Split(roomStatus.Player, ",")[1] == username.Username {
if err1 := db.Create(&model.BackgammonRoom{
RoomId: roomStatus.RoomId,
Player: strings.Split(roomStatus.Player, ",")[0],
Winner: "",
Current: strings.Split(roomStatus.Player, ",")[0],
PawnStatus: initPawns(),
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func initPawns() string {
var newPawns string
for i := 0; i < cols; i++ {
tmp := "0" + strings.Repeat(",0", cols-1)
if i == 0 {
newPawns = tmp
continue
}
newPawns += ";" + tmp
}
return newPawns
}
// 新建房间
func addRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var currentStatus model.BackgammonRoom
db := database.GetInstance().GetMysqlDb()
if err := db.Order("room_id desc").First(&currentStatus).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
newPawns := initPawns()
if err := db.Create(&model.BackgammonRoom{
RoomId: currentStatus.RoomId + 1,
Player: username.Username,
Current: username.Username,
Winner: "",
PawnStatus: newPawns,
}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", currentStatus.RoomId+1))
if utils.ErrHandle(ctx, err) {
return
}
}
func joinRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id, err := strconv.Atoi(ctx.Params().Get("id"))
if utils.ErrHandle(ctx, err) {
return
}
roomStatus, err := getRoomStatus(id)
if utils.ErrHandle(ctx, err) {
return
}
if utils.CheckListItem(strings.Split(roomStatus.Player, ","), username.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("无法重复加入房间"))
return
}
if !utils.CheckListItem(strings.Split(roomStatus.Player, ","), username.Username) && len(strings.Split(roomStatus.Player, ",")) > 2 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间人数已满"))
return
}
roomStatus.Player = roomStatus.Player + "," + username.Username
db := database.GetInstance().GetMysqlDb()
if err1 := db.Model(&model.BackgammonRoom{}).Where("id = ?", roomStatus.ID).Updates(&roomStatus).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func getRoomStatus(roomId int) (model.BackgammonRoom, error) {
var status model.BackgammonRoom
db := database.GetInstance().GetMysqlDb()
if err := db.Where("room_id = ?", roomId).Order("id desc").First(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(status) {
return model.BackgammonRoom{}, errors.New("房间号不存在")
}
return status, nil
}
// 获取房间棋盘状态
func getStatus(ctx iris.Context) {
id, err := strconv.Atoi(ctx.Params().Get("id"))
if utils.ErrHandle(ctx, err) {
return
}
roomStatus, err := getRoomStatus(id)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", roomStatus))
if utils.ErrHandle(ctx, err) {
return
}
}
// 新增棋子
func addPawn(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id, err := strconv.Atoi(ctx.Params().Get("id"))
if utils.ErrHandle(ctx, err) {
return
}
roomStatus, err := getRoomStatus(id)
if utils.ErrHandle(ctx, err) {
return
}
var tmpT string
if roomStatus.Winner != "" {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("对局已结束"))
return
}
if len(strings.Split(roomStatus.Player, ",")) != 2 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("当前房间,玩家人数不足"))
return
}
if roomStatus.Current != username.Username {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("现在不是你的回合"))
return
}
if strings.Split(roomStatus.Player, ",")[0] == username.Username {
tmpT = "1"
} else if strings.Split(roomStatus.Player, ",")[1] == username.Username {
tmpT = "-1"
} else {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("非玩家,无法进行游戏"))
return
}
place := strings.Split(ctx.URLParam("place"), ",")
var newPawn []int
for _, i := range place {
tmp, _ := strconv.Atoi(i)
newPawn = append(newPawn, tmp)
}
var pawnStatus [][]string
for _, i := range strings.Split(roomStatus.PawnStatus, ";") {
var tmp []string
for _, j := range strings.Split(i, ",") {
tmp = append(tmp, j)
}
pawnStatus = append(pawnStatus, tmp)
}
if pawnStatus[newPawn[0]][newPawn[1]] != "0" {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("该位置已有棋子"))
return
}
winner := getWinner(pawnStatus, tmpT, [2]int{newPawn[0], newPawn[1]})
if winner {
roomStatus.Winner = username.Username
}
pawnStatus[newPawn[0]][newPawn[1]] = tmpT
var tmp []string
for _, i := range pawnStatus {
tmp = append(tmp, strings.Join(i, ","))
}
roomStatus.PawnStatus = strings.Join(tmp, ";")
roomStatus.Current = strings.Replace(strings.Replace(roomStatus.Player, username.Username, "", 1), ",", "", 1)
db := database.GetInstance().GetMysqlDb()
if err1 := db.Create(&model.BackgammonRoom{
RoomId: roomStatus.RoomId,
Player: roomStatus.Player,
Winner: roomStatus.Winner,
Current: roomStatus.Current,
PawnStatus: roomStatus.PawnStatus,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", roomStatus))
if utils.ErrHandle(ctx, err) {
return
}
}
// 判断当前是否存在winner
func getWinner(pawns [][]string, t string, pawn [2]int) bool {
pawnAround := [8][2]int{{pawn[0] - 1, pawn[1] - 1}, {pawn[0], pawn[1] - 1}, {pawn[0] + 1, pawn[1] - 1}, {pawn[0] - 1, pawn[1]},
{pawn[0] + 1, pawn[1]}, {pawn[0] - 1, pawn[1] + 1}, {pawn[0], pawn[1] + 1}, {pawn[0] + 1, pawn[1] + 1}}
around := [8]int{0, 0, 0, 0, 0, 0, 0, 0}
for i, p := range pawnAround {
if p[0] >= 0 && p[1] >= 0 && p[0] < cols && p[1] < cols && pawns[p[0]][p[1]] == t {
current := [2]int{p[0], p[1]}
for j := 0; j < 3; j++ {
switch i {
case 0:
current[0]--
current[1]--
case 1:
current[1]--
case 2:
current[0]++
current[1]--
case 3:
current[0]--
case 4:
current[0]++
case 5:
current[0]--
current[1]++
case 6:
current[1]++
case 7:
current[0]++
current[1]++
}
//fmt.Println(current)
if current[0] < 0 || current[0] > cols-1 || current[1] < 0 || current[1] > cols-1 || pawns[current[0]][current[1]] != t {
around[i] = j + 1
break
}
around[i] = j + 2
}
}
}
if around[0]+around[7] >= 4 || around[1]+around[6] >= 4 || around[2]+around[5] >= 4 || around[3]+around[4] >= 4 {
return true
}
return false
}

View File

@ -0,0 +1,15 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Backgammon(party iris.Party) {
party.Get("/", getRooms)
party.Post("/", jwtSet.Jwt.Serve, addRoom)
party.Get("/{id:int}", getStatus)
party.Put("/{id:int}", jwtSet.Jwt.Serve, joinRoom)
party.Delete("/{id:int}", jwtSet.Jwt.Serve, delRoom)
party.Post("/{id:int}", jwtSet.Jwt.Serve, addPawn)
}

View File

@ -0,0 +1,614 @@
package api
import (
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"io"
"main/database"
"main/model"
"main/utils"
"math/rand"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
var initChessPawns = model.ChessStatus{
Current: "",
IsEnd: false,
Status: "0,1,2,3,4,5,6,7,8;-1,-1,-1,-1,-1,-1,-1,-1,-1;-1,9,-1,-1,-1,-1,-1,10,-1;11,-1,12,-1,13,-1,14,-1,15;-1,-1,-1,-1,-1,-1,-1,-1,-1;-1,-1,-1,-1,-1,-1,-1,-1,-1;31,-1,30,-1,29,-1,28,-1,27;-1,26,-1,-1,-1,-1,-1,25,-1;-1,-1,-1,-1,-1,-1,-1,-1,-1;24,23,22,21,20,19,18,17,16",
Winner: "",
ChessId: "",
}
func addAiChessPlayer(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if username.Username == "" {
return
}
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if status.Players != username.Username {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房主方可添加机器人"))
return
}
status.Players += ",ai--" + id
status.Status = initChessPawns.Status
status.Current = username.Username
status.IsEnd = initChessPawns.IsEnd
status.Winner = initChessPawns.Winner
status.ChessId = initChessPawns.ChessId
db := database.GetInstance().GetMysqlDb()
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
func updateChessAiStep(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if username.Username == "" {
return
}
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if players := strings.Split(status.Players, ","); players[0] != username.Username || players[1] != "ai--"+id {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间人员配置错误"))
return
}
if status.Current != "ai--"+id {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("当前非ai回合"))
return
}
stepList := strings.Split(getAiChessStep(chessPawnStatusToFen(chessPawnStrToSlice(status.Status)), "queryall", "b"), "|")
var tmpNum int
if strings.Index(stepList[0], "score:??") != -1 {
rand.NewSource(time.Now().Unix())
tmpNum = rand.Intn(len(stepList))
} else {
tmpNum = 0
}
stepTmp := strings.Split(stepList[tmpNum], ",")[0]
//fmt.Println(stepTmp, chessPawnStatusToFen(chessPawnStrToSlice(status.Status)))
if strings.Index(stepTmp, "move:") == -1 {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("机器人无合适步骤,对局结束"))
return
}
step := strings.Split(stepTmp, "move:")[1]
tmp := "abcdefghi0123456789"
statusList := chessPawnStrToSlice(status.Status)
start0 := 8 - strings.IndexByte(tmp, step[0])
end0 := 8 - strings.IndexByte(tmp, step[2])
start1 := strings.IndexByte(tmp, step[1]) - 9
end1 := strings.IndexByte(tmp, step[3]) - 9
statusList[end1][end0] = statusList[start1][start0]
statusList[start1][start0] = "-1"
status.Status = chessPawnSliceToStr(statusList)
status.ChessId = statusList[end1][end0]
status.Current = username.Username
db := database.GetInstance().GetMysqlDb()
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(200, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
func testChess(ctx iris.Context) {
var res [][]string
db := database.GetInstance().GetMysqlDb()
var status []model.ChessStatus
if err := db.Find(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for _, s := range status {
stepTmp := getAiChessStep(chessPawnStatusToFen(chessPawnStrToSlice(s.Status)), "queryall", "b")
//fmt.Println(s.Status, chessPawnStatusToFen(chessPawnStrToSlice(s.Status)))
step := strings.Split(stepTmp, "move:")[1]
tmp := "abcdefghi0123456789"
//statusList := chessPawnStrToSlice(status.Status)
start0 := strings.IndexByte(tmp, step[0])
end0 := strings.IndexByte(tmp, step[2])
start1 := strings.IndexByte(tmp, step[1]) - 9
end1 := strings.IndexByte(tmp, step[3]) - 9
statusTmp := chessPawnStrToSlice(s.Status)
start := statusTmp[start1][start0]
end := statusTmp[end1][end0]
res = append(res, []string{start, end})
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}
func resetRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if username.Username == "" {
return
}
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if utils.DataIsNil(status) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间号不存在"))
return
}
if strings.Split(status.Players, ",")[0] != username.Username {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房主方可重置房间"))
return
}
db := database.GetInstance().GetMysqlDb()
status.Status = initChessPawns.Status
status.Current = username.Username
status.IsEnd = initChessPawns.IsEnd
status.Winner = initChessPawns.Winner
status.ChessId = initChessPawns.ChessId
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
// 新建房间
func newChessRoom(ctx iris.Context) {
creator := utils.GetLoginUser(ctx)
if creator.Username == "" {
return
}
db := database.GetInstance().GetMysqlDb()
status := model.ChessStatus{
Players: creator.Username,
Current: creator.Username,
IsEnd: initChessPawns.IsEnd,
Status: initChessPawns.Status,
Winner: initChessPawns.Winner,
ChessId: initChessPawns.ChessId,
}
if err := db.Create(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status.ID))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取所有房间
func getChessRooms(ctx iris.Context) {
db := database.GetInstance().GetMysqlDb()
var rooms []model.ChessStatus
if err := db.Find(&rooms).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", rooms))
if utils.ErrHandle(ctx, err) {
return
}
}
// 加入房间
func joinChessRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if utils.DataIsNil(status) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间号不存在"))
return
}
if len(strings.Split(status.Players, ",")) >= 2 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间人数已满"))
return
}
if utils.CheckListItem(strings.Split(status.Players, ","), username.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("不可重复加入房间"))
return
}
status.Players += fmt.Sprintf(",%s", username.Username)
db := database.GetInstance().GetMysqlDb()
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if err := db.Create(&model.ChessStatusLog{
RoomId: status.ID,
Players: status.Players,
Current: status.Current,
IsEnd: status.IsEnd,
Status: status.Status,
Winner: status.Winner,
ChessId: status.ChessId,
Time: status.CreatedAt,
}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
// 离开房间
func leaveChessRoom(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if utils.DataIsNil(status) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间号不存在"))
return
}
if !utils.CheckListItem(strings.Split(status.Players, ","), username.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未加入该房间"))
return
}
for _, v := range strings.Split(status.Players, ",") {
if v != username.Username {
status.Players = v
}
}
db := database.GetInstance().GetMysqlDb()
if status.Players == username.Username || status.Players == "ai--"+id {
if err := db.Delete(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
} else {
status.Current = status.Players
status.ChessId = initChessPawns.ChessId
status.IsEnd = initChessPawns.IsEnd
status.Winner = initChessPawns.Winner
status.Status = initChessPawns.Status
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取房间状态接口
func getChessRoom(ctx iris.Context) {
id := ctx.Params().Get("id")
status := getChessRoomStatus(id)
if utils.DataIsNil(status) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间号不存在"))
return
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
// 更新棋盘状态
func updateChessStatus(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
id := ctx.Params().Get("id")
pawn := ctx.URLParam("pawn")
des := ctx.URLParam("des")
status := getChessRoomStatus(id)
if utils.DataIsNil(status) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间号不存在"))
return
}
if len(strings.Split(status.Players, ",")) < 2 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("房间人数不足"))
return
}
pawnNum, _ := strconv.Atoi(pawn)
if (strings.Split(status.Players, ",")[0] == username.Username && pawnNum > 15) || (strings.Split(status.Players, ",")[1] == username.Username && pawnNum < 16) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只能移动自己的棋子"))
return
}
if status.Current != username.Username {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("当前不是你的回合"))
return
}
if checkChessStep(pawn, status.Status, des) {
tmpStatus := chessPawnStrToSlice(status.Status)
locTmp := getPawnLoc(status.Status, pawn)
toTmp0, _ := strconv.Atoi(strings.Split(des, ",")[0])
toTmp1, _ := strconv.Atoi(strings.Split(des, ",")[1])
tmpStatus[locTmp[0]][locTmp[1]] = "-1"
tmpStatus[toTmp0][toTmp1] = pawn
status.Status = chessPawnSliceToStr(tmpStatus)
status.ChessId = pawn
for _, v := range strings.Split(status.Players, ",") {
if v != username.Username {
status.Current = v
}
}
if checkWinner(status.Status) == 1 {
status.Winner = username.Username
status.IsEnd = true
status.Current = ""
}
} else {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("当前无法移到该位置"))
return
}
db := database.GetInstance().GetMysqlDb()
if checkWinner(status.Status) == 2 {
for _, v := range strings.Split(status.Players, ",") {
if v != username.Username {
status.Winner = v
status.IsEnd = true
}
}
}
if err := db.Save(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if err := db.Create(&model.ChessStatusLog{
RoomId: status.ID,
Current: status.Current,
Players: status.Players,
IsEnd: status.IsEnd,
Status: status.Status,
Winner: status.Winner,
ChessId: status.ChessId,
Time: status.CreatedAt,
}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", status))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取房间状态方法
func getChessRoomStatus(id string) model.ChessStatus {
db := database.GetInstance().GetMysqlDb()
var status model.ChessStatus
if err := db.Where("id = ?", id).First(&status).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
return status
}
func checkWinner(status string) int {
if utils.DataIsNil(getPawnLoc(status, "4")) || utils.DataIsNil(getPawnLoc(status, "20")) {
return 1
}
if checkNullPath(chessPawnStrToSlice(status), getPawnLoc(status, "4"), getPawnLoc(status, "20")) {
return 2
}
return 0
}
// 获取棋子位置
func getPawnLoc(statusStr string, pawn string) [2]int {
var res [2]int
status := chessPawnStrToSlice(statusStr)
for row, i := range status {
for col, j := range i {
if j == pawn {
res[0] = row
res[1] = col
}
}
}
return res
}
// 判断棋子是否可移动
func checkChessStep(pawn string, statusStr string, to string) bool {
locList := getPawnLoc(statusStr, pawn)
status := chessPawnStrToSlice(statusStr)
locTmp0 := locList[0]
locTmp1 := locList[1]
toTmp := strings.Split(to, ",")
toTmp0, _ := strconv.Atoi(toTmp[0])
toTmp1, _ := strconv.Atoi(toTmp[1])
//目标位置超出棋盘
if toTmp0 < 0 || toTmp1 < 0 || toTmp0 > 10 || toTmp1 > 8 {
return false
}
pawnNum, _ := strconv.Atoi(pawn)
toPawnNum, _ := strconv.Atoi(status[toTmp0][toTmp1])
if (pawnNum < 16 && toPawnNum < 16 && toPawnNum >= 0) || (pawnNum > 15 && toPawnNum > 15) {
return false
}
switch pawn {
case "0", "8", "16", "24": //车:同行列,路径为空
if (toTmp0 == locTmp0 && toTmp1 != locTmp1) || (toTmp1 == locTmp1 && toTmp0 != locTmp0) && checkNullPath(status, [2]int{locTmp0, locTmp1}, [2]int{toTmp0, toTmp1}) {
return true
}
case "1", "7", "17", "23": //马:日字,前后左右无子
if (utils.IntAbs(toTmp0-locTmp0) == 1 && utils.IntAbs(toTmp1-locTmp1) == 2 && status[locTmp0][(locTmp1+toTmp1)/2] == "-1") || (utils.IntAbs(toTmp0-locTmp0) == 2 && utils.IntAbs(toTmp1-locTmp1) == 1 && status[(locTmp0+toTmp0)/2][locTmp1] == "-1") {
return true
}
case "2", "6", "18", "22": //象:田字,不过河,中间格子为空
if utils.IntAbs(toTmp0-locTmp0) == 2 && utils.IntAbs(toTmp1-locTmp1) == 2 && ((locTmp0 < 5 && toTmp0 < 5) || (locTmp0 > 4 && toTmp0 > 4)) && status[(locTmp0+toTmp0)/2][(locTmp1+toTmp1)/2] == "-1" {
return true
}
case "3", "5", "19", "21": //士:斜着走,不超出方格
if toTmp1 < 3 || toTmp1 > 5 || (locTmp0 < 5 && toTmp0 > 2) || (locTmp0 > 4 && toTmp0 < 7) {
return false
}
if utils.IntAbs(toTmp0-locTmp0) == 1 && utils.IntAbs(toTmp1-locTmp1) == 1 {
return true
}
case "4", "20": //将:走一步,不超出方格
if toTmp1 < 3 || toTmp1 > 5 || (locTmp0 < 5 && toTmp0 > 2) || (locTmp0 > 4 && toTmp0 < 7) {
return false
}
if utils.IntAbs(toTmp0-locTmp0)+utils.IntAbs(toTmp1-locTmp1) == 1 {
return true
}
case "9", "10", "25", "26": //炮:同行列,路径不为空,目标位置不为空
if ((toTmp0 == locTmp0 && toTmp1 != locTmp1) || (toTmp1 == locTmp1 && toTmp0 != locTmp0)) && ((!checkNullPath(status, [2]int{locTmp0, locTmp1}, [2]int{toTmp0, toTmp1}) && status[toTmp0][toTmp1] != "-1") || (checkNullPath(status, [2]int{locTmp0, locTmp1}, [2]int{toTmp0, toTmp1}) && status[toTmp0][toTmp1] == "-1")) {
return true
}
case "11", "12", "13", "14", "15": //兵:走一步,过河后可横移
if (toTmp0 < 5 && toTmp1 == locTmp1 && toTmp0-locTmp0 == 1) || (toTmp0 > 4 && utils.IntAbs(toTmp0-locTmp0+toTmp1-locTmp1) == 1) {
return true
}
case "27", "28", "29", "30", "31": //兵:走一步,过河后可横移
if (toTmp0 > 4 && toTmp1 == locTmp1 && toTmp0-locTmp0 == -1) || (toTmp0 < 5 && utils.IntAbs(toTmp0-locTmp0+toTmp1-locTmp1) == 1) {
return true
}
default:
return false
}
return false
}
// 棋盘状态字符串转数组
func chessPawnStrToSlice(status string) [][]string {
var res [][]string
for _, i := range strings.Split(status, ";") {
var colList []string
for _, j := range strings.Split(i, ",") {
colList = append(colList, j)
}
res = append(res, colList)
}
return res
}
// 棋盘状态数组转字符串
func chessPawnSliceToStr(status [][]string) string {
var resList []string
for _, i := range status {
resList = append(resList, strings.Join(i, ","))
}
res := strings.Join(resList, ";")
return res
}
func chessPawnStatusToFen(status [][]string) string {
var res []string
for _, i := range status {
resTmp := ""
count := 0
for col, j := range i {
if j == "-1" && col == len(i)-1 {
resTmp += strconv.Itoa(count + 1)
} else if j == "-1" {
count += 1
} else {
if count != 0 {
resTmp += strconv.Itoa(count)
count = 0
}
switch j {
case "0", "8":
resTmp += "R"
case "1", "7":
resTmp += "N"
case "2", "6":
resTmp += "B"
case "3", "5":
resTmp += "A"
case "4":
resTmp += "K"
case "9", "10":
resTmp += "C"
case "11", "12", "13", "14", "15":
resTmp += "P"
case "16", "24":
resTmp += "r"
case "17", "23":
resTmp += "n"
case "18", "22":
resTmp += "b"
case "19", "21":
resTmp += "a"
case "20":
resTmp += "k"
case "25", "26":
resTmp += "c"
case "27", "28", "29", "30", "31":
resTmp += "p"
}
}
}
res = append(res, resTmp)
}
return utils.Reverse(strings.Join(res, "/"))
}
// 判断路径是否为空
func checkNullPath(status [][]string, start [2]int, end [2]int) bool {
if start[0] == end[0] {
path := []int{start[1], end[1]}
sort.Ints(path)
for i := path[0] + 1; i < path[1]; i++ {
if status[start[0]][i] != "-1" {
return false
}
}
return true
}
if start[1] == end[1] {
path := []int{start[0], end[0]}
sort.Ints(path)
for i := path[0] + 1; i < path[1]; i++ {
if status[i][start[1]] != "-1" {
return false
}
}
return true
}
return false
}
func getAiChessStep(fenStatus string, t string, p string) string {
urlPath, err := url.Parse("http://www.chessdb.cn/chessdb.php")
params := url.Values{}
params.Set("action", t)
params.Set("board", fmt.Sprintf("%s %s", fenStatus, p))
params.Set("showall", "1")
urlPath.RawQuery = params.Encode()
res, err := http.Get(urlPath.String())
if err != nil {
return err.Error()
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(res.Body)
body, _ := io.ReadAll(res.Body)
return string(body)
}

View File

@ -0,0 +1,19 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Chess(party iris.Party) {
party.Post("/", jwtSet.Jwt.Serve, newChessRoom)
party.Get("/", getChessRooms)
party.Get("/{id:int}", getChessRoom)
party.Post("/{id:int}", jwtSet.Jwt.Serve, joinChessRoom)
party.Delete("/{id:int}", jwtSet.Jwt.Serve, leaveChessRoom)
party.Put("/{id:int}", jwtSet.Jwt.Serve, updateChessStatus)
party.Get("/{id:int}/reset", jwtSet.Jwt.Serve, resetRoom)
party.Post("/{id:int}/ai", jwtSet.Jwt.Serve, addAiChessPlayer)
party.Put("/{id:int}/ai", jwtSet.Jwt.Serve, updateChessAiStep)
party.Get("/test", testChess)
}

View File

@ -0,0 +1,319 @@
package api
import (
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"mime/multipart"
"os"
"path"
"path/filepath"
"strings"
"time"
)
func getRootFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
userPath := fmt.Sprintf("./upload/%s", username.Username)
if !utils.FileIsExist(userPath) {
err := os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
var files filesRes
fileList, err := os.ReadDir(userPath)
if utils.ErrHandle(ctx, err) {
return
}
for _, file := range fileList {
if file.IsDir() {
files.Dirs = append(files.Dirs, file.Name())
} else {
var item fileItem
item.Name = file.Name()
f, err := os.Stat(path.Join(userPath, file.Name()))
if utils.ErrHandle(ctx, err) {
return
}
item.Size = f.Size()
item.Type = utils.GetFileType(f.Name())
files.Files = append(files.Files, item)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取指定目录下文件
func getFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New(userPath + ":目录不存在"))
return
}
var files filesRes
fileList, err := os.ReadDir(userPath)
if utils.ErrHandle(ctx, err) {
return
}
for _, file := range fileList {
if file.IsDir() {
files.Dirs = append(files.Dirs, file.Name())
} else {
var item fileItem
item.Name = file.Name()
f, err := os.Stat(path.Join(userPath, file.Name()))
if utils.ErrHandle(ctx, err) {
return
}
item.Size = f.Size()
item.Type = utils.GetFileType(f.Name())
files.Files = append(files.Files, item)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
if utils.ErrHandle(ctx, err) {
return
}
}
// 删除文件或目录
func deleteFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("目录不存在"))
return
}
if info, _ := os.Stat(userPath); info.IsDir() {
err := os.RemoveAll(userPath)
if utils.ErrHandle(ctx, err) {
return
}
} else {
err := os.Remove(userPath)
if utils.ErrHandle(ctx, err) {
return
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 上传头像
func uploadAvatar(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
file, info, err := ctx.FormFile("file")
if utils.ErrHandle(ctx, err) {
return
}
defer func(file multipart.File) {
err = file.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(file)
userPath := fmt.Sprintf("./static/%s", username.Username)
if !utils.FileIsExist(userPath) {
err = os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
fileType := strings.Split(info.Filename, ".")[len(strings.Split(info.Filename, "."))-1]
avatarName := fmt.Sprintf("./static/%s/avatar-%s.%s", username.Username, time.Now().Format("2006-01-02"), fileType)
_, err = ctx.SaveFormFile(info, avatarName)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", avatarName[1:]))
if utils.ErrHandle(ctx, err) {
return
}
}
func uploadDir(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("目录已存在"))
return
}
err := os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 上传文件
func uploadFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
file, info, err := ctx.FormFile("file")
if utils.ErrHandle(ctx, err) {
return
}
defer func(file multipart.File) {
err = file.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(file)
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
err = os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
_, err = ctx.SaveFormFile(info, fmt.Sprintf("./upload/%s/%s/%s", username.Username, filePath, info.Filename))
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 文件下载转到nginx-upload目录
func downloadFile(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", userToken.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("文件不存在"))
return
}
if info, _ := os.Stat(userPath); info.IsDir() {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只可下载文件"))
return
}
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", userToken.Username, filePath))
ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
ctx.Recorder().Header().Add("Content-Disposition", "attachment")
ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
return
}
func getDownloadFileType(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
var res videoM3u8
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
username := userToken.Username
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
currentPath, _ := filepath.Split(filePath)
filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
res.Video = utils.GetFileType(userPath) == "video"
res.M3u8 = utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if err != nil {
return
}
return
}
func downloadVideo(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
username := userToken.Username
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
currentPath, _ := filepath.Split(filePath)
filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
//fmt.Println(filePath, currentPath, filename)
if path.Ext(userPath) != ".ts" && !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("文件不存在"))
return
}
if info, err := os.Stat(userPath); err == nil && info.IsDir() {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只可下载文件"))
return
}
if utils.GetFileType(userPath) == "video" && utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename)) {
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
} else if utils.GetFileType(userPath) == "video" {
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", username, filePath))
} else {
tsPath := fmt.Sprintf("./upload-video/%s/%s%s/%s.ts", username, currentPath, filename[:len(filename)-6], filename)
ctx.Recorder().Header().Add("X-Accel-Redirect", tsPath[1:])
}
ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
ctx.Recorder().Header().Add("Content-Disposition", "attachment")
ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
return
}

View File

@ -0,0 +1,18 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func File(party iris.Party) {
party.Get("/upload", jwtSet.Jwt.Serve, getRootFile)
party.Get("/upload/{path:path}", jwtSet.Jwt.Serve, getFile)
party.Post("/upload/{path:path}", jwtSet.Jwt.Serve, uploadDir)
party.Post("/upload-file/{path:path}", jwtSet.Jwt.Serve, uploadFile)
party.Delete("/upload/{path:path}", jwtSet.Jwt.Serve, deleteFile)
party.Post("/static/avatar", jwtSet.Jwt.Serve, uploadAvatar)
party.Get("/download/{path:path}", downloadFile)
party.Get("/download-video-check/{path:path}", getDownloadFileType)
party.Get("/download-video/{path:path}", downloadVideo)
}

View File

@ -0,0 +1,13 @@
package api
import (
"github.com/kataras/iris/v12"
"main/utils"
)
func Apis(ctx iris.Context) {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "allApis"))
if err != nil {
return
}
}

View File

@ -0,0 +1,55 @@
package api
import (
"fmt"
"github.com/kataras/iris/v12"
"main/utils"
"regexp"
)
func getMenu(ctx iris.Context) {
var resTmp []subMenu
var res []resMenu
user := utils.GetLoginUser(ctx)
if utils.DataIsNil(user) {
return
}
if len(utils.MenuList) == 0 {
utils.UpdateMenuList()
}
resTmp = append(resTmp, subMenu{MenuId: "000", Name: "首页", Icon: "bi-emoji-wink", Path: "/", RouteOnly: false})
for _, menu := range utils.MenuList {
patternWhiteList := fmt.Sprintf("^%s,|,%s,|,%s$|%s", user.Username, user.Username, user.Username, user.Username)
regWhiteList := regexp.MustCompile(patternWhiteList)
patternUserType := fmt.Sprintf("^%s,|,%s,|,%s$|%s", user.Type, user.Type, user.Type, user.Type)
regUserType := regexp.MustCompile(patternUserType)
if match := regWhiteList.MatchString(menu.WhiteList); match || regUserType.MatchString(menu.UserType) {
resTmp = append(resTmp, subMenu{
MenuId: menu.MenuId,
Name: menu.Name,
Icon: menu.Icon,
Path: menu.Path,
RouteOnly: menu.RouteOnly,
})
}
}
for _, menu := range resTmp {
if menu.RouteOnly {
res = append(res, resMenu{MenuId: menu.MenuId, Name: menu.Name, Icon: menu.Icon, Path: menu.Path, RouteOnly: menu.RouteOnly})
continue
}
if len(menu.MenuId) == 3 {
var tmp []subMenu
for _, sub := range resTmp {
if len(sub.MenuId) == 5 && sub.MenuId[0:3] == menu.MenuId && !sub.RouteOnly {
tmp = append(tmp, sub)
}
}
res = append(res, resMenu{MenuId: menu.MenuId, Name: menu.Name, Icon: menu.Icon, Path: menu.Path, Detail: tmp})
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}

View File

@ -0,0 +1,10 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Menus(party iris.Party) {
party.Get("/", jwtSet.Jwt.Serve, getMenu)
}

View File

@ -0,0 +1,210 @@
package api
import (
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"mime/multipart"
"os"
"time"
)
func getNotesList(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var notes []model.UserNotes
var res []noteParam
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ?", username.Username).Select("id", "content").Find(&notes).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for _, item := range notes {
if len(item.Content) > 100 {
item.Content = item.Content[:30] + "\n......"
}
res = append(res, noteParam{
ID: item.ID,
Content: item.Content,
})
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}
func addNote(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var note noteParam
err := ctx.ReadJSON(&note)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Create(&model.UserNotes{
Username: username.Username,
Content: note.Content,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
var newNote model.UserNotes
if err1 := db.Where("username = ?", username.Username).Order("id desc").First(&newNote).Error; err1 != nil {
logrus.Errorln("sql执行失败", err)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", newNote.ID))
if utils.ErrHandle(ctx, err) {
return
}
}
func getNote(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
db := database.GetInstance().GetMysqlDb()
var note model.UserNotes
if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(note) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("not found"))
return
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", note))
if utils.ErrHandle(ctx, err) {
return
}
}
func deleteNote(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var note model.UserNotes
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(note) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("not found"))
return
}
if err := db.Delete(&note).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func updateNote(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var note model.UserNotes
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(note) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("not found"))
return
}
var newNote noteParam
err := ctx.ReadJSON(&newNote)
if utils.ErrHandle(ctx, err) {
return
}
if err1 := db.Model(&note).Updates(model.UserNotes{
Content: newNote.Content,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func uploadNoteFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
noteId := ctx.Params().Get("id")
userPath := fmt.Sprintf("./upload-note/%s/%s", username.Username, noteId)
if !utils.FileIsExist(userPath) {
err := os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
file, info, err := ctx.FormFile("file")
if utils.ErrHandle(ctx, err) {
return
}
defer func(file multipart.File) {
err = file.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(file)
filePath := fmt.Sprintf("%s/%s", userPath, info.Filename)
_, err = ctx.SaveFormFile(info, filePath)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", fmt.Sprintf("/api/notes/%s/file/%s", noteId, info.Filename)))
if utils.ErrHandle(ctx, err) {
return
}
}
func getNoteFile(ctx iris.Context) {
noteId := ctx.Params().Get("id")
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
filename := ctx.Params().Get("filename")
userPath := fmt.Sprintf("./upload-note/%s/%s/%s", userToken.Username, noteId, filename)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("文件不存在"))
return
}
if info, _ := os.Stat(userPath); info.IsDir() {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只可下载文件"))
return
}
ctx.Recorder().Header().Add("X-Accel-Redirect", userPath[1:])
ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
ctx.Recorder().Header().Add("Content-Disposition", "attachment")
ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
return
}

View File

@ -0,0 +1,16 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Notes(party iris.Party) {
party.Get("/", jwtSet.Jwt.Serve, getNotesList)
party.Post("/", jwtSet.Jwt.Serve, addNote)
party.Get("/{id:int}", jwtSet.Jwt.Serve, getNote)
party.Put("/{id:int}", jwtSet.Jwt.Serve, updateNote)
party.Delete("/{id:int}", jwtSet.Jwt.Serve, deleteNote)
party.Post("/{id:int}/file", jwtSet.Jwt.Serve, uploadNoteFile)
party.Get("/{id:int}/file/{filename:string}", getNoteFile)
}

View File

@ -0,0 +1,88 @@
package api
import (
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/utils"
"strconv"
"strings"
"time"
)
// 获取节假日信息
func getHolidays(ctx iris.Context) {
yearParam := ctx.URLParam("year")
if yearParam == "" {
yearParam = strconv.Itoa(time.Now().Year())
}
logrus.Infoln("假期查询年份:", yearParam)
year, err := strconv.Atoi(yearParam)
var res []utils.ResHolidays
if utils.ErrHandle(ctx, err) {
return
}
if utils.ErrHandle(ctx, err) {
return
}
startDate := time.Date(year, 1, 1, 0, 0, 0, 0, time.Local)
for startDate.Year() == year {
isHoliday, name := utils.CheckHoliday(startDate.Format("2006-01-02"))
if startDate.Weekday() == time.Saturday || startDate.Weekday() == time.Sunday {
res = append(res, utils.ResHolidays{
Date: startDate.Format("2006-01-02"),
HolidayNameCn: "周末",
})
} else if isHoliday {
res = append(res, utils.ResHolidays{
Date: startDate.Format("2006-01-02"),
HolidayNameCn: name,
})
}
startDate = startDate.AddDate(0, 0, 1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if err != nil {
return
}
}
// 获取IP归属地
func getIpLocation(ctx iris.Context) {
var ip string
if ctx.URLParam("ip") != "" {
ip = ctx.URLParam("ip")
} else {
ip = utils.GetRequestIp(ctx)
}
ipLocation, err := utils.GetIpLocation(ip)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", ipLocationData{
Ip: ip,
Location: ipLocation,
}))
if err != nil {
return
}
}
// 邮件发送
func sendEmail(ctx iris.Context) {
receiver := strings.Split(ctx.URLParam("receiver"), ";")
subject := ctx.URLParam("subject")
content := ctx.URLParam("content")
err := utils.SendEmail(receiver, subject, content)
if utils.ErrHandle(ctx, err) {
logrus.Errorln(err)
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "发送成功"))
if err != nil {
return
}
}
func getSudokuCheck(ctx iris.Context) {
}

View File

@ -0,0 +1,10 @@
package api
import "github.com/kataras/iris/v12"
func PublicApis(party iris.Party) {
party.Get("/holidays", getHolidays)
party.Get("/send_email", sendEmail)
party.Get("/get_ip_location", getIpLocation)
party.Get("/get_sudoku_check", getSudokuCheck)
}

View File

@ -0,0 +1,170 @@
package api
import (
"errors"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"strings"
)
func getSudokuList(ctx iris.Context) {
var resSudokuList resSudokuListType
var startingSudokuList []sudokuListType
var newSudokuList []model.Sudoku
db := database.GetInstance().GetMysqlDb()
if err := db.Where("id not in (?)", db.Table("sudoku_statuses").Distinct("sudoku_id").Where("username = ? and deleted_at is null", "admin")).Find(&newSudokuList).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for _, v := range newSudokuList {
resSudokuList.New = append(resSudokuList.New, sudokuListType{Sudoku: v.Sudoku, SudokuId: v.ID, Complete: false})
}
queryId := db.Table("sudoku_statuses").Select("max(id)").Where("username = ? and deleted_at is null", "admin").Group("sudoku_id")
if queryId.Error != nil {
logrus.Errorln("sql执行失败", queryId.Error)
}
queryStatus := db.Table("sudoku_statuses").Where("id in (?)", queryId)
if queryStatus.Error != nil {
logrus.Errorln("sql执行失败", queryStatus.Error)
}
if err := db.Model(&model.Sudoku{}).Select("sudokus.sudoku, q.*").Joins("left join (?) q on sudokus.id = q.sudoku_id", queryStatus).Scan(&startingSudokuList).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for _, v := range startingSudokuList {
if v.Complete {
resSudokuList.Complete = append(resSudokuList.Complete, v)
} else {
resSudokuList.Starting = append(resSudokuList.Starting, v)
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", resSudokuList))
if utils.ErrHandle(ctx, err) {
return
}
}
func addSudokuGame(ctx iris.Context) {
var sudokuParam addSudokuParam
var dbCheck model.Sudoku
var sudokuResult [9][9]string
err := ctx.ReadJSON(&sudokuParam)
if utils.ErrHandle(ctx, err) {
return
}
if sudokuParam.Result != "" {
sudokuResult, err = sudokuStringToList(sudokuParam.Result)
if utils.ErrHandle(ctx, err) {
return
}
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Where("sudoku = ?", sudokuParam.Sudoku).First(&dbCheck).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if !utils.DataIsNil(dbCheck) {
utils.ErrHandle(ctx, errors.New("棋盘已存在"))
return
}
err, r := utils.CheckSudoku(sudokuParam.Sudoku)
if utils.ErrHandle(ctx, err) {
return
}
if r.Data.Check || checkSudokuCompleted(sudokuResult) {
if r.Data.Check {
if err1 := db.Create(&model.Sudoku{Sudoku: sudokuParam.Sudoku, Username: "admin", Result: r.Data.Result}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else {
if err1 := db.Create(&model.Sudoku{Sudoku: sudokuParam.Sudoku, Username: "admin", Result: sudokuParam.Result}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
} else {
utils.ErrHandle(ctx, errors.New("检测题目无法完成,请上传解题结果"))
return
}
}
func sudokuStringToList(sudoku string) ([9][9]string, error) {
var res [9][9]string
sudokuRows := strings.Split(sudoku, ";")
if len(sudokuRows) != 9 {
return res, errors.New("棋盘格式错误")
}
for r, row := range sudokuRows {
sudokuCols := strings.Split(row, ",")
if len(sudokuCols) != 9 {
return res, errors.New("棋盘格式错误")
}
for c, col := range sudokuCols {
if len(col) > 1 || strings.Index("123456789", col) == -1 {
return res, errors.New("棋盘格式错误")
}
res[r][c] = col
}
}
return res, nil
}
func sudokuListToString(sudoku [9][9]string) string {
var res string
for r, _ := range sudoku {
var tmp string
for c, _ := range sudoku[r] {
if tmp == "" {
tmp = sudoku[r][c]
} else {
tmp += "," + sudoku[r][c]
}
}
if res == "" {
res = tmp
} else {
res += ";" + tmp
}
}
return res
}
// 检查题目是否已完成
func checkSudokuCompleted(sudoku [9][9]string) bool {
for r, _ := range sudoku {
for c, _ := range sudoku[r] {
if sudoku[r][c] == "" || !checkNum(r, c, sudoku) {
return false
}
}
}
return true
}
// 检查题目当前位置是否符合要求
func checkNum(r int, c int, sudoku [9][9]string) bool {
if sudoku[r][c] == "" {
return true
}
for i, n := range sudoku[r] {
if n == sudoku[r][c] && i != c {
return false
}
}
for i, _ := range sudoku {
if sudoku[i][c] == sudoku[r][c] && i != r {
return false
}
}
for row := (r % 3) * 3; row < (r%3)*3+2; row++ {
for col := (c % 3) * 3; col < (c%3)*3+2; col++ {
if sudoku[row][col] == sudoku[r][c] && row != r && col != c {
return false
}
}
}
return true
}

View File

@ -0,0 +1,10 @@
package api
import (
"github.com/kataras/iris/v12"
)
func Sudoku(party iris.Party) {
party.Get("/", getSudokuList)
party.Post("/", addSudokuGame)
}

View File

@ -0,0 +1,59 @@
package api
import (
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"strings"
)
func getSysIcons(ctx iris.Context) {
var icons []model.SysIcons
db := database.GetInstance().GetMysqlDb()
if err := db.Find(&icons).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", icons))
if utils.ErrHandle(ctx, err) {
return
}
}
func addSysIcons(ctx iris.Context) {
var params sysIconsParam
var icons []model.SysIcons
var sysIcons []model.SysIcons
err := ctx.ReadJSON(&params)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Find(&sysIcons).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
for _, iconStr := range strings.Split(params.Icons, ",") {
icon := strings.Join([]string{"bi", iconStr}, "-")
if !checkIconExist(icon, sysIcons) {
icons = append(icons, model.SysIcons{Icon: icon})
sysIcons = append(sysIcons, model.SysIcons{Icon: icon})
}
}
if err1 := db.Create(&icons).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func checkIconExist(icon string, sysIcons []model.SysIcons) bool {
for _, sysIcon := range sysIcons {
if sysIcon.Icon == icon {
return true
}
}
return false
}

View File

@ -0,0 +1,8 @@
package api
import "github.com/kataras/iris/v12"
func SysSettings(party iris.Party) {
party.Get("/icon", getSysIcons)
party.Post("/icon", addSysIcons)
}

View File

@ -0,0 +1,96 @@
package api
import (
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"strconv"
"strings"
)
func getSystem(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
date := ctx.URLParam("date")
//username := "admin"
db := database.GetInstance().GetMysqlDb()
var systemList []resSystem
var ids []int
if err := db.Model(&model.SysInfo{}).Select("max(id)").Where("date = ? and username = ?", date, username.Username).Group("ip").Scan(&ids).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if err := db.Model(&model.SysInfo{}).Where("id in (?)", ids).Find(&systemList).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", systemList))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取当前系统信息
func getSysInfo(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
//username := "admin"
date := ctx.URLParam("date")
ip := ctx.URLParam("ip")
db := database.GetInstance().GetMysqlDb()
var sysInfoList []model.SysInfo
var res []resSysInfo
if err := db.Where("username = ? and date = ? and ip = ?", username.Username, date, ip).Find(&sysInfoList).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
for _, sysInfo := range sysInfoList {
var diskList []resDisk
diskLists := strings.Split(sysInfo.DiskPoint, ",")
for i, disk := range diskLists {
if strings.Contains(disk, "docker") {
continue
}
diskPer, err := strconv.ParseFloat(strings.Split(sysInfo.DiskPer, ",")[i], 64)
if utils.ErrHandle(ctx, err) {
return
}
diskList = append(diskList, resDisk{
Point: disk,
Total: strings.Split(sysInfo.DiskTotal, ",")[i],
Used: strings.Split(sysInfo.DiskUsed, ",")[i],
Per: utils.Round(diskPer, 2),
})
}
res = append(res, resSysInfo{
Datetime: sysInfo.Datetime,
CpuPer: utils.Round(sysInfo.CpuPer, 2),
Mem: resMem{
MemPer: utils.Round(sysInfo.MemPer, 2),
MemUsed: sysInfo.MemUsed,
MemTotal: sysInfo.MemTotal,
},
Disk: diskList,
Net: resNet{
Sent: sysInfo.SentSpeed,
Rec: sysInfo.RecSpeed,
},
})
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}
//func updateSysInfo(ctx iris.Context) {
// date := ctx.URLParam("date")
// crontab.UpdateSysInfo(date)
// err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", fmt.Sprintf("%s 日期数据同步完成", date)))
// if utils.ErrHandle(ctx, err) {
// return
// }
//}

View File

@ -0,0 +1,12 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func SysInfo(party iris.Party) {
party.Get("/server", jwtSet.Jwt.Serve, getSystem)
party.Get("/", jwtSet.Jwt.Serve, getSysInfo)
//party.Get("/update", updateSysInfo)
}

View File

@ -0,0 +1,178 @@
package api
import "time"
// user-----------------------------------------------------------------------------------------------
type result struct {
Date string
Password string
ConfirmCode string
UpdatedAt time.Time
Key string
AesKey string
}
// weather---------------------------------------------------------------------------------------------
type resWeather struct {
Status int `json:"status"`
Message string `json:"message"`
Data resData `json:"data"`
}
type resData struct {
Forecast24h resDate `json:"forecast_24h"`
}
type resDate struct {
D0 res24h `json:"1"`
D1 res24h `json:"2"`
}
type res24h struct {
Time string `json:"time"`
MaxDegree string `json:"max_degree"`
MinDegree string `json:"min_degree"`
DayWeather string `json:"day_weather"`
DayWindDirection string `json:"day_wind_direction"`
DayWindPower string `json:"day_wind_power"`
NightWeather string `json:"night_weather"`
NightWindPower string `json:"night_wind_power"`
NightWindDirection string `json:"night_wind_direction"`
}
type resLocation struct {
Data map[string]string `json:"data"`
Message string `json:"message"`
Status int `json:"status"`
}
// backgammon-----------------------------------------------------------------------------------------------
type typeRoomStatus struct {
RoomId int `json:"room_id"`
Player string `json:"player"`
}
// file-----------------------------------------------------------------------------------------------------
type filesRes struct {
Dirs []string `json:"dirs"`
Files []fileItem `json:"files"`
}
type fileItem struct {
Name string `json:"name"`
Type string `json:"type"`
Size int64 `json:"size"`
}
type videoM3u8 struct {
Video bool `json:"video"`
M3u8 bool `json:"m3u8"`
}
// notes------------------------------------------------------------------------------------------------------
type noteParam struct {
ID uint `json:"id"`
Content string `json:"content"`
}
// sysInfo------------------------------------------------------------------------------------------------------
type resSysInfo struct {
Datetime string `json:"datetime"`
CpuPer float64 `json:"cpu_per"`
Mem resMem `json:"mem"`
Disk []resDisk `json:"disk"`
Net resNet `json:"net"`
}
type resMem struct {
MemTotal string `json:"mem_total"`
MemUsed string `json:"mem_used"`
MemPer float64 `json:"mem_per"`
}
type resDisk struct {
Point string `json:"point"`
Total string `json:"total"`
Used string `json:"used"`
Per float64 `json:"per"`
}
type resNet struct {
Sent string `json:"sent"`
Rec string `json:"rec"`
}
type resSystem struct {
Hostname string `json:"hostname"`
Ip string `json:"ip"`
}
type sysInfoIDs struct {
IDs []int `json:"ids"`
}
// yeb----------------------------------------------------------------------------------------------------------
type paramsBalance struct {
Card string `json:"card"`
Type bool `json:"type"`
Balance float64 `json:"balance"`
}
type paramSZBalance struct {
Card string `json:"card"`
Type bool `json:"type"` // 1-支出0-收入
Amount float64 `json:"amount"`
}
// 月余额
type dateLog struct {
Date string `json:"date"`
Duration string `json:"duration"`
Changes float64 `json:"changes"`
Balance float64 `json:"balance"`
Detail []cardLog `json:"detail"`
}
// 详情
type cardLog struct {
Card string `json:"card"`
Balance float64 `json:"balance"`
Changes float64 `json:"changes"`
}
// menus-----------------------------------------------------------------------------
type resMenu struct {
MenuId string `json:"menu_id"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
RouteOnly bool `json:"route_only"`
Detail []subMenu `json:"detail"`
}
type subMenu struct {
MenuId string `json:"menu_id"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
RouteOnly bool `json:"route_only"`
}
type sysIconsParam struct {
Icons string `json:"icons"`
}
// sudoku-----------------------------------------------------------------------------
type resSudokuListType struct {
New []sudokuListType `json:"new"`
Starting []sudokuListType `json:"starting"`
Complete []sudokuListType `json:"complete"`
}
type sudokuListType struct {
Sudoku string `json:"sudoku"`
SudokuId uint `json:"sudokuId"`
Username string `json:"username"`
Status string `json:"status"`
Complete bool `json:"complete"`
Id uint `json:"id"`
}
type addSudokuParam struct {
Sudoku string `json:"sudoku"`
Result string `json:"result"`
}
// public ------------------------------------------------------------------------------
type ipLocationData struct {
Ip string `json:"ip"`
Location string `json:"location"`
}

View File

@ -0,0 +1,365 @@
package api
import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v4"
"github.com/jakehl/goid"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/jwtSet"
"main/model"
"main/service/admin"
"main/utils"
"math/rand"
"strconv"
"strings"
"time"
)
// 返回加密后用户信息
func userinfo(ctx iris.Context) {
user := utils.GetLoginUser(ctx)
if utils.DataIsNil(user) {
return
}
if user.Email != "" {
user.Email = fmt.Sprintf("%s****%s", user.Email[0:2], user.Email[len(user.Email)-7:])
}
if user.Mobile != "" {
user.Mobile = fmt.Sprintf("%s****%s", user.Mobile[0:2], user.Mobile[len(user.Mobile)-4:])
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", user))
if utils.ErrHandle(ctx, err) {
return
}
}
// 更新用户信息
func updateUserinfo(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
var params model.Userinfo
err := ctx.ReadJSON(&params)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if strings.Contains(params.Email, "*") {
params.Email = ""
}
if strings.Contains(params.Mobile, "*") {
params.Mobile = ""
}
if err1 := db.Model(&model.Userinfo{}).Where("username = ?", username.Username).Updates(params).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
for i, u := range utils.UserList {
if u.Username == username.Username {
utils.UserList[i] = params
}
}
utils.UpdateUserInfo()
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 用户登录
func login(ctx iris.Context) (string, error) {
username := ctx.URLParam("username")
password := ctx.URLParam("password")
confirmCode := ctx.URLParam("confirmCode")
auto := ctx.URLParam("auto")
var res result
db := database.GetInstance().GetMysqlDb()
if err := db.
Model(&model.User{}).
Select("users.password, users.confirm_code, users.updated_at, day_keys.key, day_keys.aes_key").
Joins("left join day_keys on day_keys.user = users.username and day_keys.date = users.date").
Where("users.username = ?", username).
Order("users.date desc").
Scan(&res).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(res) {
return "", errors.New("用户不存在")
}
rsaDePass, err := utils.RsaDecrypt(password, res.Key)
if err != nil {
return "", err
}
if confirmCode == "" {
aesDePass, err := utils.DecryptByAes(res.Password, []byte(res.AesKey))
if err != nil {
return "", err
}
//fmt.Println(string(aesDePass), rsaDePass)
if string(aesDePass) != rsaDePass {
return "", errors.New("用户信息错误")
}
} else if res.ConfirmCode != confirmCode {
return "", errors.New("验证码错误")
} else if res.ConfirmCode != "" && time.Now().After(res.UpdatedAt.Add(time.Minute*5)) {
return "", errors.New("验证码已过期")
}
priKeys, _ := utils.GetPrivateKeys(username, time.Now().Format("2006-01-02"))
newPwd, _ := utils.EncryptByAes([]byte(rsaDePass), []byte(priKeys.AesKey))
if err1 := db.
Model(&model.User{}).
Where("username = ?", username).
Updates(map[string]interface{}{
"password": newPwd,
"date": time.Now().Format("2006-01-02"),
"confirm_code": "",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
rand1 := rand.New(rand.NewSource(time.Now().UnixNano()))
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": username,
"iat": time.Now().Unix(),
"jti": strconv.Itoa(rand1.Int()),
"exp": time.Now().Add(2 * time.Hour).Unix(),
})
jwtKey := jwtSet.GetJwtKeys().Key
tokenString, err := token.SignedString([]byte(jwtKey))
if err != nil {
return "", err
}
ctx.SetCookieKV("is_login", "1", iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
ctx.SetCookieKV("token", tokenString, iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
ctx.SetCookieKV("loginTime", strconv.FormatInt(time.Now().UnixMilli(), 10), iris.CookieHTTPOnly(false))
if err1 := db.Create(&model.UserAction{
Username: username,
Action: "用户登录",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if err1 := db.Create(&model.JwtKeys{
Username: username,
Date: time.Now().Format("2006-01-02"),
Key: jwtKey,
Token: tokenString,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if auto == "true" {
deviceId := goid.NewV4UUID()
location := admin.GetIpLocation(utils.GetRequestIp(ctx))
ctx.SetCookieKV("deviceId", deviceId.String(), iris.CookieHTTPOnly(false))
if err1 := db.Create(&model.UserAutoLogin{
Username: username,
DeviceId: deviceId.String(),
Location: location,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
}
return tokenString, nil
}
// 用户注册
func register(ctx iris.Context) (string, error) {
username := ctx.URLParam("username")
password := ctx.URLParam("password")
priKeys, err := utils.GetPrivateKeys(username, time.Now().Format("2006-01-02"))
if err != nil {
return "", err
}
dePass, err := utils.RsaDecrypt(password, priKeys.Key)
if err != nil {
return "", err
}
enPass, err := utils.EncryptByAes([]byte(dePass), []byte(priKeys.AesKey))
if err != nil {
return "", err
}
db := database.GetInstance().GetMysqlDb()
var user []model.User
if err1 := db.Where("username = ?", username).Find(&user).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if len(user) > 0 {
err = errors.New("user exists")
return "", err
}
if err1 := db.Create(&model.User{
Username: username,
Password: enPass,
Date: time.Now().Format("2006-01-02"),
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if len(utils.UserList) == 0 {
if err1 := db.Create(&model.Userinfo{
Username: username,
Type: "admin",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else {
if err1 := db.Create(&model.Userinfo{
Username: username,
Type: "user",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
}
utils.UpdateUserInfo()
rand1 := rand.New(rand.NewSource(time.Now().UnixNano()))
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": username,
"iat": time.Now().Unix(),
"jti": strconv.Itoa(rand1.Int()),
"exp": time.Now().Add(2 * time.Hour).Unix(),
})
jwtKey := jwtSet.GetJwtKeys().Key
tokenString, err := token.SignedString([]byte(jwtKey))
if err != nil {
return "", err
}
ctx.SetCookieKV("is_login", "1", iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
ctx.SetCookieKV("token", tokenString, iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
ctx.SetCookieKV("loginTime", strconv.FormatInt(time.Now().UnixMilli(), 10), iris.CookieHTTPOnly(false))
if err1 := db.Create(&model.UserAction{
Username: username,
Action: "用户注册并登录",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if err1 := db.Create(&model.JwtKeys{
Username: username,
Date: time.Now().Format("2006-01-02"),
Key: jwtKey,
Token: tokenString,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
return tokenString, nil
}
// 退出登录
func logout(ctx iris.Context) {
db := database.GetInstance().GetMysqlDb()
username := utils.GetLoginUser(ctx)
auth := ctx.Values().Get("jwt")
deviceId := ctx.GetCookie("deviceId")
if auth == nil {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.SetErr(errors.New("未登录"))
return
}
if err := db.Where("token = ?", auth.(*jwt.Token).Raw).Delete(&model.JwtKeys{}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
ctx.RemoveCookie("is_login")
ctx.RemoveCookie("token")
if deviceId != "" {
ctx.RemoveCookie("deviceId")
if err := db.Where("device_id = ? and username = ?", deviceId, username).Delete(&model.UserAutoLogin{}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
}
if err := db.Create(&model.UserAction{
Username: username.Username,
Action: "用户注销登录",
}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 重置密码
func resetPwd(ctx iris.Context) {
username := ctx.URLParam("username")
//var user model.Userinfo
db := database.GetInstance().GetMysqlDb()
user := utils.GetUserInfo(username)
if utils.DataIsNil(user) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("用户不存在"))
return
}
confirmCode := utils.NewKey(8)
if err := db.Model(&model.User{}).Where("username = ?", username).Updates(model.User{ConfirmCode: confirmCode}).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := utils.SendEmail([]string{user.Email}, "密码重置", fmt.Sprintf("验证码为:%s\n您正在进行密码重置验证码5分钟内有效如非本人操作请忽略本邮件", confirmCode))
if utils.ErrHandle(ctx, err) {
return
}
if err1 := db.Create(&model.UserAction{
Username: username,
Action: "获取重置密码验证码",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", fmt.Sprintf("%s****%s", user.Email[0:2], user.Email[7:])))
if utils.ErrHandle(ctx, err) {
return
}
}
func autoLogin(ctx iris.Context) {
var user []model.UserAutoLogin
location := admin.GetIpLocation(utils.GetRequestIp(ctx))
deviceId := ctx.GetCookie("deviceId")
if deviceId == "" || location == "" {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "自动登录未设置", false))
if utils.ErrHandle(ctx, err) {
return
}
return
}
db := database.GetInstance().GetMysqlDb()
if err := db.Where("device_id = ? and location = ?", deviceId, location).Find(&user).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if len(user) == 0 {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "自动登录未设置", false))
if utils.ErrHandle(ctx, err) {
return
}
return
}
rand1 := rand.New(rand.NewSource(time.Now().UnixNano()))
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user[0].Username,
"iat": time.Now().Unix(),
"jti": strconv.Itoa(rand1.Int()),
"exp": time.Now().Add(2 * time.Hour).Unix(),
})
jwtKey := jwtSet.GetJwtKeys().Key
tokenString, err := token.SignedString([]byte(jwtKey))
if utils.ErrHandle(ctx, err) {
return
}
ctx.SetCookieKV("is_login", "1", iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
ctx.SetCookieKV("token", tokenString, iris.CookieHTTPOnly(false), iris.CookieExpires(2*time.Hour))
if err1 := db.Create(&model.UserAction{
Username: user[0].Username,
Action: "用户自动登录",
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if err1 := db.Create(&model.JwtKeys{
Username: user[0].Username,
Date: time.Now().Format("2006-01-02"),
Key: jwtKey,
Token: tokenString,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", tokenString))
if utils.ErrHandle(ctx, err) {
return
}
}

View File

@ -0,0 +1,46 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
"main/utils"
)
func User(party iris.Party) {
party.Get("/", jwtSet.Jwt.Serve, userinfo)
party.Put("/", jwtSet.Jwt.Serve, updateUserinfo)
party.Post("/", func(context iris.Context) {
token, err := register(context)
if utils.ErrHandle(context, err) {
return
}
err = context.JSON(utils.FormatRes(iris.StatusOK, "", token))
if err != nil {
return
}
})
party.Get("/login", func(context iris.Context) {
user := context.URLParam("username")
pubKey, err := utils.GetPublicKey(user)
if utils.ErrHandle(context, err) {
return
}
err = context.JSON(utils.FormatRes(200, "", pubKey))
if err != nil {
return
}
})
party.Post("/login", func(ctx iris.Context) {
token, err := login(ctx)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(200, "", token))
if err != nil {
return
}
})
party.Delete("/login", jwtSet.Jwt.Serve, logout)
party.Get("/reset", resetPwd)
party.Get("/auto", autoLogin)
}

View File

@ -0,0 +1,171 @@
package api
import (
"encoding/json"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"io"
"main/database"
"main/model"
"main/utils"
"net/http"
"net/url"
"strings"
"time"
)
// 获取location
func getLocation(ctx iris.Context) {
param := ctx.URLParam("location")
res, err := http.Get(fmt.Sprintf("https://wis.qq.com/city/like?source=pc&city=%s", param))
if utils.ErrHandle(ctx, err) {
return
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(res.Body)
body, _ := io.ReadAll(res.Body)
var r resLocation
//解析json结构
err = json.Unmarshal(body, &r)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(200, "", r.Data))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取天气方法
func getWeather(ctx iris.Context) {
user := utils.GetLoginUser(ctx)
if utils.DataIsNil(user) {
return
}
var info model.Userinfo
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ?", user.Username).First(&info).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
var location []string
if info.Location == "" {
location = []string{"北京", "北京", "顺义"}
} else {
info.Location = strings.ReplaceAll(info.Location, " ", "")
location = strings.Split(info.Location, ",")
if len(location) < 3 {
location = append(location, "")
}
}
res, err := getMyWeather(location[0], location[1], location[2])
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(200, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取地点对应地址天气
func getMyWeather(province string, city string, county string) (string, error) {
var weather []model.Weather
var respWeather string
db := database.GetInstance().GetMysqlDb()
if err := db.Where(&model.Weather{Date: time.Now().Format("2006-01-02"), Location: fmt.Sprintf("%s,%s,%s", province, city, county)}).Find(&weather).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if len(weather) == 0 {
resp, err := http.Get(fmt.Sprintf("https://wis.qq.com/weather/common?"+
"source=pc&weather_type=forecast_24h&province=%s&city=%s&county=%s", url.QueryEscape(province), url.QueryEscape(city), url.QueryEscape(county)))
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
var r resWeather
//解析json结构
err = json.Unmarshal(body, &r)
if err != nil {
//fmt.Println(fmt.Sprintf("https://wis.qq.com/weather/common?"+
// "source=pc&weather_type=forecast_24h&province=%s&city=%s&county=%s", url.QueryEscape(province), url.QueryEscape(city), url.QueryEscape(county)))
//fmt.Println(resp.Body, "----------", string(body), "----------", err)
return "", err
}
todayWeather := formatWeather(r.Data.Forecast24h.D0)
tomWeather := formatWeather(r.Data.Forecast24h.D1)
respWeather = fmt.Sprintf("%s;%s", todayWeather, tomWeather)
if err1 := db.Create(&model.Weather{
Date: time.Now().Format("2006-01-02"),
Location: fmt.Sprintf("%s,%s,%s", province, city, county),
Weather: respWeather,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else {
respWeather = weather[0].Weather
}
return respWeather, nil
}
// 天气格式化
func formatWeather(data res24h) string {
var weather string
var windPower string
var windDirection string
var degree string
if data.DayWeather == data.NightWeather {
weather = data.DayWeather
} else {
weather = fmt.Sprintf("%s转%s", data.NightWeather, data.DayWeather)
}
if data.DayWindDirection == data.NightWindDirection {
windDirection = data.DayWindDirection
} else {
windDirection = fmt.Sprintf("%s转%s", data.NightWindDirection, data.DayWindDirection)
}
if data.DayWindPower == data.NightWindPower {
windPower = data.DayWindPower + "级"
} else {
windPower = fmt.Sprintf("%s~%s级", data.NightWindPower, data.DayWindPower)
}
degree = fmt.Sprintf("%s~%s℃", data.MinDegree, data.MaxDegree)
return fmt.Sprintf("%s, %s, %s %s", weather, degree, windDirection, windPower)
}
func testWeather(ctx iris.Context) {
var location []string
loc := ctx.URLParam("location")
fmt.Println(loc)
if loc == "" {
location = []string{"北京", "北京", "顺义"}
fmt.Println(location)
} else {
loc = strings.ReplaceAll(loc, " ", "")
location = strings.Split(loc, ",")
if len(location) < 3 {
location = append(location, "")
}
fmt.Println(location)
}
res, err := getMyWeather(location[0], location[1], location[2])
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(200, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}

View File

@ -0,0 +1,12 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Weather(p iris.Party) {
p.Get("/", jwtSet.Jwt.Serve, getWeather)
p.Get("/location", getLocation)
p.Get("/test", testWeather)
}

206
api_iris/service/api/yeb.go Normal file
View File

@ -0,0 +1,206 @@
package api
import (
"errors"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"time"
)
func getYeb(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
var balances []model.Balances
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ?", username).Order("card").Find(&balances).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", balances))
if utils.ErrHandle(ctx, err) {
return
}
}
func addYeb(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
var balance paramsBalance
var tmpBalance []model.Balances
err := ctx.ReadJSON(&balance)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Where("username = ? and card = ?", username, balance.Card).Find(&tmpBalance).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if len(tmpBalance) > 0 {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("card已存在"))
return
}
if err1 := db.Create(&model.Balances{
Username: username,
Card: balance.Card,
Type: balance.Type,
Balance: balance.Balance,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if balance.Type {
balance.Balance = -balance.Balance
}
if err1 := db.Create(&model.BalanceLogs{
Username: username,
Card: balance.Card,
Date: time.Now().Format("2006-01-02"),
Balance: balance.Balance,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func updateYeb(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
var params paramsBalance
var balances []model.Balances
err := ctx.ReadJSON(&params)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Where("username = ? and card = ?", username, params.Card).Find(&balances).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if len(balances) == 0 {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("card 不存在"))
return
}
balances[0].Balance = params.Balance
balances[0].Type = params.Type
if err1 := db.Save(&balances[0]).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
//if err1 := db.Model(&balances).Update("balance", params.Balance).Error; err1 != nil {
// logrus.Errorln("sql执行失败", err1)
//}
if params.Type {
params.Balance = -params.Balance
}
if err1 := db.Create(&model.BalanceLogs{
Username: username,
Card: params.Card,
Date: time.Now().Format("2006-01-02"),
Balance: params.Balance,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func deleteYeb(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
var params paramsBalance
var balances []model.Balances
err := ctx.ReadJSON(&params)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Where("username = ? and card = ?", username, params.Card).Find(&balances).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if len(balances) == 0 {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("card 不存在"))
return
}
if err1 := db.Delete(&balances).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if err1 := db.Create(&model.BalanceLogs{
Username: username,
Card: params.Card,
Date: time.Now().Format("2006-01-02"),
Balance: 0,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
func szYeb(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
var params paramSZBalance
var balance model.Balances
err := ctx.ReadJSON(&params)
if utils.ErrHandle(ctx, err) {
return
}
db := database.GetInstance().GetMysqlDb()
if err1 := db.Where("username = ? and card = ?", username, params.Card).Find(&balance).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if utils.DataIsNil(balance) {
utils.ErrHandle(ctx, errors.New("card 不存在"))
return
}
if balance.Type == params.Type {
balance.Balance = utils.Round(balance.Balance+params.Amount, 2)
} else {
balance.Balance = utils.Round(balance.Balance-params.Amount, 2)
}
if err1 := db.Save(&balance).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
if balance.Type {
if err1 := db.Create(&model.BalanceLogs{
Username: username,
Card: params.Card,
Date: time.Now().Format("2006-01-02"),
Balance: -balance.Balance,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
} else {
if err1 := db.Create(&model.BalanceLogs{
Username: username,
Card: params.Card,
Date: time.Now().Format("2006-01-02"),
Balance: balance.Balance,
}).Error; err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}

View File

@ -0,0 +1,14 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func Yeb(party iris.Party) {
party.Get("/", jwtSet.Jwt.Serve, getYeb)
party.Post("/", jwtSet.Jwt.Serve, addYeb)
party.Put("/", jwtSet.Jwt.Serve, updateYeb)
party.Delete("/", jwtSet.Jwt.Serve, deleteYeb)
party.Post("/sz", jwtSet.Jwt.Serve, szYeb)
}

View File

@ -0,0 +1,220 @@
package api
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"math"
"sort"
"strings"
"time"
)
// 按月返回余额
func monthLog(ctx iris.Context) {
var balanceLogs []model.BalanceLogs
var res []dateLog
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ?", username).Order("id").Find(&balanceLogs).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if len(balanceLogs) == 0 {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if err != nil {
return
}
return
}
monthList := getMonthList(balanceLogs)
cardList := getCardList(balanceLogs)
for index, month := range monthList {
var cardLogs []cardLog
var balanceTmp float64
for _, card := range cardList {
b := getMonthBalance(balanceLogs, month, card)
if index == 0 {
cardLogs = append(cardLogs, cardLog{
Card: card,
Balance: b,
Changes: 0,
})
} else {
bTmp := getMonthBalance(balanceLogs, monthList[index-1], card)
cardLogs = append(cardLogs, cardLog{
Card: card,
Balance: b,
Changes: utils.Round(b-bTmp, 2),
})
}
balanceTmp += b
}
//cardLogs 排序
sort.Slice(cardLogs, func(i, j int) bool {
return math.Abs(cardLogs[i].Changes) > math.Abs(cardLogs[j].Changes)
})
if index == 0 {
res = append(res, dateLog{
Date: month,
Duration: "",
Changes: 0,
Balance: utils.Round(balanceTmp, 2),
Detail: cardLogs,
})
} else {
res = append(res, dateLog{
Date: month,
Duration: fmt.Sprintf("%s~%s", res[index-1].Date, month),
Changes: utils.Round(balanceTmp-res[index-1].Balance, 2),
Balance: utils.Round(balanceTmp, 2),
Detail: cardLogs,
})
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if err != nil {
return
}
}
// 获取时间段内详情
func detailLog(ctx iris.Context) {
username := utils.GetLoginUser(ctx).Username
if username == "" {
return
}
startDate := ctx.URLParam("start")
endDate := ctx.URLParam("end")
var res []dateLog
var balanceLogs []model.BalanceLogs
db := database.GetInstance().GetMysqlDb()
if err := db.Where("username = ? ", username).Find(&balanceLogs).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if len(balanceLogs) == 0 {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
return
}
dateList := getDateList(balanceLogs, startDate, endDate)
cardList := getCardList(balanceLogs)
for index, date := range dateList {
var cardLogs []cardLog
var balanceTmp float64
for _, card := range cardList {
b := getMonthBalance(balanceLogs, date, card)
if index == 0 {
cardLogs = append(cardLogs, cardLog{
Card: card,
Balance: b,
Changes: 0,
})
} else {
bTmp := getMonthBalance(balanceLogs, dateList[index-1], card)
cardLogs = append(cardLogs, cardLog{
Card: card,
Balance: b,
Changes: utils.Round(b-bTmp, 2),
})
}
balanceTmp += b
}
//cardLogs 排序
sort.Slice(cardLogs, func(i, j int) bool {
return math.Abs(cardLogs[i].Changes) > math.Abs(cardLogs[j].Changes)
})
if index == 0 {
res = append(res, dateLog{
Date: date,
Duration: "",
Changes: 0,
Balance: utils.Round(balanceTmp, 2),
Detail: cardLogs,
})
} else {
res = append(res, dateLog{
Date: date,
Duration: fmt.Sprintf("%s~%s", res[index-1].Date, date),
Changes: utils.Round(balanceTmp-res[index-1].Balance, 2),
Balance: utils.Round(balanceTmp, 2),
Detail: cardLogs,
})
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取数据中card截至month时的余额
func getMonthBalance(data []model.BalanceLogs, month string, card string) float64 {
var res float64
for _, v := range data {
if v.Card == card && v.Date <= month {
res = v.Balance
} else if v.Date > month {
break
}
}
return utils.Round(res, 2)
}
// 获取card列表
func getCardList(data []model.BalanceLogs) []string {
var resTmp []string
var res []string
for _, v := range data {
card := v.Card
if !utils.CheckListItem(resTmp, card) {
resTmp = append(resTmp, card)
res = append(res, card)
}
}
return res
}
// 获取月份列表
func getMonthList(data []model.BalanceLogs) []string {
var resTmp []string
var res []string
for _, v := range data {
month := fmt.Sprintf("%s-%s-01", strings.Split(v.Date, "-")[0], strings.Split(v.Date, "-")[1])
if !utils.CheckListItem(resTmp, month) {
resTmp = append(resTmp, month)
res = append(res, month)
}
}
t, _ := time.Parse("2006-01-02", data[len(data)-1].Date)
res = append(res, t.AddDate(0, 1, 0).Format("2006-01")+"-01")
return res
}
// 获取日期列表
func getDateList(data []model.BalanceLogs, start string, end string) []string {
var resTmp []string
var res []string
res = append(res, start)
for _, v := range data {
date := v.Date
if date <= start {
continue
} else if date >= end {
break
}
if !utils.CheckListItem(resTmp, date) {
resTmp = append(resTmp, date)
res = append(res, date)
}
}
res = append(res, end)
return res
}

View File

@ -0,0 +1,11 @@
package api
import (
"github.com/kataras/iris/v12"
"main/jwtSet"
)
func YebLog(party iris.Party) {
party.Get("/", jwtSet.Jwt.Serve, monthLog)
party.Get("/detail", jwtSet.Jwt.Serve, detailLog)
}