-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathinstall_queue.go
351 lines (297 loc) · 9.13 KB
/
install_queue.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
package install
import (
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"crawshaw.io/sqlite"
petname "github.com/dustinkirkland/golang-petname"
"github.com/go-xorm/builder"
"github.com/google/uuid"
"github.com/itchio/butler/butlerd"
"github.com/itchio/butler/butlerd/messages"
"github.com/itchio/butler/cmd/operate"
"github.com/itchio/butler/database/models"
"github.com/itchio/butler/endpoints/downloads"
itchio "github.com/itchio/go-itchio"
"github.com/itchio/wharf/state"
"github.com/pkg/errors"
)
func InstallQueue(rc *butlerd.RequestContext, queueParams butlerd.InstallQueueParams) (*butlerd.InstallQueueResult, error) {
var stagingFolder string
conn := rc.GetConn()
defer rc.PutConn(conn)
var cave *models.Cave
var installLocation *models.InstallLocation
reason := queueParams.Reason
if reason == "" {
reason = butlerd.DownloadReasonInstall
}
var id string
if queueParams.NoCave {
if queueParams.StagingFolder == "" {
return nil, errors.New("With noCave, installFolder must be specified")
}
stagingFolder = queueParams.StagingFolder
id = uuid.New().String()
} else {
if queueParams.CaveID == "" {
if queueParams.InstallLocationID == "" {
return nil, errors.New("When caveId is unspecified, installLocationId must be set")
}
installLocation = models.InstallLocationByID(conn, queueParams.InstallLocationID)
if installLocation == nil {
return nil, errors.Errorf("Install location not found (%s)", queueParams.InstallLocationID)
}
} else {
cave = operate.ValidateCave(rc, queueParams.CaveID)
if queueParams.Game == nil {
queueParams.Game = cave.Game
}
if queueParams.Upload == nil {
queueParams.Upload = cave.Upload
}
if queueParams.Build == nil {
queueParams.Build = cave.Build
}
installLocation = cave.GetInstallLocation(conn)
}
id = generateDownloadID(installLocation.Path)
stagingFolder = installLocation.GetStagingFolder(id)
}
oc, err := operate.LoadContext(rc.Ctx, rc, stagingFolder)
if err != nil {
return nil, errors.WithStack(err)
}
success := false
defer func() {
oc.Release()
if !success {
oc.Retire()
}
}()
consumer := oc.Consumer()
meta := operate.NewMetaSubcontext()
params := meta.Data
params.StagingFolder = stagingFolder
params.Reason = reason
params.IgnoreInstallers = queueParams.IgnoreInstallers
if queueParams.Game == nil {
return nil, errors.New("Missing game in install")
}
params.Game = queueParams.Game
params.Access = operate.AccessForGameID(conn, params.Game.ID)
client := rc.Client(params.Access.APIKey)
consumer.Infof("Queuing install for %s", operate.GameToString(params.Game))
freshCave := false
if queueParams.NoCave {
consumer.Infof("No-cave mode enabled")
if queueParams.InstallFolder == "" {
return nil, errors.New("With noCave is specified, InstallFolder cannot be empty")
}
params.NoCave = true
params.InstallFolder = queueParams.InstallFolder
} else {
if cave == nil {
freshCave = true
cave = &models.Cave{
ID: uuid.New().String(),
InstallLocationID: queueParams.InstallLocationID,
}
consumer.Infof("Generated fresh cave %s", cave.ID)
} else {
consumer.Infof("Re-using cave %s", cave.ID)
}
params.CaveID = cave.ID
if cave.InstallFolderName == "" {
cave.InstallFolderName = makeInstallFolderName(params.Game, consumer)
ensureUniqueFolderName(conn, cave)
}
params.InstallFolder = cave.GetInstallFolder(conn)
params.InstallLocationID = cave.InstallLocationID
params.InstallFolderName = cave.InstallFolderName
}
params.Upload = queueParams.Upload
params.Build = queueParams.Build
if params.Upload == nil {
consumer.Infof("No upload specified, looking for compatible ones...")
uploadsFilterResult, err := operate.GetFilteredUploads(client, params.Game, params.Access.Credentials, consumer)
if err != nil {
return nil, errors.WithStack(err)
}
if len(uploadsFilterResult.Uploads) == 0 {
consumer.Errorf("Didn't find a compatible upload.")
consumer.Errorf("The initial %d uploads were:", len(uploadsFilterResult.InitialUploads))
for _, upload := range uploadsFilterResult.InitialUploads {
operate.LogUpload(consumer, upload, upload.Build)
}
return nil, errors.WithStack(butlerd.CodeNoCompatibleUploads)
}
if len(uploadsFilterResult.Uploads) == 1 {
params.Upload = uploadsFilterResult.Uploads[0]
} else {
r, err := messages.PickUpload.Call(rc, butlerd.PickUploadParams{
Uploads: uploadsFilterResult.Uploads,
})
if err != nil {
return nil, errors.WithStack(err)
}
if r.Index < 0 {
return nil, errors.WithStack(butlerd.CodeOperationAborted)
}
params.Upload = uploadsFilterResult.Uploads[r.Index]
}
if params.Upload.Build != nil {
// if we reach this point, we *just now* queried for an upload,
// so we know the build object is the latest
params.Build = params.Upload.Build
}
} else {
consumer.Infof("Upload specified:")
operate.LogUpload(consumer, params.Upload, params.Build)
}
if freshCave {
dupCond := builder.Eq{
"game_id": params.Game.ID,
"upload_id": params.Upload.ID,
}
if models.MustSelectOne(conn, &models.Cave{}, dupCond) {
consumer.Errorf("Is fresh cave, and found a cave for game %d and upload %d, refusing to proceed.", params.Game.ID, params.Upload.ID)
return nil, errors.Errorf("That upload is already installed!")
}
}
// params.Upload can't be nil by now
if params.Build == nil {
// We were passed an upload but not a build:
// Let's refresh upload info so we can settle on a build we want to install (if any)
listUploadsRes, err := client.ListGameUploads(itchio.ListGameUploadsParams{
GameID: params.Game.ID,
Credentials: params.Access.Credentials,
})
if err != nil {
return nil, errors.WithStack(err)
}
found := true
for _, u := range listUploadsRes.Uploads {
if u.ID == params.Upload.ID {
if u.Build == nil {
consumer.Infof("Upload is not wharf-enabled")
} else {
consumer.Infof("Latest build for upload is %d", u.Build.ID)
// now refresh the build itself, so we get a list of build files
buildRes, err := client.GetBuild(itchio.GetBuildParams{
BuildID: u.Build.ID,
Credentials: params.Access.Credentials,
})
if err != nil {
return nil, errors.WithStack(err)
}
params.Build = buildRes.Build
}
break
}
}
if !found {
consumer.Errorf("Uh oh, we didn't find that upload on the server:")
operate.LogUpload(consumer, params.Upload, nil)
return nil, errors.New("Upload not found")
}
}
oc.Save(meta)
istate := &operate.InstallSubcontextState{}
isub := &operate.InstallSubcontext{
Data: istate,
}
oc.Load(isub)
if queueParams.FastQueue {
params.FastQueue = true
} else {
err = operate.InstallPrepare(oc, meta, isub, false /* disallow downloads */, func(res *operate.InstallPrepareResult) error {
// do muffin
return nil
})
if err != nil {
oc.Retire()
return nil, errors.WithStack(err)
}
}
success = true
res := &butlerd.InstallQueueResult{
ID: id,
CaveID: params.CaveID,
Game: params.Game,
Upload: params.Upload,
Build: params.Build,
InstallFolder: params.InstallFolder,
StagingFolder: params.StagingFolder,
Reason: params.Reason,
InstallLocationID: params.InstallLocationID,
}
if queueParams.QueueDownload {
_, err := downloads.DownloadsQueue(rc, butlerd.DownloadsQueueParams{
Item: res,
})
if err != nil {
return nil, errors.WithStack(err)
}
}
return res, nil
}
func makeInstallFolderName(game *itchio.Game, consumer *state.Consumer) string {
name := makeInstallFolderNameFromSlug(game, consumer)
if name == "" {
name = makeInstallFolderNameFromID(game, consumer)
}
return name
}
var slugRe = regexp.MustCompile(`^\/([^\/]+)`)
func makeInstallFolderNameFromSlug(game *itchio.Game, consumer *state.Consumer) string {
if game.URL == "" {
return ""
}
u, err := url.Parse(game.URL)
if err != nil {
consumer.Warnf("Could not parse game URL (%s): %s", game.URL, err.Error())
return ""
}
matches := slugRe.FindStringSubmatch(u.Path)
if len(matches) == 2 {
return matches[1]
}
return ""
}
func makeInstallFolderNameFromID(game *itchio.Game, consumer *state.Consumer) string {
return fmt.Sprintf("game-%d", game.ID)
}
func ensureUniqueFolderName(conn *sqlite.Conn, cave *models.Cave) {
// Once we reach "Overland 200", it's time to stop
const uniqueMaxTries = 200
base := cave.InstallFolderName
suffix := 2
for i := 0; i < uniqueMaxTries; i++ {
folder := cave.GetInstallFolder(conn)
_, err := os.Stat(folder)
alreadyExists := (err == nil)
if !alreadyExists {
// coolio
return
}
// uh oh, it exists
cave.InstallFolderName = fmt.Sprintf("%s %d", base, suffix)
suffix++
}
cave.InstallFolderName = base
err := errors.Errorf("Could not ensure unique install folder starting with (%s)", cave.GetInstallFolder(conn))
panic(err)
}
func generateDownloadID(basePath string) string {
for tries := 100; tries > 0; tries-- {
id := petname.Generate(3, "-")
_, err := os.Stat(filepath.Join(basePath, id))
if err != nil && os.IsNotExist(err) {
return id
}
}
return uuid.New().String()
}