aboutsummaryrefslogtreecommitdiffstats
path: root/rust/src/endpoint_handlers.rs
blob: 4567e810a3fdd3a76edb36185b0641eb69613614 (plain)
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! API endpoint handlers
//!
//! This module contains actual implementations of endpoints with rust-style type signatures.
//!
//! The remaining functions here should probably be refactored away. The 'get_release_files' style
//! functions should go in entity_crud (or some new

use crate::database_models::*;
use crate::database_schema::*;
use crate::editing::*;
use crate::editing_crud::{EditgroupCrud, EditorCrud};
use crate::entity_crud::{EntityCrud, ExpandFlags, HideFlags};
use crate::errors::*;
use crate::identifiers::*;
use crate::server::*;
use diesel::prelude::*;
use fatcat_api_spec::models;
use fatcat_api_spec::models::*;

macro_rules! entity_batch_handler {
    ($post_batch_handler:ident, $model:ident) => {
        pub fn $post_batch_handler(
            &self,
            conn: &DbConn,
            entity_list: &[models::$model],
            autoaccept: bool,
            editor_id: FatcatId,
            editgroup_id: Option<FatcatId>,
        ) -> Result<Vec<EntityEdit>> {

            let edit_context = make_edit_context(conn, editor_id, editgroup_id, autoaccept)?;
            edit_context.check(&conn)?;
            let model_list: Vec<&models::$model> = entity_list.iter().map(|e| e).collect();
            let edits = $model::db_create_batch(conn, &edit_context, model_list.as_slice())?;

            if autoaccept {
                let _clr: ChangelogRow = diesel::insert_into(changelog::table)
                    .values((changelog::editgroup_id.eq(edit_context.editgroup_id.to_uuid()),))
                    .get_result(conn)?;
            }
            edits.into_iter().map(|e| e.into_model()).collect()
        }
    }
}

pub fn get_release_files(
    conn: &DbConn,
    ident: FatcatId,
    hide_flags: HideFlags,
) -> Result<Vec<FileEntity>> {
    let rows: Vec<(FileRevRow, FileIdentRow, FileRevReleaseRow)> = file_rev::table
        .inner_join(file_ident::table)
        .inner_join(file_rev_release::table)
        .filter(file_rev_release::target_release_ident_id.eq(&ident.to_uuid()))
        .filter(file_ident::is_live.eq(true))
        .filter(file_ident::redirect_id.is_null())
        .load(conn)?;

    rows.into_iter()
        .map(|(rev, ident, _)| FileEntity::db_from_row(conn, rev, Some(ident), hide_flags))
        .collect()
}

pub fn get_release_filesets(
    conn: &DbConn,
    ident: FatcatId,
    hide_flags: HideFlags,
) -> Result<Vec<FilesetEntity>> {
    let rows: Vec<(FilesetRevRow, FilesetIdentRow, FilesetRevReleaseRow)> = fileset_rev::table
        .inner_join(fileset_ident::table)
        .inner_join(fileset_rev_release::table)
        .filter(fileset_rev_release::target_release_ident_id.eq(&ident.to_uuid()))
        .filter(fileset_ident::is_live.eq(true))
        .filter(fileset_ident::redirect_id.is_null())
        .load(conn)?;

    rows.into_iter()
        .map(|(rev, ident, _)| FilesetEntity::db_from_row(conn, rev, Some(ident), hide_flags))
        .collect()
}

pub fn get_release_webcaptures(
    conn: &DbConn,
    ident: FatcatId,
    hide_flags: HideFlags,
) -> Result<Vec<WebcaptureEntity>> {
    let rows: Vec<(
        WebcaptureRevRow,
        WebcaptureIdentRow,
        WebcaptureRevReleaseRow,
    )> = webcapture_rev::table
        .inner_join(webcapture_ident::table)
        .inner_join(webcapture_rev_release::table)
        .filter(webcapture_rev_release::target_release_ident_id.eq(&ident.to_uuid()))
        .filter(webcapture_ident::is_live.eq(true))
        .filter(webcapture_ident::redirect_id.is_null())
        .load(conn)?;

    rows.into_iter()
        .map(|(rev, ident, _)| WebcaptureEntity::db_from_row(conn, rev, Some(ident), hide_flags))
        .collect()
}

impl Server {
    pub fn lookup_container_handler(
        &self,
        conn: &DbConn,
        issnl: &Option<String>,
        wikidata_qid: &Option<String>,
        expand_flags: ExpandFlags,
        hide_flags: HideFlags,
    ) -> Result<ContainerEntity> {
        let (ident, rev): (ContainerIdentRow, ContainerRevRow) = match (issnl, wikidata_qid) {
            (Some(issnl), None) => {
                check_issn(issnl)?;
                container_ident::table
                    .inner_join(container_rev::table)
                    .filter(container_rev::issnl.eq(&issnl))
                    .filter(container_ident::is_live.eq(true))
                    .filter(container_ident::redirect_id.is_null())
                    .first(conn)?
            }
            (None, Some(wikidata_qid)) => {
                check_wikidata_qid(wikidata_qid)?;
                container_ident::table
                    .inner_join(container_rev::table)
                    .filter(container_rev::wikidata_qid.eq(&wikidata_qid))
                    .filter(container_ident::is_live.eq(true))
                    .filter(container_ident::redirect_id.is_null())
                    .first(conn)?
            }
            _ => {
                return Err(
                    FatcatError::MissingOrMultipleExternalId("in lookup".to_string()).into(),
                );
            }
        };

        let mut entity = ContainerEntity::db_from_row(conn, rev, Some(ident), hide_flags)?;
        entity.db_expand(&conn, expand_flags)?;
        Ok(entity)
    }

    pub fn lookup_creator_handler(
        &self,
        conn: &DbConn,
        orcid: &Option<String>,
        wikidata_qid: &Option<String>,
        expand_flags: ExpandFlags,
        hide_flags: HideFlags,
    ) -> Result<CreatorEntity> {
        let (ident, rev): (CreatorIdentRow, CreatorRevRow) = match (orcid, wikidata_qid) {
            (Some(orcid), None) => {
                check_orcid(orcid)?;
                creator_ident::table
                    .inner_join(creator_rev::table)
                    .filter(creator_rev::orcid.eq(orcid))
                    .filter(creator_ident::is_live.eq(true))
                    .filter(creator_ident::redirect_id.is_null())
                    .first(conn)?
            }
            (None, Some(wikidata_qid)) => {
                check_wikidata_qid(wikidata_qid)?;
                creator_ident::table
                    .inner_join(creator_rev::table)
                    .filter(creator_rev::wikidata_qid.eq(wikidata_qid))
                    .filter(creator_ident::is_live.eq(true))
                    .filter(creator_ident::redirect_id.is_null())
                    .first(conn)?
            }
            _ => {
                return Err(
                    FatcatError::MissingOrMultipleExternalId("in lookup".to_string()).into(),
                );
            }
        };

        let mut entity = CreatorEntity::db_from_row(conn, rev, Some(ident), hide_flags)?;
        entity.db_expand(&conn, expand_flags)?;
        Ok(entity)
    }

    pub fn get_creator_releases_handler(
        &self,
        conn: &DbConn,
        ident: FatcatId,
        hide_flags: HideFlags,
    ) -> Result<Vec<ReleaseEntity>> {
        // TODO: some kind of unique or group-by?
        let rows: Vec<(ReleaseRevRow, ReleaseIdentRow, ReleaseContribRow)> = release_rev::table
            .inner_join(release_ident::table)
            .inner_join(release_contrib::table)
            .filter(release_contrib::creator_ident_id.eq(&ident.to_uuid()))
            .filter(release_ident::is_live.eq(true))
            .filter(release_ident::redirect_id.is_null())
            .load(conn)?;

        // TODO: from_rows, not from_row?
        rows.into_iter()
            .map(|(rev, ident, _)| ReleaseEntity::db_from_row(conn, rev, Some(ident), hide_flags))
            .collect()
    }

    pub fn lookup_file_handler(
        &self,
        conn: &DbConn,
        md5: &Option<String>,
        sha1: &Option<String>,
        sha256: &Option<String>,
        expand_flags: ExpandFlags,
        hide_flags: HideFlags,
    ) -> Result<FileEntity> {
        let (ident, rev): (FileIdentRow, FileRevRow) = match (md5, sha1, sha256) {
            (Some(md5), None, None) => {
                check_md5(md5)?;
                file_ident::table
                    .inner_join(file_rev::table)
                    .filter(file_rev::md5.eq(md5))
                    .filter(file_ident::is_live.eq(true))
                    .filter(file_ident::redirect_id.is_null())
                    .first(conn)?
            }
            (None, Some(sha1), None) => {
                check_sha1(sha1)?;
                file_ident::table
                    .inner_join(file_rev::table)
                    .filter(file_rev::sha1.eq(sha1))
                    .filter(file_ident::is_live.eq(true))
                    .filter(file_ident::redirect_id.is_null())
                    .first(conn)?
            }
            (None, None, Some(sha256)) => {
                check_sha256(sha256)?;
                file_ident::table
                    .inner_join(file_rev::table)
                    .filter(file_rev::sha256.eq(sha256))
                    .filter(file_ident::is_live.eq(true))
                    .filter(file_ident::redirect_id.is_null())
                    .first(conn)?
            }
            _ => {
                return Err(
                    FatcatError::MissingOrMultipleExternalId("in lookup".to_string()).into(),
                );
            }
        };

        let mut entity = FileEntity::db_from_row(conn, rev, Some(ident), hide_flags)?;
        entity.db_expand(&conn, expand_flags)?;
        Ok(entity)
    }

    pub fn lookup_release_handler(
        &self,
        conn: &DbConn,
        doi: &Option<String>,
        wikidata_qid: &Option<String>,
        isbn13: &Option<String>,
        pmid: &Option<String>,
        pmcid: &Option<String>,
        core_id: &Option<String>,
        arxiv_id: &Option<String>,
        jstor_id: &Option<String>,
        expand_flags: ExpandFlags,
        hide_flags: HideFlags,
    ) -> Result<ReleaseEntity> {
        let (ident, rev): (ReleaseIdentRow, ReleaseRevRow) =
            match (doi, wikidata_qid, isbn13, pmid, pmcid, core_id, arxiv_id, jstor_id) {
                (Some(doi), None, None, None, None, None, None, None) => {
                    check_doi(doi)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::doi.eq(doi))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, Some(wikidata_qid), None, None, None, None, None, None) => {
                    check_wikidata_qid(wikidata_qid)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::wikidata_qid.eq(wikidata_qid))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, Some(isbn13), None, None, None, None, None) => {
                    // TODO: check_isbn13(isbn13)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::isbn13.eq(isbn13))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, None, Some(pmid), None, None, None, None) => {
                    check_pmid(pmid)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::pmid.eq(pmid))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, None, None, Some(pmcid), None, None, None) => {
                    check_pmcid(pmcid)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::pmcid.eq(pmcid))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, None, None, None, Some(core_id), None, None) => {
                    // TODO: check_core_id(core_id)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::core_id.eq(core_id))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, None, None, None, None, Some(arxiv_id), None) => {
                    // TODO: check_arxiv_id(arxiv_id)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::arxiv_id.eq(arxiv_id))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                (None, None, None, None, None, None, None, Some(jstor_id)) => {
                    // TODO: check_jstor_id(jstor_id)?;
                    release_ident::table
                        .inner_join(release_rev::table)
                        .filter(release_rev::jstor_id.eq(jstor_id))
                        .filter(release_ident::is_live.eq(true))
                        .filter(release_ident::redirect_id.is_null())
                        .first(conn)?
                }
                _ => {
                    return Err(
                        FatcatError::MissingOrMultipleExternalId("in lookup".to_string()).into(),
                    );
                }
            };

        let mut entity = ReleaseEntity::db_from_row(conn, rev, Some(ident), hide_flags)?;
        entity.db_expand(&conn, expand_flags)?;
        Ok(entity)
    }

    pub fn get_release_files_handler(
        &self,
        conn: &DbConn,
        ident: FatcatId,
        hide_flags: HideFlags,
    ) -> Result<Vec<FileEntity>> {
        get_release_files(conn, ident, hide_flags)
    }

    pub fn get_release_filesets_handler(
        &self,
        conn: &DbConn,
        ident: FatcatId,
        hide_flags: HideFlags,
    ) -> Result<Vec<FilesetEntity>> {
        get_release_filesets(conn, ident, hide_flags)
    }

    pub fn get_release_webcaptures_handler(
        &self,
        conn: &DbConn,
        ident: FatcatId,
        hide_flags: HideFlags,
    ) -> Result<Vec<WebcaptureEntity>> {
        get_release_webcaptures(conn, ident, hide_flags)
    }

    pub fn get_work_releases_handler(
        &self,
        conn: &DbConn,
        ident: FatcatId,
        hide_flags: HideFlags,
    ) -> Result<Vec<ReleaseEntity>> {
        let rows: Vec<(ReleaseRevRow, ReleaseIdentRow)> = release_rev::table
            .inner_join(release_ident::table)
            .filter(release_rev::work_ident_id.eq(&ident.to_uuid()))
            .filter(release_ident::is_live.eq(true))
            .filter(release_ident::redirect_id.is_null())
            .load(conn)?;

        rows.into_iter()
            .map(|(rev, ident)| ReleaseEntity::db_from_row(conn, rev, Some(ident), hide_flags))
            .collect()
    }

    pub fn accept_editgroup_handler(&self, conn: &DbConn, editgroup_id: FatcatId) -> Result<()> {
        accept_editgroup(conn, editgroup_id)?;
        Ok(())
    }

    pub fn create_editgroup_handler(
        &self,
        conn: &DbConn,
        editgroup: models::Editgroup,
    ) -> Result<Editgroup> {
        let row = editgroup.db_create(conn, false)?;
        Ok(row.into_model_partial(None))
    }

    pub fn get_editgroup_handler(
        &self,
        conn: &DbConn,
        editgroup_id: FatcatId,
    ) -> Result<Editgroup> {
        let (eg_row, cl_row) = Editgroup::db_get_with_changelog(conn, editgroup_id)?;
        let mut editgroup = eg_row.into_model_partial(cl_row.map(|cl| cl.id));

        let edits = EditgroupEdits {
            containers: Some(
                container_edit::table
                    .filter(container_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: ContainerEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            creators: Some(
                creator_edit::table
                    .filter(creator_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: CreatorEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            files: Some(
                file_edit::table
                    .filter(file_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: FileEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            filesets: Some(
                fileset_edit::table
                    .filter(fileset_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: FilesetEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            webcaptures: Some(
                webcapture_edit::table
                    .filter(webcapture_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: WebcaptureEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            releases: Some(
                release_edit::table
                    .filter(release_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: ReleaseEditRow| e.into_model().unwrap())
                    .collect(),
            ),
            works: Some(
                work_edit::table
                    .filter(work_edit::editgroup_id.eq(editgroup_id.to_uuid()))
                    .get_results(conn)?
                    .into_iter()
                    .map(|e: WorkEditRow| e.into_model().unwrap())
                    .collect(),
            ),
        };

        editgroup.edits = Some(edits);
        Ok(editgroup)
    }

    pub fn get_editor_handler(&self, conn: &DbConn, editor_id: FatcatId) -> Result<Editor> {
        let row: EditorRow = Editor::db_get(conn, editor_id)?;
        Ok(row.into_model())
    }

    pub fn get_changelog_handler(
        &self,
        conn: &DbConn,
        limit: Option<i64>,
    ) -> Result<Vec<ChangelogEntry>> {
        let limit = limit.unwrap_or(50);

        let changes: Vec<(ChangelogRow, EditgroupRow)> = changelog::table
            .inner_join(editgroup::table)
            .order(changelog::id.desc())
            .limit(limit)
            .load(conn)?;

        let entries = changes
            .into_iter()
            .map(|(cl_row, eg_row)| ChangelogEntry {
                index: cl_row.id,
                editgroup: Some(eg_row.into_model_partial(None)),
                editgroup_id: uuid2fcid(&cl_row.editgroup_id),
                timestamp: chrono::DateTime::from_utc(cl_row.timestamp, chrono::Utc),
            })
            .collect();
        Ok(entries)
    }

    pub fn get_changelog_entry_handler(&self, conn: &DbConn, index: i64) -> Result<ChangelogEntry> {
        let cl_row: ChangelogRow = changelog::table.find(index).first(conn)?;
        let editgroup =
            self.get_editgroup_handler(conn, FatcatId::from_uuid(&cl_row.editgroup_id))?;

        let mut entry = cl_row.into_model();
        entry.editgroup = Some(editgroup);
        Ok(entry)
    }

    /// This helper either finds an Editor model by OIDC parameters (eg, remote domain and
    /// identifier), or creates one and inserts the appropriate auth rows. The semantics are
    /// basically an "upsert" of signup/account-creation.
    /// Returns an editor model and boolean flag indicating whether a new editor was created or
    /// not.
    /// If this function creates an editor, it sets the username to
    /// "{preferred_username}-{provider}"; the intent is for this to be temporary but unique. Might
    /// look like "bnewbold-github", or might look like "895139824-github". This is a hack to make
    /// check/creation idempotent.
    pub fn auth_oidc_handler(&self, conn: &DbConn, params: AuthOidc) -> Result<(Editor, bool)> {
        let existing: Vec<(EditorRow, AuthOidcRow)> = editor::table
            .inner_join(auth_oidc::table)
            .filter(auth_oidc::oidc_sub.eq(params.sub.clone()))
            .filter(auth_oidc::oidc_iss.eq(params.iss.clone()))
            .load(conn)?;

        let (editor_row, created): (EditorRow, bool) = match existing.first() {
            Some((editor, _)) => (editor.clone(), false),
            None => {
                let username = format!("{}-{}", params.preferred_username, params.provider);
                let editor = Editor {
                    editor_id: None,
                    username: username,
                    is_admin: Some(false),
                    is_bot: Some(false),
                    is_active: Some(true),
                };
                let row = editor.db_create(conn)?;
                // create an auth login row so the user can log back in
                diesel::insert_into(auth_oidc::table)
                    .values((
                        auth_oidc::editor_id.eq(row.id),
                        auth_oidc::provider.eq(params.provider),
                        auth_oidc::oidc_iss.eq(params.iss),
                        auth_oidc::oidc_sub.eq(params.sub),
                    ))
                    .execute(conn)?;
                (row, true)
            }
        };

        Ok((editor_row.into_model(), created))
    }

    entity_batch_handler!(create_container_batch_handler, ContainerEntity);
    entity_batch_handler!(create_creator_batch_handler, CreatorEntity);
    entity_batch_handler!(create_file_batch_handler, FileEntity);
    entity_batch_handler!(create_fileset_batch_handler, FilesetEntity);
    entity_batch_handler!(create_webcapture_batch_handler, WebcaptureEntity);
    entity_batch_handler!(create_release_batch_handler, ReleaseEntity);
    entity_batch_handler!(create_work_batch_handler, WorkEntity);
}