Repository navigation
Expand file tree
/
Copy pathgithub_downloader.go
More file actions
215 lines (182 loc) · 7.03 KB
/
Copy pathgithub_downloader.go
File metadata and controls
215 lines (182 loc) · 7.03 KB
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
205
206
207
208
209
210
211
212
213
214
215
/*
* 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"
"sync/atomic"
)
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) {
Log.Debug("Fetching", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
Log.Error("Failed to create Request", err)
return nil, err
}
req.Header.Set("User-Agent", UserAgent)
res, err := http.DefaultClient.Do(req)
if err != nil {
Log.Error("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 {
Log.Error(fmt.Sprintf("Failed to fetch %s (status code %d). Trying fallback url %s", url, res.StatusCode, fallbackUrl))
return GetGithubRelease(fallbackUrl, fallbackUrl)
}
err = errors.New(res.Status)
Log.Error(url, "returned Non-OK status", GithubError)
return nil, err
}
var data GithubRelease
if err = json.NewDecoder(res.Body).Decode(&data); err != nil {
Log.Error("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"
Log.Debug("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:]
Log.Debug("Finished fetching GitHub Data")
Log.Debug("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()
Log.Debug("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:]
Log.Debug("Existing hash is", InstalledHash)
} else {
Log.Debug("Didn't find hash")
}
}
}
func installLatestBuilds() (retErr error) {
// long error for testing
// return errors.New("According to all known laws of aviation, there is no way a bee should be able to fly. Its wings are too small to get its fat little body off the ground. The bee, of course, flies anyway because bees don't care what humans think is impossible. Yellow, black. Yellow, black. Yellow, black. Yellow, black. Ooh, black and yellow! Let's shake it up a little. Barry! Breakfast is ready! Coming! Hang on a second. Hello? Barry? Adam? Can you believe this is happening? I can't. I'll pick you up. Looking sharp. Use the stairs, Your father paid good money for those. Sorry. I'm excited. Here's the graduate. We're very proud of you, son. A perfect report card, all B's. Very proud. Ma! I got a thing going here. You got lint on your fuzz. Ow! That's me! Wave to us! We'll be in row 118,000. Bye! Barry, I told you, stop flying in the house! Hey, Adam. Hey, Barry. Is that fuzz gel? A little. Special day, graduation. Never thought I'd make it. Three days grade school, three days high school. Those were awkward. Three days college. I'm glad I took a day and hitchhiked around The Hive. You did come back different. Hi, Barry. Artie, growing a mustache? Looks good. Hear about Frankie? Yeah. You going to the funeral? No, I'm not going. Everybody knows, sting someone, you die. Don't waste it on a squirrel. Such a hothead. I guess he could have just gotten out of the way. I love this incorporating an amusement park into our day. That's why we don't need vacations. Boy, quite a bit of pomp under the circumstances. Well, Adam, today we are men. We are! Bee-men. Amen! Hallelujah! Students, faculty, distinguished bees, please welcome Dean Buzzwell.")
Log.Debug("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 {
Log.Warn("Failed to create", pkgJsonFile, err)
}
var wg sync.WaitGroup
var downloadedFiles atomic.Uint64
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()
Log.Debug("Downloading file", ass.Name)
res, err := http.Get(ass.DownloadURL)
if err == nil && res.StatusCode >= 300 {
err = errors.New(res.Status)
}
if err != nil {
Log.Error("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 {
Log.Error("Failed to create", outFile+":", err)
retErr = err
return
}
read, err := io.Copy(out, res.Body)
if err != nil {
Log.Error("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)
Log.Error(err.Error())
retErr = err
return
}
downloadedFiles.Add(1)
}()
}
}
wg.Wait()
if retErr != nil {
return retErr
}
if downloadedFiles.Load() < 4 {
return errors.New("Couldn't find all required files")
}
Log.Debug("Done!")
_ = FixOwnership(FilesDir)
InstalledHash = LatestHash
return
}