Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
nothub committed Feb 13, 2023
1 parent 2d2ff43 commit 448fd2b
Show file tree
Hide file tree
Showing 20 changed files with 273 additions and 461 deletions.
86 changes: 29 additions & 57 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package cmd
import (
"fmt"
"github.com/nothub/mrpack-install/buildinfo"
"github.com/nothub/mrpack-install/http"
"github.com/nothub/mrpack-install/http/download"
modrinth "github.com/nothub/mrpack-install/modrinth/api"
"github.com/nothub/mrpack-install/modrinth/mrpack"
"github.com/nothub/mrpack-install/requester"
"github.com/nothub/mrpack-install/server"
"github.com/nothub/mrpack-install/update"
"github.com/nothub/mrpack-install/util"
Expand Down Expand Up @@ -34,12 +35,12 @@ func init() {
}

type GlobalOpts struct {
Host string
ServerDir string
ServerFile string
Proxy string
DownloadThreads int
RetryTimes int
Host string
ServerDir string
ServerFile string
Proxy string
DlThreads int
DlRetries int
}

func GlobalOptions(cmd *cobra.Command) *GlobalOpts {
Expand Down Expand Up @@ -78,27 +79,26 @@ func GlobalOptions(cmd *cobra.Command) *GlobalOpts {
log.Fatalln(err)
}
if proxy != "" {
// TODO: stop changing the default http client
err := requester.DefaultHttpClient.SetProxy(proxy)
err := http.DefaultClient.SetProxy(proxy)
if err != nil {
log.Fatalln(err)
}
}
opts.Proxy = proxy

downloadThreads, err := cmd.Flags().GetInt("download-threads")
if err != nil || downloadThreads > 64 {
downloadThreads = 8
dlThreads, err := cmd.Flags().GetInt("download-threads")
if err != nil || dlThreads > 64 {
dlThreads = 8
fmt.Println(err)
}
opts.DownloadThreads = downloadThreads
opts.DlThreads = dlThreads

retryTimes, err := cmd.Flags().GetInt("download-retries")
if err != nil {
retryTimes = 3
fmt.Println(err)
}
opts.RetryTimes = retryTimes
opts.DlRetries = retryTimes

return &opts
}
Expand Down Expand Up @@ -147,16 +147,15 @@ var rootCmd = &cobra.Command{
}
index, zipPath := handleArgs(input, version, opts.ServerDir, opts.Host)

fmt.Printf("Installing %q from %q to %q", index.Name, zipPath, opts.ServerDir)

for _, file := range index.Files {
util.AssertPathSafe(file.Path, opts.ServerDir)
}

fmt.Println("Installing:", index.Name)

// download server if not present
if !util.PathIsFile(path.Join(opts.ServerDir, opts.ServerFile)) {
fmt.Println("Server file not present, downloading...\n(Point --server-dir and --server-file flags to an existing server file to skip this step.)")

inst := server.InstallerFromDeps(&index.Deps)
err := inst.Install(opts.ServerDir, opts.ServerFile)
if err != nil {
Expand All @@ -166,26 +165,15 @@ var rootCmd = &cobra.Command{
fmt.Println("Server file already present, proceeding...")
}

// mod downloads
fmt.Printf("Downloading %v dependencies...\n", len(index.Files))
var downloads []*requester.Download
for i := range index.Files {
file := index.Files[i]
if file.Env.Server == modrinth.UnsupportedEnvSupport {
continue
}
downloads = append(downloads, requester.NewDownload(file.Downloads, map[string]string{"sha1": file.Hashes.Sha1}, filepath.Base(file.Path), path.Join(opts.ServerDir, filepath.Dir(file.Path))))
}
downloadPools := requester.NewDownloadPools(requester.DefaultHttpClient, downloads, opts.DownloadThreads, opts.RetryTimes)
downloadPools.Do()
modsUnclean := false
for i := range downloadPools.Downloads {
dl := downloadPools.Downloads[i]
if !dl.Success {
modsUnclean = true
fmt.Println("Dependency downloaded Fail:", dl.FileName)
}
// downloads
downloads := index.ServerDownloads()
fmt.Printf("Downloading %v dependencies...\n", len(downloads))
downloader := download.Downloader{
Downloads: downloads,
Threads: opts.DlThreads,
Retries: opts.DlRetries,
}
downloader.Download(opts.ServerDir)

// overrides
fmt.Println("Extracting overrides...")
Expand All @@ -194,6 +182,7 @@ var rootCmd = &cobra.Command{
log.Fatalln(err)
}

// save state file
packState, err := update.BuildPackState(index, zipPath)
if err != nil {
log.Fatalln(err)
Expand All @@ -203,29 +192,12 @@ var rootCmd = &cobra.Command{
log.Fatalln(err)
}

if modsUnclean {
fmt.Println("There have been problems downloading mods, you probably have to fix some dependency problems manually!")
}
util.RemoveEmptyDirs(opts.ServerDir)

fmt.Println("Done :) Have a nice day ✌️")
fmt.Println("Installation done :) Have a nice day ✌️")
},
}

func readArgs(args []string) (string, string) {
var input string
var version string

if len(args) > 0 {
input = args[0]
}

if len(args) > 1 {
version = args[1]
}

return input, version
}

func handleArgs(input string, version string, serverDir string, host string) (*mrpack.Index, string) {
err := os.MkdirAll(serverDir, 0755)
if err != nil {
Expand All @@ -238,7 +210,7 @@ func handleArgs(input string, version string, serverDir string, host string) (*m

} else if util.IsValidUrl(input) {
fmt.Println("Downloading mrpack file from", input)
file, err := requester.DefaultHttpClient.DownloadFile(input, serverDir, "")
file, err := http.DefaultClient.DownloadFile(input, serverDir, "")
if err != nil {
log.Fatalln(err.Error())
}
Expand Down Expand Up @@ -280,7 +252,7 @@ func handleArgs(input string, version string, serverDir string, host string) (*m
for i := range files {
if strings.HasSuffix(files[i].Filename, ".mrpack") {
fmt.Println("Downloading mrpack file from", files[i].Url)
file, err := requester.DefaultHttpClient.DownloadFile(files[i].Url, serverDir, "")
file, err := http.DefaultClient.DownloadFile(files[i].Url, serverDir, "")
if err != nil {
// TODO: check next file on failure
log.Fatalln(err.Error())
Expand Down
2 changes: 1 addition & 1 deletion cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ var updateCmd = &cobra.Command{

index, zipPath := handleArgs(input, version, opts.ServerDir, opts.Host)

update.Cmd(opts, index, zipPath)
update.Cmd(opts.ServerDir, opts.DlThreads, opts.DlRetries, index, zipPath)
},
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/google/uuid v1.3.0
github.com/nothub/hashutils v0.4.0
github.com/spf13/cobra v1.6.1
golang.org/x/exp v0.0.0-20230212135524-a684f29349b6
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/exp v0.0.0-20230212135524-a684f29349b6 h1:Ic9KukPQ7PegFzHckNiMTQXGgEszA7mY2Fn4ZMtnMbw=
golang.org/x/exp v0.0.0-20230212135524-a684f29349b6/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
73 changes: 73 additions & 0 deletions http/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package http

import (
"fmt"
"github.com/nothub/mrpack-install/buildinfo"
"net"
"net/http"
"net/url"
"runtime/debug"
"time"
)

type Client struct {
c http.Client
ua string
}

var DefaultClient = newHTTPClient()

func newHTTPClient() *Client {
c := &Client{
c: http.Client{},
}

c.c.Transport = newTransport()

c.ua = fmt.Sprintf("%s/%s", "mrpack-install", buildinfo.Version)
info, ok := debug.ReadBuildInfo()
if ok && info.Main.Path != "" {
c.ua = fmt.Sprintf("%s (+https://%s)", c.ua, info.Main.Path)
}

return c
}

func newTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}.DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 20 * time.Second,
ResponseHeaderTimeout: 25 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
}
}

func (c *Client) SetProxy(CustomProxy string) error {
proxy, err := url.Parse(CustomProxy)
if err != nil {
return err
}

transport := newTransport()
transport.Proxy = http.ProxyURL(proxy)
c.c.Transport = transport

// Test proxy
httpUrl := "https://api.modrinth.com/"
response, err := c.c.Get(httpUrl)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return err
}

return nil
}
66 changes: 66 additions & 0 deletions http/download/multi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package download

import (
"crypto"
"github.com/nothub/hashutils/chksum"
"github.com/nothub/hashutils/encoding"
"github.com/nothub/mrpack-install/http"
modrinth "github.com/nothub/mrpack-install/modrinth/api"
"log"
"path"
"path/filepath"
"sync"
)

type Download struct {
Path string
Urls []string
Hashes modrinth.Hashes
}

type Downloader struct {
Downloads []*Download
Threads int
Retries int
}

func (g *Downloader) Download(baseDir string) {
var wg sync.WaitGroup
for i := range g.Downloads {
wg.Add(1)
dl := g.Downloads[i]
go func() {
defer wg.Done()
absPath, _ := filepath.Abs(path.Join(baseDir, dl.Path))
success := false
for _, link := range dl.Urls {
// retry when download failed
for retries := 0; retries < g.Retries; retries++ {
// try download
f, err := http.DefaultClient.DownloadFile(link, path.Dir(absPath), path.Base(absPath))
if err != nil {
log.Printf("Download failed for %s (attempt %v), because: %s\n", dl.Path, retries+1, err.Error())
continue
}
// check hashcode
_, err = chksum.VerifyFile(f, dl.Hashes.Sha512, crypto.SHA512.New(), encoding.Hex)
if err != nil {
log.Printf("Hash check failed for %s (attempt %v), because: %s\n", dl.Path, retries+1, err.Error())
continue
}
// success yay
log.Printf("Downloaded: %s\n", f)
success = true
break
}
if success {
break
}
}
if !success {
log.Printf("Downloaded failed: %s\n", dl.Path)
}
}()
}
wg.Wait()
}
Loading

0 comments on commit 448fd2b

Please sign in to comment.