瀏覽代碼

新增文件静态服务器,为视频列表功能提供数据源服务

Signed-off-by: allan716 <[email protected]>
allan716 3 年之前
父節點
當前提交
69dc163563

+ 82 - 0
internal/backend/controllers/base/backend_static_file_system.go

@@ -0,0 +1,82 @@
+package base
+
+import (
+	"fmt"
+	"github.com/allanpk716/ChineseSubFinder/internal/pkg/settings"
+	"github.com/gin-gonic/gin"
+	"github.com/sirupsen/logrus"
+	"golang.org/x/net/context"
+	"net/http"
+	"sync"
+	"time"
+)
+
+type StaticFileSystemBackEnd struct {
+	logger  *logrus.Logger
+	running bool
+	srv     *http.Server
+	locker  sync.Mutex
+}
+
+func NewStaticFileSystemBackEnd(logger *logrus.Logger) *StaticFileSystemBackEnd {
+	return &StaticFileSystemBackEnd{
+		logger: logger,
+	}
+}
+
+func (s *StaticFileSystemBackEnd) Start(commonSettings *settings.CommonSettings) {
+	defer s.locker.Unlock()
+	s.locker.Lock()
+
+	if s.running == true {
+		s.logger.Warningln("StaticFileSystemBackEnd is already running")
+		return
+	}
+
+	s.running = true
+
+	router := gin.Default()
+
+	// 添加电影的
+	for i, path := range commonSettings.MoviePaths {
+		router.StaticFS("/movie_dir_"+fmt.Sprintf("%d", i), http.Dir(path))
+	}
+	// 添加连续剧的
+	for i, path := range commonSettings.SeriesPaths {
+		router.StaticFS("/series_dir_"+fmt.Sprintf("%d", i), http.Dir(path))
+	}
+	s.srv = &http.Server{
+		Addr:    ":" + commonSettings.LocalStaticFilePort,
+		Handler: router,
+	}
+	go func() {
+		// service connections
+		s.logger.Infoln("Listening and serving HTTP on port " + commonSettings.LocalStaticFilePort)
+		if err := s.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+			s.logger.Errorln("StaticFileSystemBackEnd listen:", err)
+		}
+	}()
+}
+
+func (s *StaticFileSystemBackEnd) Stop() {
+	defer s.locker.Unlock()
+	s.locker.Lock()
+
+	if s.running == false {
+		s.logger.Warningln("StaticFileSystemBackEnd is not running")
+		return
+	}
+
+	s.running = false
+
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	if err := s.srv.Shutdown(ctx); err != nil {
+		s.logger.Errorln("Server Shutdown:", err)
+	}
+	select {
+	case <-ctx.Done():
+		s.logger.Warningln("timeout of 5 seconds.")
+	}
+	s.logger.Infoln("Static File System Server exiting")
+}

+ 7 - 4
internal/backend/controllers/v1/controller_base.go

@@ -1,6 +1,7 @@
 package v1
 
 import (
+	"github.com/allanpk716/ChineseSubFinder/internal/backend/controllers/base"
 	"github.com/allanpk716/ChineseSubFinder/internal/logic/cron_helper"
 	"github.com/allanpk716/ChineseSubFinder/internal/types/backend"
 	"github.com/gin-gonic/gin"
@@ -9,14 +10,16 @@ import (
 )
 
 type ControllerBase struct {
-	log        *logrus.Logger
-	cronHelper *cron_helper.CronHelper
+	log                     *logrus.Logger
+	cronHelper              *cron_helper.CronHelper
+	StaticFileSystemBackEnd *base.StaticFileSystemBackEnd
 }
 
 func NewControllerBase(log *logrus.Logger, cronHelper *cron_helper.CronHelper) *ControllerBase {
 	return &ControllerBase{
-		log:        log,
-		cronHelper: cronHelper,
+		log:                     log,
+		cronHelper:              cronHelper,
+		StaticFileSystemBackEnd: base.NewStaticFileSystemBackEnd(log),
 	}
 }
 

+ 4 - 0
internal/backend/controllers/v1/settings.go

@@ -48,6 +48,10 @@ func (cb ControllerBase) SettingsHandler(c *gin.Context) {
 			if err != nil {
 				return
 			}
+			// 重新设置本地的静态文件服务器
+			cb.StaticFileSystemBackEnd.Stop()
+			cb.StaticFileSystemBackEnd.Start(cb.cronHelper.Settings.CommonSettings)
+
 			c.JSON(http.StatusOK, backend.ReplyCommon{Message: "Settings Save Success"})
 		}
 	default:

+ 2 - 0
internal/backend/routers/base_router.go

@@ -13,6 +13,8 @@ func InitRouter(fileDownloader *file_downloader.FileDownloader, router *gin.Engi
 
 	cbBase := base.NewControllerBase(fileDownloader)
 	cbV1 := v1.NewControllerBase(fileDownloader.Log, cronHelper)
+	// 静态文件服务器
+	cbV1.StaticFileSystemBackEnd.Start(fileDownloader.Settings.CommonSettings)
 	// 基础的路由
 	router.GET("/system-status", cbBase.SystemStatusHandler)
 

+ 8 - 8
internal/logic/cron_helper/cron_helper.go

@@ -25,7 +25,7 @@ type CronHelper struct {
 	videoScanAndRefreshHelper     *video_scan_and_refresh_helper.VideoScanAndRefreshHelper // 视频扫描和刷新的帮助类
 	cronLock                      sync.Mutex                                               // 锁
 	c                             *cron.Cron                                               // 定时器实例
-	settings                      *settings.Settings                                       // 设置实例
+	Settings                      *settings.Settings                                       // 设置实例
 	log                           *logrus.Logger                                           // 日志实例
 	entryIDScanVideoProcess       cron.EntryID
 	entryIDSupplierCheck          cron.EntryID
@@ -38,14 +38,14 @@ func NewCronHelper(fileDownloader *file_downloader.FileDownloader) *CronHelper {
 	ch := CronHelper{
 		fileDownloader: fileDownloader,
 		log:            fileDownloader.Log,
-		settings:       fileDownloader.Settings,
+		Settings:       fileDownloader.Settings,
 		// 实例化下载队列
 		DownloadQueue: task_queue.NewTaskQueue(fileDownloader.CacheCenter),
 	}
 
 	var err error
 	// 扫描已播放
-	ch.scanPlayedVideoSubInfo, err = scan_played_video_subinfo.NewScanPlayedVideoSubInfo(ch.log, ch.settings)
+	ch.scanPlayedVideoSubInfo, err = scan_played_video_subinfo.NewScanPlayedVideoSubInfo(ch.log, ch.Settings)
 	if err != nil {
 		ch.log.Panicln(err)
 	}
@@ -75,15 +75,15 @@ func (ch *CronHelper) Start(runImmediately bool) {
 	// ----------------------------------------------
 	// 初始化下载者,里面的两个 func 需要使用定时器启动 SupplierCheck QueueDownloader
 	ch.downloader = downloader.NewDownloader(
-		sub_formatter.GetSubFormatter(ch.log, ch.settings.AdvancedSettings.SubNameFormatter),
+		sub_formatter.GetSubFormatter(ch.log, ch.Settings.AdvancedSettings.SubNameFormatter),
 		ch.fileDownloader, ch.DownloadQueue)
 	// ----------------------------------------------
 	// 判断扫描任务的时间间隔是否符合要求,不符合则重写默认值
-	_, err := cron.ParseStandard(ch.settings.CommonSettings.ScanInterval)
+	_, err := cron.ParseStandard(ch.Settings.CommonSettings.ScanInterval)
 	if err != nil {
 		ch.log.Warningln("CommonSettings.ScanInterval format error, after v0.25.x , need reset this at WebUI")
 		// 如果解析错误了,就需要重新赋值默认值过来,然后保存
-		nowSettings := ch.settings
+		nowSettings := ch.Settings
 		nowSettings.CommonSettings.ScanInterval = settings.NewCommonSettings().ScanInterval
 		err = settings.SetFullNewSettings(nowSettings)
 		if err != nil {
@@ -95,7 +95,7 @@ func (ch *CronHelper) Start(runImmediately bool) {
 	ch.c = cron.New(cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger)))
 	// 定时器
 	// 这个暂时无法被取消执行
-	ch.entryIDScanVideoProcess, err = ch.c.AddFunc(ch.settings.CommonSettings.ScanInterval, ch.scanVideoProcessAdd2DownloadQueue)
+	ch.entryIDScanVideoProcess, err = ch.c.AddFunc(ch.Settings.CommonSettings.ScanInterval, ch.scanVideoProcessAdd2DownloadQueue)
 	if err != nil {
 		ch.log.Panicln("CronHelper scanVideoProcessAdd2DownloadQueue, Cron entryID:", ch.entryIDScanVideoProcess, "Error:", err)
 	}
@@ -120,7 +120,7 @@ func (ch *CronHelper) Start(runImmediately bool) {
 
 		ch.log.Infoln("First Time scanVideoProcessAdd2DownloadQueue Start")
 
-		if ch.settings.SpeedDevMode == false {
+		if ch.Settings.SpeedDevMode == false {
 			ch.scanVideoProcessAdd2DownloadQueue()
 		}
 

+ 4 - 1
internal/logic/file_downloader/downloader_hub.go

@@ -20,9 +20,12 @@ type FileDownloader struct {
 }
 
 func NewFileDownloader(cacheCenter *cache_center.CacheCenter) *FileDownloader {
-	return &FileDownloader{Settings: cacheCenter.Settings, Log: cacheCenter.Log,
+
+	f := FileDownloader{Settings: cacheCenter.Settings,
+		Log:         cacheCenter.Log,
 		CacheCenter: cacheCenter,
 	}
+	return &f
 }
 
 func (f *FileDownloader) GetName() string {

+ 2 - 0
internal/pkg/settings/common_settings.go

@@ -7,6 +7,7 @@ type CommonSettings struct {
 	RunScanAtStartUp         bool     `json:"run_scan_at_start_up"`         // 完成引导设置后,下次运行程序就开始扫描
 	MoviePaths               []string `json:"movie_paths"`                  // 电影的目录
 	SeriesPaths              []string `json:"series_paths"`                 // 连续剧的目录
+	LocalStaticFilePort      string   `json:"local_static_file_port"`       // 本地静态文件的端口
 }
 
 func NewCommonSettings() *CommonSettings {
@@ -17,5 +18,6 @@ func NewCommonSettings() *CommonSettings {
 		RunScanAtStartUp:         true,
 		MoviePaths:               make([]string, 0),
 		SeriesPaths:              make([]string, 0),
+		LocalStaticFilePort:      "19037",
 	}
 }