-
Notifications
You must be signed in to change notification settings - Fork 4
/
route.go
249 lines (212 loc) · 6.58 KB
/
route.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
package ioauth_download_task
import (
"bytes"
"encoding/json"
"errors"
"html/template"
"net/http"
"strings"
"time"
"github.com/anti-raid/splashtail/jobs/tasks"
"github.com/anti-raid/splashtail/splashcore/structparser/db"
types "github.com/anti-raid/splashtail/splashcore/types"
"github.com/anti-raid/splashtail/webserver/api"
"github.com/anti-raid/splashtail/webserver/state"
"github.com/go-chi/chi/v5"
docs "github.com/infinitybotlist/eureka/doclib"
"github.com/infinitybotlist/eureka/uapi"
"github.com/jackc/pgx/v5"
"go.uber.org/zap"
)
var (
taskColsArr = db.GetCols(types.Task{})
taskColsStr = strings.Join(taskColsArr, ", ")
)
var downloadTemplate = template.Must(template.New("download").Parse(`<!DOCTYPE html>
<html>
Your download should start in a moment. If not, <a href="{{.URL}}">click here</a>
<script>
if(window.opener) {
window.opener.postMessage("dl:{{.URL}}", {{.Domain}});
} else if(window.parent) {
window.parent.postMessage("dl::{{.URL}}", {{.Domain}});
}
window.location.href = "{{.URL}}";
</script>
</html>
`))
func Docs() *docs.Doc {
return &docs.Doc{
Summary: "Get IOAuth Download Link",
Description: "Gets the download link to a tasks output. Note that this endpoint, like most other IOAuth flows, is *not* meant to be used outside of the bot.",
Params: []docs.Parameter{
{
Name: "id",
Description: "Task ID",
Required: true,
In: "path",
Schema: docs.IdSchema,
},
{
Name: "no_redirect",
Description: "Whether or not to avoid the redirect/text response and merely return the link",
Required: true,
In: "query",
Schema: docs.IdSchema,
},
},
Resp: types.Task{},
}
}
func Route(d uapi.RouteData, r *http.Request) uapi.HttpResponse {
iotok := r.URL.Query().Get("ioauth")
if iotok == "" {
return uapi.HttpResponse{
Status: http.StatusBadRequest,
Json: types.ApiError{
Message: "Missing IOAuth token",
},
}
}
taskId := chi.URLParam(r, "id")
if taskId == "" {
return uapi.HttpResponse{
Status: http.StatusBadRequest,
Json: types.ApiError{Message: "task id is required"},
}
}
// Get the ioauth token
resp, err := state.Rueidis.Do(d.Context, state.Rueidis.B().Get().Key("ioauth:{"+iotok+"}").Build()).AsBytes()
if err != nil {
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{
Message: "Internal Server Error [while checking ioauth token]: " + err.Error(),
},
}
}
if resp == nil {
return uapi.HttpResponse{
Status: http.StatusBadRequest,
Json: types.ApiError{
Message: "Invalid IOAuth token",
},
}
}
var iot types.IOAuthOutput
err = json.Unmarshal(resp, &iot)
if err != nil {
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{
Message: "Internal Server Error [while parsing ioauth token]: " + err.Error(),
},
}
}
// Delete expired tasks first
_, err = state.Pool.Exec(d.Context, "DELETE FROM tasks WHERE created_at + expiry < NOW()")
if err != nil {
state.Logger.Error("Failed to delete expired tasks [db delete]", zap.Error(err))
return uapi.DefaultResponse(http.StatusInternalServerError)
}
row, err := state.Pool.Query(d.Context, "SELECT "+taskColsStr+" FROM tasks WHERE task_id = $1", taskId)
if err != nil {
state.Logger.Error("Failed to fetch task [db fetch]", zap.Error(err))
return uapi.DefaultResponse(http.StatusInternalServerError)
}
task, err := pgx.CollectOneRow(row, pgx.RowToStructByName[types.Task])
if errors.Is(err, pgx.ErrNoRows) {
return uapi.HttpResponse{
Status: http.StatusNotFound,
Json: types.ApiError{Message: "Task not found"},
}
}
if err != nil {
state.Logger.Error("Failed to fetch task [db fetch]", zap.Error(err))
return uapi.DefaultResponse(http.StatusInternalServerError)
}
if task.Output == nil {
return uapi.HttpResponse{
Status: http.StatusNotFound,
Json: types.ApiError{Message: "Task output not found"},
}
}
taskDef, ok := tasks.TaskDefinitionRegistry[task.TaskName]
if !ok {
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{Message: "Task definition not found"},
}
}
if task.TaskForRaw != nil {
task.TaskFor = tasks.ParseTaskFor(*task.TaskForRaw)
if task.TaskFor == nil {
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{Message: "Invalid task.TaskFor. Parsing error occurred"},
}
}
if task.TaskFor.ID == "" || task.TaskFor.TargetType == "" {
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{Message: "Invalid task.TaskFor. Missing ID or TargetType"},
}
}
if task.TaskFor.TargetType == types.TargetTypeUser {
if iot.DiscordUser.ID != task.TaskFor.ID {
return uapi.HttpResponse{
Status: http.StatusForbidden,
Json: types.ApiError{Message: "You are not authorized to fetch this task [TargetType = User]!"},
}
}
} else if task.TaskFor.TargetType == types.TargetTypeServer {
// Check permissions
resp, ok := api.HandlePermissionCheck(iot.DiscordUser.ID, task.TaskFor.ID, taskDef.CorrespondingBotCommand_Download(), []string{})
if !ok {
return resp
}
} else {
return uapi.HttpResponse{
Status: http.StatusNotImplemented,
Json: types.ApiError{Message: "Downloading is not supported for this target type [TargetType = " + task.TaskFor.TargetType + "]"},
}
}
}
// Now get URL
url, err := state.ObjectStorage.GetUrl(d.Context, tasks.GetPathFromOutput(task.TaskID, taskDef, task.Output), task.Output.Filename, 10*time.Minute)
if err != nil {
state.Logger.Error("Failed to get url for task", zap.Error(err))
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{Message: "Failed to get url for task: " + err.Error()},
}
}
if r.URL.Query().Get("no_redirect") == "true" {
return uapi.HttpResponse{
Status: http.StatusOK,
Json: types.ApiError{
Message: url.String(),
},
}
} else {
var buf bytes.Buffer
err := downloadTemplate.Execute(&buf, map[string]any{
"URL": url.String(),
"Domain": state.Config.Sites.Frontend.Parse(),
})
if err != nil {
state.Logger.Error("Failed to execute download template", zap.Error(err))
return uapi.HttpResponse{
Status: http.StatusInternalServerError,
Json: types.ApiError{Message: "Failed to execute download template: " + err.Error()},
}
}
return uapi.HttpResponse{
Status: http.StatusFound,
Bytes: buf.Bytes(),
Headers: map[string]string{
"Content-Type": "text/html, charset=utf-8",
},
}
}
}