-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
376 lines (334 loc) · 8.71 KB
/
main.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package main
import (
"archive/zip"
"bufio"
"fmt"
"github.com/BurntSushi/toml"
"github.com/docopt/docopt-go"
"golang.org/x/net/html"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/user"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
)
var addon_dir string = ""
const base_url string = "https://www.esoui.com"
const search_url string = "/downloads/search.php"
type Config struct {
AddonsPath string
}
type AddOn struct {
title string
description string
depends []string
version string
}
func getDownloadLink(resp http.Response, content string) (string, error) {
z := html.NewTokenizer(resp.Body)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
return "", fmt.Errorf("Download link not found!")
case tt == html.StartTagToken:
t := z.Token()
next_tt := z.Next()
if next_tt != html.TextToken {
continue
}
text := string(z.Text())
if t.Data == "a" {
if text != content {
continue
}
for _, a := range t.Attr {
if a.Key == "href" {
return a.Val, nil
}
}
}
}
}
}
func getCDNDownloadLink(resp http.Response) string {
z := html.NewTokenizer(resp.Body)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
panic("Download link not found!")
case tt == html.StartTagToken:
t := z.Token()
if t.Data == "iframe" {
for _, a := range t.Attr {
if a.Key == "src" {
return a.Val
}
}
}
}
}
}
var dependencyRegexp = regexp.MustCompile(`([^><=]+).*`)
func extractDependency(line string) []string {
// just splitting the line gives us most, but some addon's now support 'semantic versioning'
// so we need to extract that bit out
var out []string
for _, part := range strings.Split(line, " ") {
t := dependencyRegexp.FindStringSubmatch(part)
if len(t) <= 1 {
continue
}
out = append(out, t[1:]...)
}
return out
}
func scanDirectory(path string) (*AddOn, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(f)
re := regexp.MustCompile(`## (.*): (.*)`)
addon := AddOn{}
for scanner.Scan() {
line := scanner.Text()
matches := re.FindStringSubmatch(line)
if matches == nil {
continue
}
switch matches[1] {
case "Title":
addon.title = matches[2]
case "DependsOn":
addon.depends = extractDependency(matches[2])
case "Version":
addon.version = matches[2]
case "Description":
addon.description = matches[2]
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &addon, nil
}
func downloadPlugin(v, addon_dir, base_url, search_url string) error {
var resp *http.Response
var err error
if strings.HasPrefix(v, "http://") || strings.HasPrefix(v, "https://") {
resp, err = http.Get(v)
} else {
// If there is a -, it's for a specific version
parts := strings.Split(v, "-")
v = parts[0]
// Find the plugin from esoui.com
values := url.Values{}
values.Add("x", "0")
values.Add("y", "0")
values.Add("search", v)
resp, err = http.PostForm(fmt.Sprintf("%s/%s", base_url, search_url), values)
if err != nil {
return err
}
}
download_link, err := getDownloadLink(*resp, "Download")
resp.Body.Close()
if err != nil {
fmt.Printf("Failed to find plugin %v; consider just pasting a link\n", v)
if err != nil {
return err
}
}
resp, err = http.Get(fmt.Sprintf("%s/%s", base_url, download_link))
if err != nil {
return err
}
download_link = getCDNDownloadLink(*resp)
resp.Body.Close()
resp, err = http.Get(download_link)
if err != nil {
return err
}
tmpfile, err := ioutil.TempFile("", "addon-zip")
if err != nil {
return err
}
defer os.Remove(tmpfile.Name())
fmt.Printf("Downloading AddOn %s to %v\n", v, tmpfile.Name())
io.Copy(tmpfile, resp.Body)
fmt.Printf("Extracting file...\n")
r, err := zip.OpenReader(tmpfile.Name())
if err != nil {
return err
}
for _, f := range r.File {
fpath := filepath.Join(addon_dir, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, os.ModePerm)
continue
}
err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm)
if err != nil {
return err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
_, err = io.Copy(outFile, rc)
outFile.Close()
rc.Close()
if err != nil {
return err
}
}
return nil
}
func fuzzyMatch(directory string, filename string) (string, error) {
files, err := ioutil.ReadDir(directory)
if err != nil {
return "", fmt.Errorf("error scanning directory %s: %v", directory, err)
}
for _, file := range files {
if strings.ToLower(file.Name()) == strings.ToLower(filename) {
return file.Name(), nil
}
}
return "", fmt.Errorf("failed to find a matching file %s in %s", filename, directory)
}
func updatePlugins(force_install bool) {
fmt.Printf("Walking dir %s\n", addon_dir)
files, err := ioutil.ReadDir(addon_dir)
if err != nil {
panic(err)
}
addons := make(map[string]AddOn)
required := []string{}
for _, file := range files {
fmt.Printf("Looking at %s\n", file.Name())
path := fmt.Sprintf("%s/%s/%s.txt", addon_dir, file.Name(), file.Name())
fuzzyDir, err := fuzzyMatch(addon_dir, file.Name())
if err != nil {
fmt.Printf("Problem finding plugin metadata in %v: %v\n", path, err)
continue
}
path = fmt.Sprintf("%s/%s/", addon_dir, fuzzyDir)
fuzzyFile, err := fuzzyMatch(path, fmt.Sprintf("%s.txt", file.Name()))
if err != nil {
fmt.Printf("Problem finding plugin metadata in %v: %v\n", path, err)
continue
}
path = fmt.Sprintf("%s/%s", path, fuzzyFile)
addon, err := scanDirectory(path)
if err != nil {
fmt.Printf("Problem finding plugin metadata in %v: %v\n", path, err)
continue
}
addons[file.Name()] = *addon
required = append(required, addon.depends...)
}
// Make sure all plugins are installed...
for len(required) > 0 {
v := required[0]
if _, ok := addons[v]; !ok || force_install {
fmt.Printf("Updating plugin: %v\n", v)
err := downloadPlugin(v, addon_dir, base_url, search_url)
if err != nil {
fmt.Printf("Failed to install plugin %v: %v", v, err)
required = required[1:]
continue
}
fmt.Printf("Done!\n")
path := fmt.Sprintf("%s/%s/%s.txt", addon_dir, v, v)
addon, err := scanDirectory(path)
if err != nil {
fmt.Printf("Got error in %v: %v\n", path, err)
continue
}
addons[v] = *addon
required = append(required, addon.depends...)
}
required = required[1:]
}
}
func main() {
usage := `ESO addon manager
Usage:
eso-addons [options] list
eso-addons [options] install (<plugin name>...)
eso-addons [options] update
Options:
-c, --config <path> Config to load; defaults to ~/.eso_addons
The config file is a TOML document which currently supports only
one option; AddonsPath. Thhis should point to the ESO AddOns folder
-p, --path <path> Path to the ESO addons folder.
`
// Create new parser object
arguments, err := docopt.ParseDoc(usage)
if err != nil {
panic(err)
}
user, err := user.Current()
if err != nil {
panic(err)
}
if arguments["--config"] == nil {
arguments["--config"] = path.Join(user.HomeDir, ".eso_addons")
}
if arguments["--path"] == nil {
var conf Config
if runtime.GOOS == "windows" {
arguments["--path"] = path.Join(user.HomeDir, "My Documents", "Elder Scrolls Online", "live", "AddOns")
} else {
arguments["--path"] = path.Join(user.HomeDir, ".steam", "steamapps", "compatdata", "306130", "pfx", "drive_c", "users", "steamuser", "My Documents", "Elder Scrolls Online", "live", "AddOns")
}
if _, err := toml.DecodeFile(arguments["--config"].(string), &conf); err != nil {
fmt.Printf("Warning; failed to find config file %v\n", arguments["--config"].(string))
// No idea; just select the default path
} else if conf.AddonsPath != "" {
arguments["--path"] = conf.AddonsPath
}
}
addon_dir = arguments["--path"].(string)
if arguments["install"].(bool) {
plugin_names := arguments["<plugin name>"].([]string)
for _, plugin_name := range plugin_names {
err := downloadPlugin(plugin_name, addon_dir, base_url, search_url)
if err != nil {
fmt.Printf("Failed to install plugin %v: %v", plugin_name, err)
return
}
updatePlugins(false)
}
fmt.Printf("Done!\n")
} else if arguments["list"].(bool) {
fmt.Printf("Walking dir %s\n", addon_dir)
files, err := ioutil.ReadDir(addon_dir)
if err != nil {
panic(err)
}
for _, file := range files {
path := fmt.Sprintf("%s/%s/%s.txt", addon_dir, file.Name(), file.Name())
addon, err := scanDirectory(path)
if err != nil {
fmt.Printf("Got error in %v: %v\n", path, err)
continue
}
fmt.Printf("%v %v -- %v\n", addon.title, addon.version, addon.description)
}
} else if arguments["update"].(bool) {
updatePlugins(true)
}
}