-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmods.rs
More file actions
379 lines (331 loc) · 11.3 KB
/
Copy pathmods.rs
File metadata and controls
379 lines (331 loc) · 11.3 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
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
377
378
379
use crate::config::AppData;
use crate::database::repository::dependencies;
use crate::database::repository::developers;
use crate::database::repository::incompatibilities;
use crate::database::repository::mod_gd_versions;
use crate::database::repository::mod_links;
use crate::database::repository::mod_tags;
use crate::database::repository::mod_versions;
use crate::database::repository::mods;
use crate::endpoints::ApiError;
use crate::events::mod_feature::ModFeaturedEvent;
use crate::extractors::auth::Auth;
use crate::forum;
use crate::mod_zip;
use crate::types::api::{create_download_link, ApiResponse};
use crate::types::mod_json::ModJson;
use crate::types::models;
use crate::types::models::incompatibility::Incompatibility;
use crate::types::models::mod_entity::{Mod, ModUpdate};
use crate::types::models::mod_gd_version::{GDVersionEnum, VerPlatform};
use crate::types::models::mod_link::ModLinks;
use crate::types::models::mod_version_status::ModVersionStatusEnum;
use crate::webhook::discord::DiscordWebhook;
use actix_web::{get, post, put, web, HttpResponse, Responder};
use serde::Deserialize;
use sqlx::Acquire;
#[derive(Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum IndexSortType {
#[default]
Downloads,
RecentlyUpdated,
RecentlyPublished,
Oldest,
Name,
NameReverse,
}
#[derive(Deserialize)]
pub struct IndexQueryParams {
pub page: Option<i64>,
pub per_page: Option<i64>,
pub query: Option<String>,
#[serde(default)]
pub gd: Option<GDVersionEnum>,
#[serde(default)]
pub platforms: Option<String>,
#[serde(default)]
pub sort: IndexSortType,
pub geode: Option<String>,
pub developer: Option<String>,
pub tags: Option<String>,
pub featured: Option<bool>,
pub status: Option<ModVersionStatusEnum>,
}
#[derive(Deserialize)]
pub struct CreateQueryParams {
download_link: String,
}
#[get("/v1/mods")]
pub async fn index(
data: web::Data<AppData>,
query: web::Query<IndexQueryParams>,
auth: Auth,
) -> Result<impl Responder, ApiError> {
let mut pool = data.db().acquire().await?;
if let Some(s) = query.status {
if s == ModVersionStatusEnum::Rejected {
auth.check_admin()?;
}
}
let mut result = Mod::get_index(&mut pool, query.0).await?;
for i in &mut result.data {
for j in &mut i.versions {
j.modify_metadata(data.app_url(), false);
}
}
Ok(web::Json(ApiResponse {
error: "".into(),
payload: result,
}))
}
#[get("/v1/mods/{id}")]
pub async fn get(
data: web::Data<AppData>,
id: web::Path<String>,
auth: Auth,
) -> Result<impl Responder, ApiError> {
let dev = auth.developer().ok();
let mut pool = data.db().acquire().await?;
let has_extended_permissions = match auth.developer() {
Ok(dev) => dev.admin || developers::has_access_to_mod(dev.id, &id, &mut pool).await?,
_ => false,
};
let mut the_mod: Mod = mods::get_one(&id, true, &mut pool)
.await?
.ok_or(ApiError::NotFound(format!("Mod '{id}' not found")))?;
let version_statuses = match dev {
None => Some(vec![
ModVersionStatusEnum::Accepted,
ModVersionStatusEnum::Pending,
]),
Some(d) => {
if d.admin {
None
} else {
Some(vec![
ModVersionStatusEnum::Accepted,
ModVersionStatusEnum::Pending,
])
}
}
};
the_mod.tags = mod_tags::get_for_mod(&the_mod.id, &mut pool)
.await?
.into_iter()
.map(|t| t.name)
.collect();
the_mod.developers = developers::get_all_for_mod(&the_mod.id, &mut pool).await?;
the_mod.versions =
mod_versions::get_for_mod(&the_mod.id, version_statuses.as_deref(), &mut pool).await?;
the_mod.links = ModLinks::fetch(&the_mod.id, &mut pool).await?;
for i in &mut the_mod.versions {
i.modify_metadata(data.app_url(), has_extended_permissions);
}
Ok(web::Json(ApiResponse {
error: "".into(),
payload: the_mod,
}))
}
#[post("/v1/mods")]
pub async fn create(
data: web::Data<AppData>,
payload: web::Json<CreateQueryParams>,
auth: Auth,
) -> Result<impl Responder, ApiError> {
let dev = auth.developer()?;
let mut pool = data.db().acquire().await?;
let bytes = mod_zip::download_mod(&payload.download_link, data.max_download_mb()).await?;
let json = ModJson::from_zip(bytes, &payload.download_link, false)?;
json.validate()?;
let existing: Option<Mod> = mods::get_one(&json.id, false, &mut pool).await?;
if let Some(m) = &existing {
if !developers::has_access_to_mod(dev.id, &m.id, &mut pool).await? {
return Err(ApiError::Authorization);
}
let versions = mod_versions::get_for_mod(&m.id, None, &mut pool).await?;
if !versions.is_empty() {
return Ok(HttpResponse::Conflict().json(ApiResponse {
error: format!("Mod {} already exists! Submit a new version.", m.id),
payload: "",
}));
}
}
let mut tx = pool.begin().await?;
let mod_already_exists = existing.is_some();
// Wacky stuff
let mut the_mod = if let Some(m) = existing {
m
} else {
mods::create(&json, &mut tx).await?
};
if !mod_already_exists {
mods::assign_owner(&the_mod.id, dev.id, &mut tx).await?;
}
if let Some(tags) = &json.tags {
let tag_list = models::tag::parse_tag_list(tags, &the_mod.id, &mut tx).await?;
mod_tags::update_for_mod(&the_mod.id, &tag_list, &mut tx).await?;
}
if let Some(l) = json.links.clone() {
the_mod.links =
Some(mod_links::upsert(&the_mod.id, l.community, l.homepage, l.source, &mut tx).await?);
}
// First version is always not accepted, even if the developer is verified
let mut version = mod_versions::create_from_json(&json, false, &mut tx).await?;
version.dependencies = Some(
dependencies::create(version.id, &json, &mut tx)
.await?
.into_iter()
.map(|x| x.into_response())
.collect(),
);
version.incompatibilities = Some(
incompatibilities::create(version.id, &json, &mut tx)
.await?
.into_iter()
.map(|x| x.into_response())
.collect(),
);
version.gd = mod_gd_versions::create(version.id, &json, &mut tx).await?;
the_mod.developers = developers::get_all_for_mod(&the_mod.id, &mut tx).await?;
the_mod.versions.insert(0, version);
tx.commit().await?;
for i in &mut the_mod.versions {
i.modify_metadata(data.app_url(), false);
}
forum::discord::create_or_update_thread(
data.discord().clone(),
json.id,
json.version,
"".to_string(),
data.app_url().to_string(),
pool
);
Ok(HttpResponse::Created().json(ApiResponse {
error: "".into(),
payload: the_mod,
}))
}
#[derive(Deserialize)]
struct UpdateQueryParams {
ids: String,
gd: GDVersionEnum,
platform: VerPlatform,
geode: String,
}
#[get("/v1/mods/updates")]
pub async fn get_mod_updates(
data: web::Data<AppData>,
query: web::Query<UpdateQueryParams>,
) -> Result<impl Responder, ApiError> {
let mut pool = data.db().acquire().await?;
if query.platform == VerPlatform::Android || query.platform == VerPlatform::Mac {
return Err(ApiError::BadRequest("Invalid platform. Use android32 / android64 for android and mac-intel / mac-arm for mac".to_string()));
}
let ids = query
.ids
.split(';')
.map(String::from)
.collect::<Vec<String>>();
let geode = semver::Version::parse(&query.geode).map_err(|_| {
ApiError::BadRequest(format!(
"Invalid mod.json geode version semver: {}",
query.geode
))
})?;
let mut result: Vec<ModUpdate> =
Mod::get_updates(&ids, query.platform, &geode, query.gd, &mut pool).await?;
let mut replacements =
Incompatibility::get_supersedes_for(&ids, query.platform, query.gd, &geode, &mut pool)
.await?;
for i in &mut result {
if let Some(replacement) = replacements.get(&i.id) {
let mut clone = replacement.clone();
clone.download_link = create_download_link(data.app_url(), &clone.id, &clone.version);
i.replacement = Some(clone);
replacements.remove_entry(&i.id);
}
i.download_link = create_download_link(data.app_url(), &i.id, &i.version);
}
for i in replacements {
let mut replacement = i.1.clone();
replacement.download_link =
create_download_link(data.app_url(), &replacement.id, &replacement.version);
result.push(ModUpdate {
id: i.0.clone(),
version: "1.0.0".to_string(),
mod_version_id: 0,
download_link: replacement.download_link.clone(),
replacement: Some(replacement),
dependencies: vec![],
incompatibilities: vec![],
});
}
Ok(web::Json(ApiResponse {
error: "".into(),
payload: result,
}))
}
#[get("/v1/mods/{id}/logo")]
pub async fn get_logo(
data: web::Data<AppData>,
path: web::Path<String>,
) -> Result<impl Responder, ApiError> {
use crate::database::repository::*;
let mut pool = data.db().acquire().await?;
let image: Option<Vec<u8>> = mods::get_logo(&path.into_inner(), &mut pool).await?;
match image {
Some(i) => {
if i.is_empty() {
Ok(HttpResponse::NotFound().body(""))
} else {
Ok(HttpResponse::Ok().content_type("image/png").body(i))
}
}
None => Err(ApiError::NotFound("".into())),
}
}
#[derive(Deserialize)]
struct UpdateModPayload {
featured: bool,
}
#[put("/v1/mods/{id}")]
pub async fn update_mod(
data: web::Data<AppData>,
path: web::Path<String>,
payload: web::Json<UpdateModPayload>,
auth: Auth,
) -> Result<impl Responder, ApiError> {
let dev = auth.developer()?;
auth.check_admin()?;
let mut pool = data.db().acquire().await?;
let mut tx = pool.begin().await?;
let id = path.into_inner();
if !mods::exists(&id, &mut tx).await? {
return Err(ApiError::NotFound("Mod not found".into()));
}
let featured = mods::is_featured(&id, &mut tx).await?;
Mod::update_mod(&id, payload.featured, &mut tx).await?;
tx.commit().await?;
if featured != payload.featured {
let item = Mod::get_one(&id, true, &mut pool).await?;
if let Some(item) = item {
if let Some(owner) = developers::get_owner_for_mod(&id, &mut pool).await? {
let first_ver = item.versions.first();
if let Some(ver) = first_ver {
ModFeaturedEvent {
id: item.id,
name: ver.name.clone(),
owner,
admin: dev,
base_url: data.app_url().to_string(),
featured: payload.featured,
}
.to_discord_webhook()
.send(data.webhook_url());
}
}
}
}
Ok(HttpResponse::NoContent())
}