直播/录直播回放导出

router

package router

import (
	"github.com/gin-gonic/gin"
	aigcCtl "neptune/app/controller/aigc"
	artBookCtl "neptune/app/controller/artBook"
	chatRobot2 "neptune/app/controller/chatRobot"
	"neptune/app/controller/configCenter"
	"neptune/app/controller/cos"
	drama2 "neptune/app/controller/drama"
	"neptune/app/controller/edit"
	faceReco2 "neptune/app/controller/faceReco"
	"neptune/app/controller/healthCheck"
	itemReco2 "neptune/app/controller/itemReco"
	"neptune/app/controller/login"
	"neptune/app/controller/material"
	modelCtl "neptune/app/controller/model"
	"neptune/app/controller/pictureBook"
	"neptune/app/controller/poster"
	resourceCtl "neptune/app/controller/resource"
	"neptune/app/controller/retrieve"
	"neptune/app/controller/rtmp"
	"neptune/app/controller/tutor"
	"neptune/app/controller/video"
	"neptune/app/middleware"
)

// RegisterRouter api域
func RegisterRouter(router *gin.Engine) {
	router.GET("/v1/healthCheck", healthCheck.HealthCheck)

	//剪辑端获取推送模板: 后续使用 /v1/edit
	editAbandon := router.Group("/edit")
	editAbandon.GET("/get/pattern/video/template", configCenter.GetPatternVideoTemplateHandler)
	editAbandon.POST("/get/config", configCenter.GetEditConfigHandler)

	editor := router.Group("/v1/edit")
	editor.GET("/getVideoTemplate", configCenter.GetPatternVideoTemplateHandler)
	editor.POST("/getConfig", configCenter.GetEditConfigHandler)
	editor.GET("/getOssConfig", configCenter.GetOssConfigHandler)
	editor.POST("/getOssConfig", configCenter.GetOssConfigHandler)
	editor.GET("/getVideoByVideoId", video.GetVideoAndMetadataHandler)
	editor.GET("/getSpotInteraction", configCenter.GetSpotInteractionConfigHandler)
	editor.POST("/createVideo", video.CreateVideoHandler)
	editor.GET("/getMetadataInfo", video.GetMetadataInfoHandler)
	editor.GET("/getPattern", edit.GetPatternHandler)
	editor.GET("/subjectList", resourceCtl.SubjectList)
	editor.GET("/batchGetInteractionId", configCenter.BatchGetInteractionIdHandler)
	editor.GET("/getMetadataByPlanId", video.GetPlaybackMetadataHandler)
	editor.GET("/getReplayUrl", video.GetReplayUrlHandler)
	editor.POST("/testCosUpload", cos.TestCosUploadHandler)

	record := router.Group("/v1/record")
	record.GET("/tqrcodeLogin", login.QrCodeLoginHandler)
	record.GET("/getCourseWareInfo", video.GetCourseWareInfoHandler)
	record.POST("/getCourseWareInfo", video.GetCourseWareInfoHandler)
	record.GET("/getVideoByVideoId", video.GetVideoAndMetadataForRecordHandler)
	record.POST("/getVideoByVideoId", video.GetVideoAndMetadataForRecordHandler)
	record.GET("/getConfig", configCenter.GetConfigHandler)
	record.POST("/getConfig", configCenter.GetConfigHandler)
	record.Use(middleware.WorkCheckLogin())
	record.GET("/batchGetInteractionId", configCenter.BatchGetInteractionIdHandlerForRecord)
	record.POST("/batchGetInteractionId", configCenter.BatchGetInteractionIdHandlerForRecord)
	record.GET("/getVideoList", video.GetVideoListHandler)
	record.POST("/getVideoList", video.GetVideoListHandler)
	record.POST("/upsertFolder", video.UpsertFolderHandler)
	record.POST("/createVideo", video.CreateVideoHandler)
	record.POST("/deleteFolder", video.DeleteFolderHandler)
	record.POST("/updateVideoInfo", video.UpdateVideoInfoHandler)

	//课程设计平台
	//命名规则统一
	drama := router.Group("/v1/drama")
	drama.GET("/getCardGroups", drama2.GetCardGroups)
	drama.GET("/afterClassTasks", drama2.AfterClassTasks)
	drama.GET("/interactionType", drama2.InteractionType)
	drama.GET("/chapterIcon", drama2.ChapterIcon)
	drama.GET("/login", login.AdminLoginHandler)
	// 获取课件中的互动
	drama.POST("/getInteractionMeta", drama2.GetInteractionMeta)
	drama.POST("/dramaDetail", drama2.DramaDetail)
	drama.POST("/chapterDetail", drama2.ChapterDetail)
	drama.POST("/sectionSearch", drama2.SectionSearch)
	drama.POST("/checkExplore", drama2.CheckExplore)
	drama.POST("/superScoreDrama", drama2.SuperScoreDrama)

	drama.Use(middleware.WorkCheckLogin())
	drama.POST("/create", drama2.Create)
	drama.POST("/update", drama2.Update)
	drama.POST("/setInteractionConfig", drama2.SetInteractionConfig)
	drama.POST("/getInteractionConfig", drama2.GetInteractionConfig)
	drama.POST("/search", drama2.Search)
	drama.POST("/delete", drama2.Delete)
	drama.POST("/duplicate", drama2.Duplicate)
	drama.POST("/getDramaDetail", drama2.GetDramaDetail)
	drama.POST("/publishDrama", drama2.PublishDrama)
	drama.POST("/checkDramaUpdate", drama2.CheckDramaUpdate)

	drama.POST("/publishInteraction", drama2.PublishInteraction)
	drama.POST("/interactionSearch", drama2.InteractionSearch)
	drama.POST("/createInteraction", drama2.CreateInteraction)
	drama.POST("/duplicateInteraction", drama2.DuplicateInteraction)
	drama.POST("/updateInteraction", drama2.UpdateInteraction)
	drama.POST("/deleteInteraction", drama2.DeleteInteraction)

	drama.POST("/chapterCreate", drama2.ChapterCreate)
	drama.POST("/chapterUpdate", drama2.ChapterUpdate)
	drama.POST("/chapterDelete", drama2.ChapterDelete)
	drama.POST("/chapterOrderUpdate", drama2.ChapterOrderUpdate)

	drama.POST("/sectionCreate", drama2.SectionCreate)
	drama.POST("/sectionUpdate", drama2.SectionUpdate)
	drama.POST("/sectionDelete", drama2.SectionDelete)
	drama.POST("/sectionOrderUpdate", drama2.SectionOrderUpdate)

	drama.POST("/modelIDCheck", drama2.ModelIDCheck)

	//录制资源管理后台
	resource := router.Group("/v1/resource")
	resource.GET("/getSuperScoreVideoList", resourceCtl.GetSuperScoreVideoList)
	resource.POST("/saveNewVideo", resourceCtl.SaveNewVideo)
	resource.GET("/subjectList", resourceCtl.SubjectList)
	resource.GET("/videoPlay", resourceCtl.VideoPlay)
	resource.POST("/searchVideoInfo", resourceCtl.SearchVideoInfo)
	resource.Use(middleware.WorkCheckLogin())
	resource.POST("/auditVideos", resourceCtl.AuditVideos)

	student := router.Group("/v1/student")
	student.POST("/getReadVideoUrl", video.GetReadVideoUrlHandler)

	posterGroup := router.Group("/v1/poster")
	posterGroup.POST("/getPosterModel", poster.GetPosterModelHandler)
	posterGroup.POST("/getPosterDetailById", poster.GetPosterDetailByIdHandler) // 通过id获取海报配置详情
	posterGroup.POST("/getTaskProgressDetail", poster.GetTaskProgressDetailHandler)
	posterGroup.POST("/parsePosterXlsx", poster.ParsePosterXlsxHandler)
	posterGroup.Use(middleware.TokenAuthValidate())
	posterGroup.POST("/getModelList", poster.GetModelListHandler)
	posterGroup.POST("/addModel", poster.AddModelHandler)
	posterGroup.POST("/delModel", poster.DelModelHandler)
	posterGroup.POST("/editModel", poster.EditModelHandler)
	posterGroup.POST("/delPic", poster.DelPicHandler)
	posterGroup.POST("/online", poster.OnlineHandler)
	posterGroup.POST("/copyModel", poster.CopyModelHandler)
	posterGroup.POST("/continueGen", poster.ContinueGenHandler)
	posterGroup.POST("/finalizeTheDraft", poster.FinalizeTheDraftHandler)

	pictureBookGroup := router.Group("/v1/pictureBook")
	pictureBookGroup.POST("/getPictureBookModel", pictureBook.GetPictureBookModelHandler)
	pictureBookGroup.POST("/missionCallback", pictureBook.MissionCallbackHandler)
	pictureBookGroup.POST("/getTaskProgressDetail", pictureBook.GetTaskProgressDetailHandler)
	pictureBookGroup.Use(middleware.TokenAuthValidate())
	pictureBookGroup.POST("/getModelList", pictureBook.GetModelListHandler) // 获取绘本配置列表
	pictureBookGroup.POST("/getModelConfig", pictureBook.GetDetailHandler)  // 通过id获取绘本配置详情
	pictureBookGroup.POST("/parsePictureBookXlsx", pictureBook.ParsePictureBookXlsxHandler)
	pictureBookGroup.POST("/addModel", pictureBook.AddModelHandler)
	pictureBookGroup.POST("/editModel", pictureBook.EditModelHandler)
	pictureBookGroup.POST("/delModel", pictureBook.DelModelHandler)
	pictureBookGroup.POST("/online", pictureBook.OnlineHandler)
	pictureBookGroup.POST("/delPic", pictureBook.DelPicHandler)
	pictureBookGroup.POST("/copyModel", pictureBook.CopyModelHandler)
	pictureBookGroup.POST("/continueGen", pictureBook.ContinueGenHandler)
	pictureBookGroup.POST("/finalizeTheDraft", pictureBook.FinalizeTheDraftModelHandler)

	// AI模型管理素材审核回调接口
	aiModelGroup := router.Group("/v1/aimodel")
	aiModelGroup.POST("/material/auditCallback", material.DefaultMaterialController.MaterialAuditCallback)
	aiModelGroup.GET("/mockAudit", modelCtl.MockAuditModel)

	// AI聊天机器人
	chatRobot := router.Group("/v1/chatRobot")
	chatRobot.POST("/getTextLibrary", chatRobot2.DefaultChatRobotController.GetTextLibrary)
	chatRobot.Use(middleware.TokenAuthValidate())
	chatRobot.POST("/list", chatRobot2.DefaultChatRobotController.GetChatRobotList)
	chatRobot.POST("/detail", chatRobot2.DefaultChatRobotController.GetChatRobotDetail)
	chatRobot.POST("/finalize", chatRobot2.DefaultChatRobotController.FinalizeChatRobot)
	chatRobot.POST("/copy", chatRobot2.DefaultChatRobotController.CopyChatRobot)
	chatRobot.POST("/add", chatRobot2.DefaultChatRobotController.AddChatRobot)
	chatRobot.POST("/delete", chatRobot2.DefaultChatRobotController.DeleteChatRobot)
	chatRobot.POST("/edit", chatRobot2.DefaultChatRobotController.EditChatRobot)
	chatRobot.POST("/continueGen", chatRobot2.DefaultChatRobotController.ContinueGenChatRobot)
	chatRobot.POST("/online", chatRobot2.DefaultChatRobotController.OnlineChatRobot)
	chatRobot.POST("/deleteImgs", chatRobot2.DefaultChatRobotController.DeleteChatRobotImgs)
	chatRobot.POST("/getImgLibrary", chatRobot2.DefaultChatRobotController.GetChatRobotImgLibrary)
	chatRobot.POST("/deleteTexts", chatRobot2.DefaultChatRobotController.DeleteChatRobotTexts)

	// AI人脸识别
	faceReco := router.Group("/v1/faceReco")
	faceReco.Use(middleware.TokenAuthValidate())
	faceReco.POST("/list", faceReco2.DefaultFaceRecoController.GetFaceRecoList)
	faceReco.POST("/detail", faceReco2.DefaultFaceRecoController.GetFaceRecoDetail)
	faceReco.POST("/finalize", faceReco2.DefaultFaceRecoController.FinalizeFaceReco)
	faceReco.POST("/copy", faceReco2.DefaultFaceRecoController.CopyFaceReco)
	faceReco.POST("/add", faceReco2.DefaultFaceRecoController.AddFaceReco)
	faceReco.POST("/delete", faceReco2.DefaultFaceRecoController.DeleteFaceReco)
	faceReco.POST("/edit", faceReco2.DefaultFaceRecoController.EditFaceReco)

	// AI物品识别
	itemReco := router.Group("/v1/itemReco")
	itemReco.Use(middleware.TokenAuthValidate())
	itemReco.POST("/list", itemReco2.DefaultItemRecoController.GetItemRecoList)
	itemReco.POST("/detail", itemReco2.DefaultItemRecoController.GetItemRecoDetail)
	itemReco.POST("/finalize", itemReco2.DefaultItemRecoController.FinalizeItemReco)
	itemReco.POST("/copy", itemReco2.DefaultItemRecoController.CopyItemReco)
	itemReco.POST("/add", itemReco2.DefaultItemRecoController.AddItemReco)
	itemReco.POST("/delete", itemReco2.DefaultItemRecoController.DeleteItemReco)
	itemReco.POST("/edit", itemReco2.DefaultItemRecoController.EditItemReco)

	//AI模型管理后台
	model := router.Group("/v1/model")
	model.GET("/model/getModel", modelCtl.GetModel)
	model.GET("/model/enums", modelCtl.GetModelEnums)
	model.GET("/robotAssistant/list", modelCtl.GetRobotAssistantList)
	model.GET("/robotAssistant/detail", modelCtl.GetRobotAssistantDetail)
	model.POST("/model/searchModel", modelCtl.SearchModel)
	model.POST("/model/verifyModel", modelCtl.VerifyModel)

	model.Use(middleware.TokenAuthValidate())
	model.POST("/robotAssistant/add", modelCtl.CreateRobotAssistant)
	model.POST("/robotAssistant/edit", modelCtl.UpdateRobotAssistant)
	model.POST("/robotAssistant/copy", modelCtl.CopyRobotAssistant)
	model.POST("/robotAssistant/finalize", modelCtl.FinalizeRobotAssistant)
	model.POST("/robotAssistant/del", modelCtl.DeleteRobotAssistant)

	//AIGC服务
	aigc := router.Group("/v1/aigc")
	aigc.POST("/text2audio", aigcCtl.Text2Audio)
	aigc.POST("/mediaAudit", aigcCtl.MediaAudit)
	aigc.POST("/text2text", aigcCtl.Text2Text)
	aigc.POST("/text2img", aigcCtl.Text2Img)
	aigc.POST("/getText2ImgResult", aigcCtl.GetText2ImgResult)

	// 智能手册
	artBookRouter := router.Group("/v1/artBook")
	artBookRouter.POST("/getArtBookModel", artBookCtl.GetArtBookModelHandler)
	artBookRouter.POST("/getModelConfig", artBookCtl.GetModelConfigHandler) // done
	artBookRouter.POST("/getTaskProgressDetail", artBookCtl.GetTaskProgressDetailHandler)
	artBookRouter.Use(middleware.TokenAuthValidate())
	artBookRouter.POST("/getModelList", artBookCtl.GetModelListHandler) // done

	artBookRouter.POST("/addModel", artBookCtl.AddModelHandler)   // done
	artBookRouter.POST("/editModel", artBookCtl.EditModelHandler) // done
	artBookRouter.POST("/delModel", artBookCtl.DelModelHandler)   // done
	artBookRouter.POST("/copyModel", artBookCtl.CopyModelHandler) // done
	artBookRouter.POST("/online", artBookCtl.OnlineHandler)
	artBookRouter.POST("/delPic", artBookCtl.DelPicHandler)
	artBookRouter.POST("/continueGen", artBookCtl.ContinueGenHandler)
	artBookRouter.POST("/finalizeTheDraft", artBookCtl.FinalizeTheDraftModelHandler) // done

	rtmpCheckerRouter := router.Group("/v1/rtmpChecker")
	rtmpCheckerRouter.GET("/getTencentPushStreamInfo", rtmp.GetTencentPushStreamInfo)
	rtmpCheckerRouter.GET("/getAliPushStreamInfo", rtmp.GetAliPushStreamInfo)

	// 大阅读AI写作助手
	tutorG := router.Group("/v1/tutor")
	tutorG.Use(middleware.TokenAuthValidate())
	tutorG.POST("/add", tutor.DefaultController.Add)
	tutorG.POST("/copy", tutor.DefaultController.Copy)
	tutorG.POST("/edit", tutor.DefaultController.Edit)
	tutorG.POST("/list", tutor.DefaultController.List)
	tutorG.POST("/detail", tutor.DefaultController.Detail)
	tutorG.POST("/finalize", tutor.DefaultController.Finalize)
	tutorG.POST("/delete", tutor.DefaultController.Delete)

	//取直播回放
	retrieveRouter := router.Group("/v1/retrieve")
	//retrieveRouter.Use(middleware.TokenAuthValidate())
	retrieveRouter.POST("/add", retrieve.AddRe)
	retrieveRouter.POST("/addRecord", retrieve.AddRecord)

	retrieveRouter.GET("/list", retrieve.ListRe)
	retrieveRouter.DELETE("/delete", retrieve.DeleteRe)
	retrieveRouter.POST("/pass", retrieve.PassIn)
	retrieveRouter.POST("/unpass", retrieve.UnPassIn)
	retrieveRouter.GET("/getList", retrieve.ListUid)

}

controller 

package retrieve

import (
	"encoding/csv"
	"errors"
	"fmt"
	"git.100tal.com/wangxiao_go_lib/xesGoKit/xesgin"
	logger "git.100tal.com/wangxiao_go_lib/xesLogger"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"io"
	"neptune/app/entity/retrieve"
	service "neptune/app/service/retrieve"
	"net/http"
)

//直播
func AddRe(c *gin.Context) {
	logTag := "retrieve.AddRe"
	ctx := xesgin.TransferToContext(c)
	var args retrieve.Retrieve
	err := c.ShouldBind(&args)
	//直播
	args.ReStatus = "0"
	if err != nil {
		logger.Ex(ctx, logTag, "AddRe error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	err = CheckRetrieveParamsHandler(args)
	if err != nil {
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	inRetrieve, err := service.NewInRetrieveService().AddInRetrieve(ctx, args)
	if err != nil {
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	c.JSON(http.StatusOK, xesgin.Success(inRetrieve))
	return
}

//录直播
func AddRecord(c *gin.Context) {
	logTag := "retrieve.AddRecord"
	ctx := xesgin.TransferToContext(c)
	var args retrieve.Retrieve
	err := c.ShouldBind(&args)
	//录直播
	args.ReStatus = "1"
	if err != nil {
		logger.Ex(ctx, logTag, "AddRe error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	err = CheckRetrieveParamsHandler1(args)
	if err != nil {
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	inRetrieve, err := service.NewInRetrieveService().AddInRetrieveRecording(ctx, args)
	if err != nil {
		c.JSON(http.StatusOK, xesgin.Error(err))
		return
	}
	c.JSON(http.StatusOK, xesgin.Success(inRetrieve))
	return
}

func ListRe(c *gin.Context) {
	logTag := "app.controller.retrieve.ListRe"
	ctx := xesgin.TransferToContext(c)
	params := &retrieve.SearchParams{
		Name:   cast.ToString(c.Query("name")),
		Status: cast.ToInt(c.Query("status")),
	}
	inRetrieve, err := service.NewInRetrieveService().ListInRetrieve(ctx, params)
	if err != nil {
		logger.Ex(ctx, logTag, "ListRe error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(inRetrieve))
	return

}
func ListUid(c *gin.Context) {
	logTag := "app.controller.retrieve.ListUid"
	ctx := xesgin.TransferToContext(c)
	id := c.Query("uid")
	idI, err := service.NewInRetrieveService().ListR(ctx, cast.ToString(id))
	if err != nil {
		logger.Ex(ctx, logTag, "List error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(idI))
}
func ListInRetrieveByStatus(c *gin.Context) {
	logTag := "app.controller.retrieve.ListInRetrieveByStatus"
	ctx := xesgin.TransferToContext(c)
	status := c.Query("status")
	statusI, err := service.NewInRetrieveService().ListByStatus(ctx, cast.ToInt(status))
	if err != nil {
		logger.Ex(ctx, logTag, "ListByStatus error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(statusI))
}
func ListInRetrieveByNameAndStatus(c *gin.Context) {
	logTag := "app.controller.retrieve.ListInRetrieveByNameAndStatus"
	ctx := xesgin.TransferToContext(c)
	status := c.Query("status")
	name := c.Query("name")
	list, err := service.NewInRetrieveService().ListByNameAndeStatus(ctx, cast.ToString(name), cast.ToInt(status))
	if err != nil {
		logger.Ex(ctx, logTag, "ListByNameAndeStatus error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(list))
}
func DeleteRe(c *gin.Context) {
	logTag := "app.controller.retrieve.DeleteRe"
	ctx := xesgin.TransferToContext(c)
	id := c.Query("id")
	idI, err := service.NewInRetrieveService().DeleteInRetrieve(ctx, cast.ToInt(id))
	if err != nil {
		logger.Ex(ctx, logTag, "DeleteRe error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(idI))
}
func PassIn(c *gin.Context) {
	logTag := "app.controller.retrieve.PassIn"
	ctx := xesgin.TransferToContext(c)
	id := c.Query("id")
	idI, err := service.NewInRetrieveService().PassIn(ctx, cast.ToInt(id))
	if err != nil {
		logger.Ex(ctx, logTag, "Pass error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(idI))
}

func UnPassIn(c *gin.Context) {
	logTag := "app.controller.retrieve.UnPassIn"
	ctx := xesgin.TransferToContext(c)
	id := c.Query("id")
	idI, err := service.NewInRetrieveService().UnPassInRetrieve(ctx, cast.ToInt(id))
	if err != nil {
		logger.Ex(ctx, logTag, "Pass error[%s].", err.Error())
		c.JSON(http.StatusOK, xesgin.Error(err))
	}
	c.JSON(http.StatusOK, xesgin.Success(idI))
}
func CheckRetrieveParamsHandler(args retrieve.Retrieve) error {

	if len(args.File) != 0 {

		resp, err := http.Get(args.File[0])
		if err != nil {
			return errors.New("文件不能打开")
		}

		defer resp.Body.Close()

		// 创建一个新的CSV reader
		reader := csv.NewReader(resp.Body)

		// 循环读取文件的每一行
		for {
			record, err := reader.Read()
			if err == io.EOF {
				break
			}
			// 检查列的数量
			if len(record) != 3 {
				fmt.Println(record)
				return errors.New("文件内容列数必须为3")
			}
		}

	}
	return nil
}
func CheckRetrieveParamsHandler1(args retrieve.Retrieve) error {

	if len(args.File) != 0 {

		resp, err := http.Get(args.File[0])
		if err != nil {
			return errors.New("文件不能打开")
		}

		defer resp.Body.Close()

		// 创建一个新的CSV reader
		reader := csv.NewReader(resp.Body)

		// 循环读取文件的每一行
		for {
			record, err := reader.Read()
			if err == io.EOF {
				break
			}
			// 检查列的数量
			if len(record) != 1 {
				fmt.Println(record)
				return errors.New("文件内容列数必须为1")
			}
		}

	}
	return nil
}

service

package retrieve

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/csv"
	"encoding/json"
	"errors"
	"fmt"
	logger "git.100tal.com/wangxiao_go_lib/xesLogger"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"io"
	"io/ioutil"
	"neptune/app/entity/retrieve"
	"neptune/app/repository/mysqlRepo"
	"net/http"
	"strings"
	"time"
)

type InRetrieveService interface {
	AddInRetrieve(ctx context.Context, args retrieve.Retrieve) (retrieve.InRetrieve, error)
	AddInRetrieveRecording(ctx context.Context, args retrieve.Retrieve) (retrieve.InRetrieve, error)
	DeleteInRetrieve(ctx context.Context, id int) (interface{}, error)
	ListInRetrieve(ctx context.Context, params *retrieve.SearchParams) (interface{}, error)
	PassInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) (interface{}, error)
	PassInRetrieveRecording(ctx context.Context, inRetrieve *retrieve.InRetrieve) (interface{}, error)
	UnPassInRetrieve(ctx context.Context, id int) (interface{}, error)
	ListR(ctx context.Context, uid string) (interface{}, error)
	ListByStatus(ctx context.Context, status int) (interface{}, error)
	ListByNameAndeStatus(ctx context.Context, name string, status int) (interface{}, error)
	PassIn(ctx context.Context, id int) (interface{}, error)
}

type inRetrieveServiceImpl struct {
	liveReplayRequestsDao mysqlRepo.LiveReplayRequestsDao
}

var (
	_ InRetrieveService = (*inRetrieveServiceImpl)(nil)
)

func NewInRetrieveService() InRetrieveService {
	return &inRetrieveServiceImpl{
		liveReplayRequestsDao: mysqlRepo.DefaultLiveReplayRequestsDao,
	}
}
func (i *inRetrieveServiceImpl) AddInRetrieve(ctx context.Context, args retrieve.Retrieve) (retrieve.InRetrieve, error) {
	logTag := "service.retrieve.AddInRetrieve"
	var task string
	var inRetrieve retrieve.InRetrieve
	if len(args.File) == 0 {
		args.RequestType = "FORM"
	} else {
		args.RequestType = "FILE"
	}
	if args.RequestType == "FORM" {
		task = args.EventId + "_" + args.SpeakerId + "_" + args.Course
	} else {
		task = args.File[0]
	}
	//将请求写入数据库
	inRetrieve = retrieve.InRetrieve{
		Name:        args.Name,
		Task:        task,
		RequestType: args.RequestType,
		CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
		Restatus:    cast.ToInt(args.ReStatus),
	}
	err := i.liveReplayRequestsDao.AddInRetrieve(ctx, &inRetrieve)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddInRetrieve err: %s", err.Error()))
		return retrieve.InRetrieve{}, nil
	}
	return inRetrieve, nil
}

func (i *inRetrieveServiceImpl) AddInRetrieveRecording(ctx context.Context, args retrieve.Retrieve) (retrieve.InRetrieve, error) {
	logTag := "service.retrieve.AddInRetrieveRecording"
	var task string
	var inRetrieve retrieve.InRetrieve
	if len(args.File) == 0 {
		args.RequestType = "FORM"
	} else {
		args.RequestType = "FILE"
	}
	if args.RequestType == "FORM" {
		task = args.EventId
	} else {
		task = args.File[0]
	}
	//将请求写入数据库
	inRetrieve = retrieve.InRetrieve{
		Name:        args.Name,
		Task:        task,
		RequestType: args.RequestType,
		CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
		Restatus:    cast.ToInt(args.ReStatus),
	}
	err := i.liveReplayRequestsDao.AddInRetrieve(ctx, &inRetrieve)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddInRetrieve err: %s", err.Error()))
		return retrieve.InRetrieve{}, nil
	}
	return inRetrieve, nil
}

func (i *inRetrieveServiceImpl) DeleteInRetrieve(ctx context.Context, id int) (interface{}, error) {
	logTag := "service.retrieve.DeleteInRetrieve"
	err := i.liveReplayRequestsDao.DeleteInRetrieve(ctx, id)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao DeleteInRetrieve err: %s", err.Error()))
		return nil, err
	}
	return id, nil
}

func (i *inRetrieveServiceImpl) ListInRetrieve(ctx context.Context, params *retrieve.SearchParams) (interface{}, error) {
	logTag := "service.retrieve.ListInRetrieve"
	inRetrieve, err := i.liveReplayRequestsDao.ListInRetrieve(ctx, params)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao ListInRetrieve err: %s", err.Error()))
		return nil, err
	}
	return inRetrieve, nil
}
func (i *inRetrieveServiceImpl) ListR(ctx context.Context, uid string) (interface{}, error) {
	logTag := "service.retrieve.ListRService"
	linkR, err := i.liveReplayRequestsDao.GetLinkR(ctx, uid)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao ListR err: %s", err.Error()))
		return nil, err
	}
	return linkR, nil
}
func (i *inRetrieveServiceImpl) ListByStatus(ctx context.Context, status int) (interface{}, error) {
	logTag := "service.retrieve.ListByStatusService"
	ListS, err := i.liveReplayRequestsDao.GetInRetrieveByStatus(ctx, status)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao GetInRetrieveByStatus err: %s", err.Error()))
		return nil, err
	}
	return ListS, nil
}
func (i *inRetrieveServiceImpl) ListByNameAndeStatus(ctx context.Context, name string, status int) (interface{}, error) {
	logTag := "service.retrieve.ListByNameAndStatusService"
	ListS, err := i.liveReplayRequestsDao.GetInRetrieveByNameAndStatus(ctx, name, status)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao GetInRetrieveByNameAndStatus err: %s", err.Error()))
		return nil, err
	}
	return ListS, nil
}

//直播
func (i *inRetrieveServiceImpl) PassInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) (interface{}, error) {
	logTag := "service.retrieve.PassInRetrieve"
	uid := uuid.New().String()
	//一条消息
	if inRetrieve.RequestType == "FORM" {
		//拼接URL
		retrieveUrl := "https://gslbsaturn.xescdn.com/v1/player/vodshow?appid=xes10001&udata=gKaGzoaj4njY&support=4&proto=2&scheme=3&fid=/xes10001/xes10001_3_" + inRetrieve.Task + "/index.m3u8&traceid=d3700c71bfb045e790443bb3c7f4bdd5&agentp=psplayer-ios&agentv=2.8.8&bid=7&uri=/xes10001/xes10001_3_" + inRetrieve.Task + "/index.m3u8&psid=gKaGzoaj4njY&os=iPadOS16.3.1&dev=iPad11%2C6&arch=ARM64E&uid=57968009&cfg=2"
		addrStr, err := GetAddr(ctx, retrieveUrl)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
			return nil, err
		}

		//发送消息
		ticket, err := GetOssTicket()
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("GetOssTicket err: %s", err.Error()))
			return nil, err
		}
		parts := strings.Split(inRetrieve.Task, "_")
		if parts[2] == "0" {
			parts[2] = "课中"
		} else if parts[2] == "1" {
			parts[2] = "课前"
		} else {
			parts[2] = "课后"
		}
		linkR := &retrieve.LinkR{
			UId:       uid,
			EventId:   cast.ToInt(parts[0]),
			SpeakerId: cast.ToInt(parts[1]),
			Course:    parts[2],
			Link:      cast.ToString(addrStr),
		}
		err = i.liveReplayRequestsDao.AddLink(ctx, linkR)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddLink err: %s", err.Error()))
			return nil, err
		}
		mess := fmt.Sprintf("{\"msgtype\":\"text\",\"text\":{\"content\":\"您的搜索id为%s,请根据搜索id去网站中查询视频链接\"}}", linkR.UId)
		mess = base64.StdEncoding.EncodeToString([]byte(mess))
		err = SendMsg(ctx, ticket, inRetrieve.Name, mess)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("SendMsg err: %s", err.Error()))
			return nil, err
		}
		fmt.Println(linkR.Link)
		//审核通过,修改审核状态
		inRetrieve.Status = 1
		err = i.liveReplayRequestsDao.UpdateInRetrieve(ctx, inRetrieve)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("UpdateInRetrieve err: %s", err.Error()))
			return nil, err
		}
	} else {
		//多条消息
		var linkR *retrieve.LinkR
		// 打开文件
		resp, err := http.Get(inRetrieve.Task)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("http.Get err: %s", err))
			return nil, err
		}
		defer resp.Body.Close()
		reader := csv.NewReader(resp.Body)
		// 读取并处理CSV文件的每一行
		for {
			record, err := reader.Read()
			if err == io.EOF {
				break
			}
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("csv read err: %s", err.Error()))
				return retrieve.InRetrieve{}, nil
			}
			eventId := record[0]
			speakerId := record[1]
			courseId := record[2]
			// 将这一行的所有列用"_"拼接起来
			joinedRecord := strings.Join(record, "_")
			retrieveUrl := "https://gslbsaturn.xescdn.com/v1/player/vodshow?appid=xes10001&udata=gKaGzoaj4njY&support=4&proto=2&scheme=3&fid=/xes10001/xes10001_3_" + joinedRecord + "/index.m3u8&traceid=d3700c71bfb045e790443bb3c7f4bdd5&agentp=psplayer-ios&agentv=2.8.8&bid=7&uri=/xes10001/xes10001_3_" + joinedRecord + "/index.m3u8&psid=gKaGzoaj4njY&os=iPadOS16.3.1&dev=iPad11%2C6&arch=ARM64E&uid=57968009&cfg=2"
			addrStr, err := GetAddr(ctx, retrieveUrl)
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
				return nil, err
			}

			if courseId == "0" {
				courseId = "课中"
			} else if courseId == "1" {
				courseId = "课前"
			} else {
				courseId = "课后"
			}
			linkR = &retrieve.LinkR{
				UId:       uid,
				EventId:   cast.ToInt(eventId),
				SpeakerId: cast.ToInt(speakerId),
				Course:    courseId,
				Link:      cast.ToString(addrStr),
			}
			err = i.liveReplayRequestsDao.AddLink(ctx, linkR)
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddLink err: %s", err.Error()))
				return nil, err
			}

		}
		//发送消息
		ticket, err := GetOssTicket()
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("GetOssTicket err: %s", err.Error()))
			return nil, err
		}
		mess := fmt.Sprintf("{\"msgtype\":\"text\",\"text\":{\"content\":\"您的搜索id为%s,请根据搜索id去网站中查询视频链接\"}}", linkR.UId)
		mess = base64.StdEncoding.EncodeToString([]byte(mess))
		err = SendMsg(ctx, ticket, inRetrieve.Name, mess)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao SendMsg err: %s", err.Error()))
			return nil, err
		}
		//审核通过,修改审核状态
		inRetrieve.Status = 1
		err = i.liveReplayRequestsDao.UpdateInRetrieve(ctx, inRetrieve)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("UpdateInRetrieve err: %s", err.Error()))
			return nil, err
		}
	}

	//保存回档记录
	var archive *retrieve.Archive
	archive = &retrieve.Archive{
		Task:       inRetrieve.Task,
		Initiator:  inRetrieve.Name,
		ReviewTime: time.Now(),
		Status:     1,
	}
	err := i.liveReplayRequestsDao.AddArchive(ctx, archive)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddArchive err: %s", err.Error()))
		return nil, err
	}
	删除记录
	//err = i.liveReplayRequestsDao.DeleteInRetrieve(ctx, id)
	//if err != nil {
	//	logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao DeleteInRetrieve err: %s", err.Error()))
	//	return nil, err
	//}

	return inRetrieve, nil
}

//获取addr
func GetAddr(ctx context.Context, retrieveUrl string) (interface{}, error) {
	logTag := "service.retrieve.PassInRetrieve"
	resp, err := http.Get(retrieveUrl)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)
	body, err := ioutil.ReadAll(resp.Body)
	var res retrieve.Response
	err = json.Unmarshal([]byte(body), &res)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
		return nil, err
	}
	var addrs []string
	for _, addr := range res.Content.Addrs {
		addrs = append(addrs, addr.Addr)
	}
	//直播回放addr
	addrStr := strings.Join(addrs, "\n")
	return addrStr, nil
}

func SendMsg(ctx context.Context, ticket, userCodes, message string) error {
	logTag := "service.retrieve.SendMsg"
	userType := "workcode"
	sendMsgUrl := fmt.Sprintf("https://api.service.100tal.com/cmpts/msgchl/yach/notice/send?ticket=%s&user_type=%s&userid_list=%s&message=%s",
		ticket, userType, userCodes, message)

	// create request body
	requestBody := bytes.NewBuffer([]byte{})

	// create http request
	req, err := http.NewRequest("POST", sendMsgUrl, requestBody)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve NewRequest err: %s", err.Error()))
		return err
	}

	// set headers
	req.Header.Set("Content-Type", "application/json")

	// create http client
	client := &http.Client{}

	// send request
	resp, err := client.Do(req)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve client.Do err: %s", err.Error()))

		return err
	}

	// read response body
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve ioutil.ReadAll err: %s", err.Error()))
		return err
	}
	logger.Ix(ctx, logTag, "body value:%+v", string(body))
	var result map[string]interface{}
	json.Unmarshal([]byte(string(body)), &result)
	if result["errcode"] != cast.ToFloat64(0) {
		return errors.New(result["errmsg"].(string))
	}
	return nil
}
func GetOssTicket() (string, error) {
	url := "https://api.service.100tal.com/basic/get_ticket?appid=1688527648&appkey=fIEfGcFFEDjc84hX"
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	defer resp.Body.Close()
	response, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var getOssTicketResponse GetOssTicketResponse
	err = json.Unmarshal(response, &getOssTicketResponse)
	if err != nil {
		return "", err
	}
	return getOssTicketResponse.Ticket, nil
}

type GetOssTicketResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Ticket  string `json:"ticket"`
}

func (i *inRetrieveServiceImpl) UnPassInRetrieve(ctx context.Context, id int) (interface{}, error) {
	logTag := "service.retrieve.UnPassInRetrieve"
	inRetrieve, err := i.liveReplayRequestsDao.GetInRetrieve(ctx, id)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao UnPassInRetrieve err: %s", err.Error()))
		return nil, err
	}
	ticket, err := GetOssTicket()
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("GetOssTicket err: %s", err.Error()))
		return nil, err
	}
	mess := fmt.Sprintf("{\"msgtype\":\"text\",\"text\":{\"content\":\" %s您提交的课程回放导出申请未通过\"}}", inRetrieve.Name)
	mess = base64.StdEncoding.EncodeToString([]byte(mess))
	err = SendMsg(ctx, ticket, inRetrieve.Name, mess)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao SendMsg err: %s", err.Error()))
		return nil, err
	}
	删除记录
	//err = i.liveReplayRequestsDao.DeleteInRetrieve(ctx, id)
	//if err != nil {
	//	logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao DeleteInRetrieve err: %s", err.Error()))
	//	return nil, err
	//}
	//保存回档记录
	var archive *retrieve.Archive
	archive = &retrieve.Archive{
		Task:       inRetrieve.Task,
		Initiator:  inRetrieve.Name,
		ReviewTime: time.Now(),
		Status:     0,
	}
	err = i.liveReplayRequestsDao.AddArchive(ctx, archive)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddArchive err: %s", err.Error()))
		return nil, err
	}
	return id, nil
}

//录直播
func (i *inRetrieveServiceImpl) PassInRetrieveRecording(ctx context.Context, inRetrieve *retrieve.InRetrieve) (interface{}, error) {
	logTag := "service.retrieve.PassInRetrieveRecording"
	uid := uuid.New().String()
	//一条消息
	if inRetrieve.RequestType == "FORM" {
		streamName, err := i.GetStreamName(ctx, inRetrieve)

		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao GetStreamName err: %s", err.Error()))
			return nil, err
		}
		//拼接URL
		retrieveUrl := "https://gslbsaturn.xescdn.com/v1/player/vodshow?appid=xes10001&udata=gKaGzoaj4njY&support=4&proto=2&scheme=3&fid=" + cast.ToString(streamName) + "&traceid=d3700c71bfb045e790443bb3c7f4bdd5&agentp=psplayer-ios&agentv=2.8.8&bid=7&uri=" + cast.ToString(streamName) + "&psid=gKaGzoaj4njY&os=iPadOS16.3.1&dev=iPad11%2C6&arch=ARM64E&uid=57968009&cfg=2"
		addrStr, err := GetAddr(ctx, retrieveUrl)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
			return nil, err
		}

		//发送消息
		ticket, err := GetOssTicket()
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("GetOssTicket err: %s", err.Error()))
			return nil, err
		}

		linkR := &retrieve.LinkR{
			UId:     uid,
			EventId: cast.ToInt(inRetrieve.Task),
			Link:    cast.ToString(addrStr),
		}
		err = i.liveReplayRequestsDao.AddLink(ctx, linkR)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddLink err: %s", err.Error()))
			return nil, err
		}
		mess := fmt.Sprintf("{\"msgtype\":\"text\",\"text\":{\"content\":\"您的搜索id为%s,请根据搜索id去网站中查询视频链接\"}}", linkR.UId)
		mess = base64.StdEncoding.EncodeToString([]byte(mess))
		err = SendMsg(ctx, ticket, inRetrieve.Name, mess)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("SendMsg err: %s", err.Error()))
			return nil, err
		}
		fmt.Println(linkR.Link)
		//审核通过,修改审核状态
		inRetrieve.Status = 1
		err = i.liveReplayRequestsDao.UpdateInRetrieve(ctx, inRetrieve)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("UpdateInRetrieve err: %s", err.Error()))
			return nil, err
		}
	} else {
		//多条消息
		var linkR *retrieve.LinkR
		// 打开文件
		resp, err := http.Get(inRetrieve.Task)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("http.Get err: %s", err))
			return nil, err
		}
		defer resp.Body.Close()
		reader := csv.NewReader(resp.Body)
		// 读取并处理CSV文件的每一行
		for {
			record, err := reader.Read()
			if err == io.EOF {
				break
			}
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("csv read err: %s", err.Error()))
				return retrieve.InRetrieve{}, nil
			}
			eventId := record[0]
			inRetrieve.Task = cast.ToString(eventId)
			streamName, err := i.GetStreamName(ctx, inRetrieve)

			retrieveUrl := "https://gslbsaturn.xescdn.com/v1/player/vodshow?appid=xes10001&udata=gKaGzoaj4njY&support=4&proto=2&scheme=3&fid=" + cast.ToString(streamName) + "&traceid=d3700c71bfb045e790443bb3c7f4bdd5&agentp=psplayer-ios&agentv=2.8.8&bid=7&uri=" + cast.ToString(streamName) + "&psid=gKaGzoaj4njY&os=iPadOS16.3.1&dev=iPad11%2C6&arch=ARM64E&uid=57968009&cfg=2"
			addrStr, err := GetAddr(ctx, retrieveUrl)
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("PassInRetrieve err: %s", err.Error()))
				return nil, err
			}
			linkR = &retrieve.LinkR{
				UId:     uid,
				EventId: cast.ToInt(inRetrieve.Task),
				Link:    cast.ToString(addrStr),
			}
			err = i.liveReplayRequestsDao.AddLink(ctx, linkR)
			if err != nil {
				logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddLink err: %s", err.Error()))
				return nil, err
			}

		}
		//发送消息
		ticket, err := GetOssTicket()
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("GetOssTicket err: %s", err.Error()))
			return nil, err
		}
		mess := fmt.Sprintf("{\"msgtype\":\"text\",\"text\":{\"content\":\"您的搜索id为%s,请根据搜索id去网站中查询视频链接\"}}", linkR.UId)
		mess = base64.StdEncoding.EncodeToString([]byte(mess))
		err = SendMsg(ctx, ticket, inRetrieve.Name, mess)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao SendMsg err: %s", err.Error()))
			return nil, err
		}
		//审核通过,修改审核状态
		inRetrieve.Status = 1
		err = i.liveReplayRequestsDao.UpdateInRetrieve(ctx, inRetrieve)
		if err != nil {
			logger.Ex(ctx, logTag, fmt.Sprintf("UpdateInRetrieve err: %s", err.Error()))
			return nil, err
		}
	}

	//保存回档记录
	var archive *retrieve.Archive
	archive = &retrieve.Archive{
		Task:       inRetrieve.Task,
		Initiator:  inRetrieve.Name,
		ReviewTime: time.Now(),
		Status:     1,
	}
	err := i.liveReplayRequestsDao.AddArchive(ctx, archive)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao AddArchive err: %s", err.Error()))
		return nil, err
	}
	return inRetrieve, nil
}

//获取流名
func (i *inRetrieveServiceImpl) GetStreamName(ctx context.Context, inRetrieve *retrieve.InRetrieve) (interface{}, error) {
	logTag := "service.retrieve.GetStreamName"
	lzb, err := i.liveReplayRequestsDao.GetXesVodInfoLzb(ctx, cast.ToInt(inRetrieve.Task))
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao GetXesVodInfoLzb err: %s", err.Error()))
		return nil, err
	}
	streamName, err := i.liveReplayRequestsDao.GetXesLiveVideo(ctx, cast.ToString(lzb.VideoId))
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao GetXesLiveVideo err: %s", err.Error()))
		return nil, err
	}
	return streamName.VideoHlsPath, nil

}

//判断是直播还是录直播
func (i *inRetrieveServiceImpl) PassIn(ctx context.Context, id int) (interface{}, error) {
	logTag := "service.retrieve.PassIn"

	inRetrieve, err := i.liveReplayRequestsDao.GetInRetrieve(ctx, id)
	if err != nil {
		logger.Ex(ctx, logTag, fmt.Sprintf("liveReplayRequestsDao PassInRetrieve err: %s", err.Error()))
		return nil, err
	}
	if inRetrieve.Restatus == 0 {
		i.PassInRetrieve(ctx, inRetrieve)
	} else {
		i.PassInRetrieveRecording(ctx, inRetrieve)

	}
	return inRetrieve, nil
}

dao

package mysqlRepo

import (
	"context"
	"git.100tal.com/wangxiao_go_lib/dbdao"
	logger "git.100tal.com/wangxiao_go_lib/xesLogger"
	"neptune/app/entity/retrieve"
)

type LiveReplayRequestsDao interface {
	AddInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) error
	DeleteInRetrieve(ctx context.Context, id int) error
	ListInRetrieve(ctx context.Context, params *retrieve.SearchParams) ([]*retrieve.InRetrieve, error)
	GetInRetrieve(ctx context.Context, id int) (*retrieve.InRetrieve, error)
	AddArchive(ctx context.Context, archive *retrieve.Archive) error
	AddLink(ctx context.Context, linkR *retrieve.LinkR) error
	GetLinkR(ctx context.Context, uid string) ([]*retrieve.LinkR, error)
	UpdateArchive(ctx context.Context, archive *retrieve.Archive) error
	UpdateInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) error
	GetInRetrieveByStatus(ctx context.Context, status int) (*retrieve.InRetrieve, error)
	GetInRetrieveByNameAndStatus(ctx context.Context, name string, status int) (*retrieve.InRetrieve, error)
	GetXesVodInfoLzb(ctx context.Context, planId int) (*retrieve.XesVodInfoLzb, error)
	GetXesLiveVideo(ctx context.Context, videoId string) (*retrieve.XesLiveVideo, error)
}
type liveReplayRequestsDaoImpl struct {
	Reader       dbdao.DbBaseDao
	Writer       dbdao.DbBaseDao
	ReaderLive   dbdao.DbBaseDao
	ReaderSchool dbdao.DbBaseDao
}

var (
	_                            LiveReplayRequestsDao = (*liveReplayRequestsDaoImpl)(nil)
	DefaultLiveReplayRequestsDao LiveReplayRequestsDao
)

func init() {
	DefaultLiveReplayRequestsDao = NewLiveReplayRequestsDao()
}
func NewLiveReplayRequestsDao() LiveReplayRequestsDao {
	this := new(liveReplayRequestsDaoImpl)
	ctx := context.Background()
	writer := dbdao.GetDbInstanceWithCtx(ctx, "yingyan", "writer")
	this.Writer.UpdateEngine(writer.Engine)
	this.Writer.InitSession(ctx)

	reader := dbdao.GetDbInstanceWithCtx(ctx, "yingyan", "reader")
	this.Reader.UpdateEngine(reader.Engine)
	this.Reader.InitSession(ctx)

	readerLive := dbdao.GetDbInstanceWithCtx(ctx, "liverecording", "reader")
	this.ReaderLive.UpdateEngine(readerLive.Engine)
	this.ReaderLive.InitSession(ctx)

	readerSchool := dbdao.GetDbInstanceWithCtx(ctx, "high_school", "reader")
	this.ReaderSchool.UpdateEngine(readerSchool.Engine)
	this.ReaderSchool.InitSession(ctx)

	return this
}
func (l *liveReplayRequestsDaoImpl) AddInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) error {
	logTag := "liveReplayRequestsDaoImpl.AddInRetrieve"
	session := l.Writer.Engine.Table("livereplayrequests")
	defer session.Close()
	_, err := session.Insert(inRetrieve)
	if err != nil {
		logger.Ex(ctx, logTag, "session.InRetrieve.Insert err:%+v", err)
		return err
	}
	return nil
}
func (l *liveReplayRequestsDaoImpl) UpdateInRetrieve(ctx context.Context, inRetrieve *retrieve.InRetrieve) error {
	logTag := "liveReplayRequestsDaoImpl.UpdateInRetrieve"
	session := l.Writer.Engine.Table("livereplayrequests")
	defer session.Close()

	_, err := session.ID(inRetrieve.Id).Update(inRetrieve)
	if err != nil {
		logger.Ex(ctx, logTag, "session.InRetrieve.Update err:%+v", err)
		return err
	}
	return nil
}
func (l *liveReplayRequestsDaoImpl) DeleteInRetrieve(ctx context.Context, id int) error {
	logTag := "liveReplayRequestsDaoImpl.DeleteInRetrieve"
	session := l.Writer.Engine.Table("livereplayrequests")
	defer session.Close()
	_, err := session.ID(id).Delete(&retrieve.InRetrieve{})
	if err != nil {
		logger.Ex(ctx, logTag, "session.Delete err:%+v", err)
		return err
	}
	return nil
}
func (l *liveReplayRequestsDaoImpl) ListInRetrieve(ctx context.Context, params *retrieve.SearchParams) ([]*retrieve.InRetrieve, error) {
	logTag := "liveReplayRequestsDaoImpl.ListInRetrieve"
	session := l.Reader.Engine.Table("livereplayrequests")
	defer session.Close()
	var inRetrievesList = make([]*retrieve.InRetrieve, 0)
	sql := "select * from " + "livereplayrequests"
	if params.Name != "" && (params.Status == 0 || params.Status == 1) {
		err := session.Where("name = ? AND status = ?", params.Name, params.Status).Find(&inRetrievesList)

		if err != nil {
			logger.Ex(ctx, logTag, "session.list err:%+v", err)
			return nil, err
		}
		session = session.Where("name = ?", params.Name)
	} else if params.Name != "" {
		err := session.Where("name = ?", params.Name).Find(&inRetrievesList)
		if err != nil {
			logger.Ex(ctx, logTag, "session.list err:%+v", err)
			return nil, err
		}
	} else if params.Status == 1 || params.Status == 0 {
		err := session.Where("status = ?", params.Status).Find(&inRetrievesList)
		if err != nil {
			logger.Ex(ctx, logTag, "session.list err:%+v", err)
			return nil, err
		}
	} else {
		err := session.SQL(sql).Find(&inRetrievesList)
		if err != nil {
			logger.Ex(ctx, logTag, "session.list err:%+v", err)
			return nil, err
		}
	}
	return inRetrievesList, nil
}
func (l *liveReplayRequestsDaoImpl) GetInRetrieve(ctx context.Context, id int) (*retrieve.InRetrieve, error) {
	logTag := "liveReplayRequestsDaoImpl.GetInRetrieve"
	session := l.Reader.Engine.Table("livereplayrequests")
	defer session.Close()
	inRetrieve := new(retrieve.InRetrieve)
	_, err := session.Where("id = ?", id).Get(inRetrieve)

	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return inRetrieve, nil
}
func (l *liveReplayRequestsDaoImpl) GetInRetrieveByStatus(ctx context.Context, status int) (*retrieve.InRetrieve, error) {
	logTag := "liveReplayRequestsDaoImpl.GetInRetrieveByStatus"
	session := l.Reader.Engine.Table("livereplayrequests")
	defer session.Close()
	inRetrieve := new(retrieve.InRetrieve)
	_, err := session.Where("status = ?", status).Get(inRetrieve)

	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return inRetrieve, nil
}

func (l *liveReplayRequestsDaoImpl) GetXesVodInfoLzb(ctx context.Context, planId int) (*retrieve.XesVodInfoLzb, error) {
	logTag := "liveReplayRequestsDaoImpl.GetXesVodInfoLzb"
	session := l.ReaderLive.Engine.Table("xes_vod_info_lzb")
	defer session.Close()
	xesVodInfoLzb := new(retrieve.XesVodInfoLzb)
	_, err := session.Where("plan_id = ?", planId).Get(xesVodInfoLzb)
	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return xesVodInfoLzb, nil
}

func (l *liveReplayRequestsDaoImpl) GetXesLiveVideo(ctx context.Context, videoId string) (*retrieve.XesLiveVideo, error) {
	logTag := "liveReplayRequestsDaoImpl.GetXesLiveVideo"
	session := l.ReaderSchool.Engine.Table("xes_live_video")
	defer session.Close()
	xesLiveVideo := new(retrieve.XesLiveVideo)
	_, err := session.Where("video_hls_path = ?", videoId).Get(xesLiveVideo)
	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return xesLiveVideo, nil
}

func (l *liveReplayRequestsDaoImpl) GetInRetrieveByNameAndStatus(ctx context.Context, name string, status int) (*retrieve.InRetrieve, error) {
	logTag := "liveReplayRequestsDaoImpl.GetInRetrieveByNameAndStatus"
	session := l.Reader.Engine.Table("livereplayrequests")
	defer session.Close()
	inRetrieve := new(retrieve.InRetrieve)
	_, err := session.Where("name = ? AND status = ?", name, status).Get(inRetrieve)

	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return inRetrieve, nil
}
func (l *liveReplayRequestsDaoImpl) GetLinkR(ctx context.Context, uid string) ([]*retrieve.LinkR, error) {
	logTag := "liveReplayRequestsDaoImpl.GetLinkR"
	session := l.Reader.Engine.Table("linkr")
	defer session.Close()

	sql := "select * from " + "linkr" + " where uid = ?"
	var linkRList = make([]*retrieve.LinkR, 0)
	err := session.SQL(sql, uid).Find(&linkRList)

	if err != nil {
		logger.Ex(ctx, logTag, "session.list err:%+v", err)
		return nil, err
	}
	return linkRList, nil
}

func (l *liveReplayRequestsDaoImpl) AddArchive(ctx context.Context, archive *retrieve.Archive) error {
	logTag := "liveReplayRequestsDaoImpl.AddArchive"
	session := l.Writer.Engine.Table("exportreversion")
	defer session.Close()
	_, err := session.Insert(archive)
	if err != nil {
		logger.Ex(ctx, logTag, "session.archive.Insert err:%+v", err)
		return err
	}
	return nil
}
func (l *liveReplayRequestsDaoImpl) UpdateArchive(ctx context.Context, archive *retrieve.Archive) error {
	logTag := "liveReplayRequestsDaoImpl.UpdateArchive"
	session := l.Writer.Engine.Table("exportreversion")
	defer session.Close()

	_, err := session.ID(archive.Id).Update(archive)
	if err != nil {
		logger.Ex(ctx, logTag, "session.archive.Update err:%+v", err)
		return err
	}
	return nil
}
func (l *liveReplayRequestsDaoImpl) AddLink(ctx context.Context, linkR *retrieve.LinkR) error {
	logTag := "liveReplayRequestsDaoImpl.AddLink"
	session := l.Writer.Engine.Table("linkr")
	defer session.Close()
	_, err := session.Insert(linkR)
	if err != nil {
		logger.Ex(ctx, logTag, "session.archive.Insert err:%+v", err)
		return err
	}
	return nil
}

entity

package retrieve

import (
	"time"
)

type Retrieve struct {
	Name        string `form:"name"`
	EventId     string `form:"eventId"`
	SpeakerId   string `form:"speakerId"`
	Course      string `form:"course"`
	RequestType string `form:"requestType"`
	ReStatus    string `form:"reStatus"`
	//File        []*multipart.FileHeader `form:"file"`
	File []string `form:"file"`
}
type LinkR struct {
	Id        int    `xorm:"pk autoincr not null comment('主键ID') int(11) 'id'"`
	UId       string `xorm:"not null comment('GUID') varchar(255) 'uid'"`
	EventId   int    `xorm:"not null comment('场次ID') int(11) 'eventid'"`
	SpeakerId int    `xorm:"not null comment('主讲ID') int(11) 'speakerid'"`
	Course    string `xorm:"not null default '' comment('课程环节') varchar(64) 'course'"`
	Link      string `xorm:"not null default '' comment('课程链接') TEXT 'link'"`
}
type InRetrieve struct {
	Id          int    `xorm:"pk autoincr not null comment('主键ID') int(11) 'id'"`
	Name        string `xorm:"not null default '' comment('申请人') varchar(64) 'name'"`
	Task        string `xorm:"not null default '' comment('任务') varchar(255) 'task'"`
	RequestType string `xorm:"not null default '' comment('申请类型') varchar(255) 'request_type'"`
	CreateTime  string `xorm:"not null default '' comment('申请时间') varchar(255) 'create_time'"`
	Restatus    int    `xorm:"not null default 0   comment('申请方式:直播/录直播') int(11) 'restatus'"`
	Status      int    `xorm:"not null default 0   comment('审核状态:有没有审核') int(11) 'status'"`
}
type Archive struct {
	Id         int       `xorm:"pk autoincr not null comment('主键ID') int(11) 'id'"`
	Task       string    `xorm:"not null default '' comment('任务') varchar(255) 'task'"`
	Initiator  string    `xorm:"not null default '' comment('申请人') varchar(64) 'initiator'"`
	ReviewTime time.Time `xorm:"not null default 'CURRENT_TIMESTAMP' comment('审核时间') timestamp 'review_time'"`
	Status     int       `xorm:"not null default 0   comment('审核状态:通过否?') int(11) 'status'"`
}
type Response struct {
	State   int    `json:"state"`
	Message string `json:"message"`
	Content struct {
		Addrs []struct {
			Addr string `json:"addr"`
		} `json:"addrs"`
	} `json:"content"`
}
type SearchParams struct {
	Name   string
	Status int
}
type XesLiveVideo struct {
	Id              int       `xorm:"not null pk autoincr INT(11) 'id'"`
	VideoPlayUrl    string    `xorm:"not null default '' VARCHAR(200) 'video_play_url'"`
	MetadataUrl     string    `xorm:"not null default '' VARCHAR(200) 'metadata_url'"`
	VideoName       string    `xorm:"not null VARCHAR(100) 'video_name'"`
	VideoSource     int       `xorm:"not null TINYINT(4) 'video_source'"`
	VideoModel      int       `xorm:"not null TINYINT(4) 'video_model'"`
	VideoStatus     int       `xorm:"not null default 3 TINYINT(4) 'video_status'"`
	CreateTime      time.Time `xorm:"not null DATETIME 'create_time'"`
	CreateUser      int       `xorm:"not null INT(11) 'create_user'"`
	VideoAuditor    int       `xorm:"not null default 0 INT(11) 'video_auditor'"`
	AuditTime       time.Time `xorm:"not null DATETIME 'audit_time'"`
	AuditorName     string    `xorm:"not null default '' CHAR(32) 'auditor_name'"`
	OriginPlanId    int       `xorm:"not null default 0 INT(11) 'origin_plan_id'"`
	CoursewareId    int       `xorm:"not null default 0 INT(11) 'courseware_id'"`
	Duration        int       `xorm:"not null default 0 INT(11) 'duration'"`
	VideoMd5        string    `xorm:"not null default '' VARCHAR(32) 'video_md5'"`
	ThumbnailUrl    string    `xorm:"not null default '' VARCHAR(200) 'thumbnail_url'"`
	CheckStatus     int       `xorm:"not null default 0 TINYINT(4) 'check_status'"`
	VideoHlsPath    string    `xorm:"not null default '' VARCHAR(200) 'video_hls_path'"`
	InterVerifRet   int       `xorm:"not null default 0 TINYINT(2) 'inter_verif_ret'"`
	GradeId         string    `xorm:"not null default '' VARCHAR(40) 'grade_id'"`
	SubjectId       string    `xorm:"not null default '' VARCHAR(40) 'subject_id'"`
	VideoResolution string    `xorm:"not null default '' VARCHAR(10) 'video_resolution'"`
	BusinesslineId  int       `xorm:"not null default 0 INT(11) 'businessline_id'"`
	OriginVideoId   int       `xorm:"not null default 0 INT(11) 'origin_video_id'"`
	VideoHlsPathSd  string    `xorm:"not null VARCHAR(200) 'video_hls_path_sd'"`
	VideoHlsPathHd  string    `xorm:"not null VARCHAR(200) 'video_hls_path_hd'"`
}
type XesVodInfoLzb struct {
	Id            int       `xorm:"not null pk autoincr INT(11) 'id'"`
	PlanId        int       `xorm:"not null default 0 INT(11) 'plan_id'"`
	VideoPlanId   int       `xorm:"not null default 0 INT(11) 'video_plan_id'"`
	VirtualPlanId int       `xorm:"not null default 0 INT(11) 'virtual_plan_id'"`
	StartTime     int       `xorm:"not null default 0 INT(11) 'starttime'"`
	EndTime       int       `xorm:"not null default 0 INT(11) 'endtime'"`
	CreateTime    time.Time `xorm:"not null default CURRENT_TIMESTAMP DATETIME 'create_time'"`
	ModifyTime    time.Time `xorm:"not null default CURRENT_TIMESTAMP DATETIME 'modify_time'"`
	Pattern       int       `xorm:"not null default 0 TINYINT(2) 'pattern'"`
	State         int       `xorm:"not null default 0 TINYINT(2) 'state'"`
	RoomList      string    `xorm:"TEXT 'room_list'"`
	TeacherId     int       `xorm:"not null default 0 INT(11) 'teacher_id'"`
	CourseId      string    `xorm:"not null default '' VARCHAR(100) 'course_id'"`
	SubjectIds    string    `xorm:"not null default '' VARCHAR(30) 'subject_ids'"`
	VideoId       int       `xorm:"not null default 0 INT(11) 'video_id'"`
}

配置

[App]
name=Neptune

[Server]
mode=release
addr=:19043
; read timeout
readTimeout=5s
; write timeout
writeTimeout=10s
; 连接 idle timeout
idleTimeout=10s
grace=false

[GatewayAuth]
appId=2001066
appKey=8292a2b883fc550a78700e86706e69f1

[log]
LogPath=/opt/logs/xeslog/neptune/neptune.log
Level=DEBUG
RotateSize=2G
RotateHourly=true
;是否启用日志切分
Rotate=true
;日志保留时间,当前配置为6小时
Retention=6

;健康地图日志采样率及日志字段过滤
SkipFields=
SampleRate=

[Registration]
;新增配置,控制是否开启本地服务发现模式
enableLocalDiscovery=true
;rpc调用超时控制
rpcCallTimeout=3s
;addrs=10.90.70.205:2181 10.90.71.147:2181 10.90.71.159:2181
addrs=10.90.73.71:2181 10.90.73.74:2181 10.90.73.89:2181
;Addrs=127.0.0.1:2379 127.0.0.1:2379
group=release
localStorage=/data/live/neptune

[sentinel]
centerHost=10.90.71.67:2379
;服务名称
appName=neptune
;数据统计间隔
pushInterval=1s
;日志级别
logLevel=0
;日志目录
logDir=/home/logs/xeslog/neptune/sentinel/
;是否启用流控功能
enableSentinel=true

[Env]
env=test
appId=xes10001

[LoginCheck]
BackDoorFlag=DEBUG
Debug=on


[Redis]
;pika ip
pika=10.90.29.173:20221
;redis ip
redis=10.90.29.173:2379

[RedisConfig]
;pika 配置
pika.password=TTX4j7JAqWwtf2KJ+
pika.idletimeout=60
pika.poolsize=10
pika.db=0
;redis 配置
redis.password=qvxvfVo5zdYzQ4vntiv+
redis.idletimeout=60
redis.poolsize=100
redis.db=0

[GatewayConf]
appId=2001066
appKey=8292a2b883fc550a78700e86706e69f1

[AdminLiveGateway]
appId=2001066
authSign=8292a2b883fc550a78700e86706e69f1

[Authentication]
appId=2001066
appKey=8292a2b883fc550a78700e86706e69f1

[TencentCloud]
secretId=AKIDCMTWgMrAF7ZmmY6RcZJq9C3wdBlEl6E7
secretKey=lJhGmAJDsLb3JKlzz74pOltnSs45qqb9

[MysqlCluster]
yingyan.writer=study_rw:D7e6e15ed3ed46289e2234377854d921@tcp(10.90.29.171:2306)/yingyan?charset=utf8mb4
yingyan.reader=study_ro:A4b25D7DA7184e3DAe4bDf04d49b3deD@tcp(10.90.29.171:2306)/yingyan?charset=utf8mb4

liverecording.reader=study_rw:D7e6e15ed3ed46289e2234377854d921@tcp(10.90.29.171:2306)/liverecording?charset=utf8mb4
high_school.reader=study_rw:D7e6e15ed3ed46289e2234377854d921@tcp(10.90.29.171:2306)/high_school?charset=utf8mb4

media.writer=root:CkPLS39pwq&ud3ed46289e2234377854d921U@tcp(172.24.78.76:3306)/pt_live?chatset=utf8mb4
media.reader=root:CkPLS39pwq&ud3ed46289e2234377854d921U@tcp(172.24.78.76:3306)/pt_live?chatset=utf8mb4
medialive.writer=root:CkPLS39pwq&ud3ed46289e2234377854d921U@tcp(172.24.78.76:3306)/pt_live?chatset=utf8mb4
medialive.reader=root:CkPLS39pwq&ud3ed46289e2234377854d921U@tcp(172.24.78.76:3306)/pt_live?chatset=utf8mb4

[MysqlConfig]
#是否打开执行sql记录
showSql=true
#是否记录sql执行时间,前提需打开showSql
showExecTime=true
#慢执行日志,前提打开showExecTime,单位500s,默认为0,打全部执行耗时日志
slowslowDuration=500

[Cube]
appId=2001066
appKey=8292a2b883fc550a78700e86706e69f1

app主要代码

cmd运行main

conf配置

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值