forked from Vencord/Installer
-
Notifications
You must be signed in to change notification settings - Fork 4
/
github_downloader.go
204 lines (173 loc) · 5.28 KB
/
github_downloader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
* SPDX-License-Identifier: GPL-3.0
* Vencord Installer, a cross platform gui/cli app for installing Vencord
* Copyright (c) 2023 Vendicated and Vencord contributors
*/
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
path "path/filepath"
"strconv"
"strings"
"sync"
)
type GithubRelease struct {
Name string `json:"name"`
TagName string `json:"tag_name"`
Assets []struct {
Name string `json:"name"`
DownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
var ReleaseData GithubRelease
var GithubError error
var GithubDoneChan chan bool
var InstalledHash = "None"
var LatestHash = "Unknown"
var IsDevInstall bool
func GetGithubRelease(url, fallbackUrl string) (*GithubRelease, error) {
fmt.Println("Fetching", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Failed to create Request", err)
return nil, err
}
req.Header.Set("User-Agent", UserAgent)
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("Failed to send Request", err)
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 300 {
isRateLimitedOrBlocked := res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 429
triedFallback := url == fallbackUrl
// GitHub has a very strict 60 req/h rate limit and some (mostly indian) isps block github for some reason.
// If that is the case, try our fallback at https://vencord.dev/releases/project
if isRateLimitedOrBlocked && !triedFallback {
//disable fallback as I am too lazy to do that
return nil,errors.New(res.Status)
//fmt.Printf("Failed to fetch %s (status code %d). Trying fallback url %s\n", url, res.StatusCode, fallbackUrl)
//return GetGithubRelease(fallbackUrl, fallbackUrl)
}
err = errors.New(res.Status)
fmt.Println(url, "returned Non-OK status", GithubError)
return nil, err
}
var data GithubRelease
if err = json.NewDecoder(res.Body).Decode(&data); err != nil {
fmt.Println("Failed to decode GitHub JSON Response", err)
return nil, err
}
return &data, nil
}
func InitGithubDownloader() {
GithubDoneChan = make(chan bool, 1)
IsDevInstall = os.Getenv("VENCORD_DEV_INSTALL") == "1"
fmt.Println("Is Dev Install: ", IsDevInstall)
if IsDevInstall {
GithubDoneChan <- true
return
}
go func() {
// Make sure UI updates once the request either finished or failed
defer func() {
GithubDoneChan <- GithubError == nil
}()
data, err := GetGithubRelease(ReleaseUrl, ReleaseUrlFallback)
if err != nil {
GithubError = err
return
}
ReleaseData = *data
i := strings.LastIndex(data.Name, " ") + 1
LatestHash = data.Name[i:]
fmt.Println("Finished fetching GitHub Data")
fmt.Println("Latest hash is", LatestHash, "Local Install is", Ternary(LatestHash == InstalledHash, "up to date!", "outdated!"))
}()
// Check hash of installed version if exists
f, err := os.Open(Patcher)
if err != nil {
return
}
//goland:noinspection GoUnhandledErrorResult
defer f.Close()
fmt.Println("Found existing Vencord Install. Checking for hash...")
scanner := bufio.NewScanner(f)
if scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "// Vencord ") {
InstalledHash = line[11:]
fmt.Println("Existing hash is", InstalledHash)
} else {
fmt.Println("Didn't find hash")
}
}
}
func installLatestBuilds() (retErr error) {
fmt.Println("Installing latest builds...")
// create an empty package.json file in our files dir.
// without this, node will walk up the file tree and search for a package.json in the
// parent folders. This might lead to issues if the user for example has ~/package.json
// with type: "module" in it
pkgJsonFile := path.Join(FilesDir, "package.json")
err := os.WriteFile(pkgJsonFile, []byte("{}"), 0644)
if err != nil {
fmt.Println("Failed to create", pkgJsonFile, err)
}
var wg sync.WaitGroup
for _, ass := range ReleaseData.Assets {
if strings.HasPrefix(ass.Name, "patcher.js") ||
strings.HasPrefix(ass.Name, "preload.js") ||
strings.HasPrefix(ass.Name, "renderer.js") ||
strings.HasPrefix(ass.Name, "renderer.css") {
wg.Add(1)
ass := ass // Need to do this to not have the variable be overwritten halfway through
go func() {
defer wg.Done()
fmt.Println("Downloading file", ass.Name)
res, err := http.Get(ass.DownloadURL)
if err == nil && res.StatusCode >= 300 {
err = errors.New(res.Status)
}
if err != nil {
fmt.Println("Failed to download", ass.Name+":", err)
retErr = err
return
}
outFile := path.Join(FilesDir, ass.Name)
out, err := os.OpenFile(outFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
fmt.Println("Failed to create", outFile+":", err)
retErr = err
return
}
read, err := io.Copy(out, res.Body)
if err != nil {
fmt.Println("Failed to download to", outFile+":", err)
retErr = err
return
}
contentLength := res.Header.Get("Content-Length")
expected := strconv.FormatInt(read, 10)
if expected != contentLength {
err = errors.New("Unexpected end of input. Content-Length was " + contentLength + ", but I only read " + expected)
fmt.Println(err)
retErr = err
return
}
}()
}
}
wg.Wait()
fmt.Println("Done!")
_ = FixOwnership(FilesDir)
InstalledHash = LatestHash
return
}