-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncproject.go
308 lines (263 loc) · 7.58 KB
/
syncproject.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/cfwidget/cfwidget/curseforge"
"github.com/cfwidget/cfwidget/env"
"github.com/cfwidget/cfwidget/widget"
"github.com/spf13/cast"
"gorm.io/gorm"
"io"
"log"
"net/http"
"net/url"
"regexp"
"runtime/debug"
)
var syncProjectConsumer SyncProjectConsumer
var remoteUrlRegex = regexp.MustCompile("\"/linkout\\?remoteUrl=(?P<Url>\\S*)\"")
var NoProjectError = errors.New("no such project")
var PrivateProjectError = errors.New("project private")
var invalidVersions = []string{"Forge", "Fabric", "Quilt", "Rift"}
func SyncProject(id uint, ctx context.Context) (*widget.Project, error) {
//just directly perform the call, we want this one now
return syncProjectConsumer.Consume(id, ctx)
}
type SyncProjectConsumer struct{}
func (consumer *SyncProjectConsumer) Consume(curseId uint, ctx context.Context) (project *widget.Project, err error) {
db, err := GetDatabase()
if err != nil {
return nil, err
}
db = db.WithContext(ctx)
//let this handle how to mark the job
//if we get an error, it failed
//otherwise, it's fine
defer func() {
e := recover()
if e != nil {
log.Printf("Error syncing project %d: %s\n%s", curseId, e, debug.Stack())
if project != nil {
project.Error = cast.ToString(e)
_ = db.Save(project).Error
}
if t, ok := e.(error); ok {
err = t
} else {
err = errors.New(cast.ToString(e))
}
}
}()
// perform task
if env.GetBool("DEBUG") {
log.Printf("Syncing project %d", curseId)
}
project = &widget.Project{
CurseId: curseId,
}
err = db.First(project).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
panic(err)
}
addon, err := getAddonProperties(curseId, ctx)
if err != nil {
if errors.Is(err, NoProjectError) {
project.Status = 404
} else if errors.Is(err, PrivateProjectError) {
project.Status = 403
} else {
panic(err)
}
err = db.Save(project).Error
if err != nil {
panic(err)
}
return nil, err
}
description, err := getAddonDescription(curseId, ctx)
if err != nil && !errors.Is(err, NoProjectError) && !errors.Is(err, PrivateProjectError) {
panic(err)
}
newProps := &widget.ProjectProperties{
Id: addon.Id,
Title: addon.Name,
Summary: addon.Summary,
Description: description,
Game: curseforge.GetGame(addon.GameId).Slug,
Type: "",
Urls: map[string]string{
"curseforge": addon.Links.WebsiteUrl,
"project": addon.Links.WebsiteUrl,
},
CreatedAt: addon.DateCreated,
Downloads: map[string]uint64{
"monthly": 0,
"total": cast.ToUint64(addon.DownloadCount),
},
License: "",
Donate: "",
Categories: make([]string, 0),
Members: make([]widget.ProjectMember, 0),
Links: make([]string, 0),
Files: make([]widget.ProjectFile, 0),
Versions: map[string][]widget.ProjectFile{},
}
for _, v := range addon.Categories {
newProps.Categories = append(newProps.Categories, v.Name)
}
categories, err := curseforge.GetCategories(addon.GameId, ctx)
newProps.Type = curseforge.GetPrimaryCategoryFor(categories, addon.PrimaryCategoryId).Name
newProps.Thumbnail = addon.Logo.ThumbnailUrl
for _, v := range addon.Authors {
newProps.Members = append(newProps.Members, widget.ProjectMember{
Username: v.Name,
Title: coalesce("Owner"),
Id: v.Id,
})
}
//files!!!!
//we have to call their API to get this stuff
files, err := curseforge.GetFiles(curseId, ctx)
if err != nil && !errors.Is(err, NoProjectError) && !errors.Is(err, PrivateProjectError) {
newProps.Files = project.ParsedProjects.Files
log.Printf("Error getting files: %s\n%s", err, debug.Stack())
}
for _, v := range files {
//if the file is not a "public" file, skip it
if !curseforge.IsAllowedFile(v.FileStatus) {
continue
}
file := widget.ProjectFile{
Id: v.Id,
Url: fmt.Sprintf("%s/files/%d", addon.Links.WebsiteUrl, v.Id),
Display: v.DisplayName,
Name: v.FileName,
Type: curseforge.GetReleaseType(v.ReleaseType),
Version: firstOrEmpty(v.GameVersions),
FileSize: v.FileLength,
Versions: v.GameVersions,
Downloads: v.DownloadCount,
UploadedAt: v.FileDate,
}
for _, g := range v.GameVersions {
if !contains(g, invalidVersions) {
file.Version = g
break
}
}
newProps.Files = append(newProps.Files, file)
for _, ver := range file.Versions {
if contains(ver, invalidVersions) {
continue
}
d, e := newProps.Versions[ver]
if !e {
d = []widget.ProjectFile{file}
} else {
d = append(d, file)
}
newProps.Versions[ver] = d
}
}
d, err := json.Marshal(newProps)
if err != nil {
panic(err)
}
s := string(d)
project.Properties = &s
project.ParsedProjects = newProps
project.Status = http.StatusOK
err = db.Save(project).Error
if err != nil {
panic(err)
}
//now, update authors to indicate this project is associated with them
for _, a := range project.ParsedProjects.Members {
var author widget.Author
err = db.Where("member_id = ?", a.Id).First(&author).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
author.Username = a.Username
author.MemberId = a.Id
temp := "{}"
author.Properties = &temp
_ = db.Create(&author).Error
}
}
exists := false
for _, e := range author.ParsedProjects.Projects {
if e.Id == project.CurseId {
exists = true
break
}
}
if !exists {
author.ParsedProjects.Projects = append(author.ParsedProjects.Projects, widget.AuthorProject{
Id: project.CurseId,
Name: project.ParsedProjects.Title,
})
d, err = json.Marshal(author.ParsedProjects)
if err != nil {
continue
}
s = string(d)
author.Properties = &s
_ = db.Save(&author).Error
}
}
return project, nil
}
func getAddonProperties(id uint, ctx context.Context) (addon curseforge.Addon, err error) {
u := fmt.Sprintf("https://api.curseforge.com/v1/mods/%d", id)
response, err := curseforge.Call(u, ctx)
if err != nil {
return
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return addon, NoProjectError
} else if response.StatusCode == http.StatusForbidden {
return addon, PrivateProjectError
} else if response.StatusCode != 200 {
body, _ := io.ReadAll(response.Body)
return addon, errors.New(fmt.Sprintf("Error from CurseForge properties for id %d: %s (%d)", id, string(body), response.StatusCode))
}
var res curseforge.ProjectResponse
err = json.NewDecoder(response.Body).Decode(&res)
addon = res.Data
return
}
func getAddonDescription(id uint, ctx context.Context) (description string, err error) {
requestUrl := fmt.Sprintf("https://api.curseforge.com/v1/mods/%d/description", id)
response, err := curseforge.Call(requestUrl, ctx)
if err != nil {
return
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return "", NoProjectError
} else if response.StatusCode == http.StatusForbidden {
return "", PrivateProjectError
} else if response.StatusCode != http.StatusOK {
body, _ := io.ReadAll(response.Body)
return description, errors.New(fmt.Sprintf("Error from CurseForge description for id %d: %s (%d)", id, string(body), response.StatusCode))
}
var data curseforge.DescriptionResponse
err = json.NewDecoder(response.Body).Decode(&data)
if err != nil {
return
}
description = remoteUrlRegex.ReplaceAllStringFunc(data.Data, func(match string) string {
urls := remoteUrlRegex.FindStringSubmatch(match)
if len(urls) < 2 {
return match
}
result := urls[1]
result, err = url.QueryUnescape(result)
result, err = url.QueryUnescape(result)
return "\"" + result + "\""
})
return
}