package internal import ( "fmt" netHttp "net/http" "os" "github.com/debridmediamanager/zurg/internal/config" "github.com/debridmediamanager/zurg/internal/router" "github.com/debridmediamanager/zurg/internal/torrent" "github.com/debridmediamanager/zurg/internal/universal" "github.com/debridmediamanager/zurg/pkg/http" "github.com/debridmediamanager/zurg/pkg/logutil" "github.com/debridmediamanager/zurg/pkg/realdebrid" "github.com/debridmediamanager/zurg/pkg/utils" "github.com/dgraph-io/ristretto" "github.com/julienschmidt/httprouter" "github.com/panjf2000/ants/v2" ) func MainApp(configPath string) { log := logutil.NewLogger() zurglog := log.Named("zurg") config, configErr := config.LoadZurgConfig(configPath, log.Named("config")) if configErr != nil { zurglog.Errorf("Config failed to load: %v", configErr) os.Exit(1) } apiClient := http.NewHTTPClient(config.GetToken(), config.GetRetriesUntilFailed(), config.GetRealDebridTimeout(), config, log.Named("httpclient")) rd := realdebrid.NewRealDebrid(apiClient, log.Named("realdebrid")) p, err := ants.NewPool(config.GetNumOfWorkers() + 1) if err != nil { zurglog.Errorf("Failed to create worker pool: %v", err) os.Exit(1) } defer p.Release() utils.EnsureDirExists("data") cache, err := ristretto.NewCache(&ristretto.Config{ NumCounters: 1e5, // 200,000 to track frequency for 100,000 items. MaxCost: 100 << 20, // maximum cost of cache (100MB). BufferItems: 1 << 10, // number of keys per Get buffer, can be adjusted. }) if err != nil { zurglog.Errorf("Failed to create cache: %v", err) os.Exit(1) } torrentMgr := torrent.NewTorrentManager(config, rd, p, cache, log.Named("manager")) downloadClient := http.NewHTTPClient(config.GetToken(), config.GetRetriesUntilFailed(), 0, config, log.Named("dlclient")) getfile := universal.NewGetFile(downloadClient) handler := httprouter.New() handler.RedirectTrailingSlash = false handler.RedirectFixedPath = true router.ApplyRouteTable(handler, getfile, torrentMgr, config, rd, log.Named("router")) addr := fmt.Sprintf("%s:%s", config.GetHost(), config.GetPort()) zurglog.Infof("Starting server on %s", addr) if err := netHttp.ListenAndServe(addr, handler); err != nil && err != netHttp.ErrServerClosed { zurglog.Errorf("Failed to start server: %v", err) os.Exit(1) } }