docbox-http 0.9.1

Docbox HTTP layer, routes, types, and middleware
Documentation
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
//! File related endpoints

use crate::{
    error::{DynHttpError, HttpCommonError, HttpErrorResponse, HttpResult, HttpStatusResult},
    extensions::max_file_size::MaxFileSizeBytes,
    middleware::{
        action_user::{ActionUser, UserParams},
        tenant::{TenantDb, TenantEvents, TenantParams, TenantSearch, TenantStorage},
    },
    models::{
        document_box::DocumentBoxScope,
        file::{
            BinaryResponse, CreatePresignedRequest, FileResponse, FileUploadResponse,
            GetPresignedRequest, HttpFileError, PresignedDownloadResponse, PresignedStatusResponse,
            PresignedUploadResponse, RawFileQuery, UpdateFileRequest, UploadFileRequest,
            UploadTaskResponse, UploadedFile,
        },
        folder::HttpFolderError,
    },
};
use axum::{
    Extension, Json,
    body::Body,
    extract::{Path, Query},
    http::{HeaderValue, Response, StatusCode, header},
};
use axum_typed_multipart::TypedMultipart;
use axum_valid::Garde;
use docbox_core::{
    database::models::{
        edit_history::EditHistory,
        file::{File, FileId, FileWithExtra},
        folder::Folder,
        generated_file::{GeneratedFile, GeneratedFileType},
        presigned_upload_task::{PresignedTaskStatus, PresignedUploadTask, PresignedUploadTaskId},
        tasks::TaskStatus,
        user::User,
    },
    files::{
        delete_file::delete_file,
        update_file::{UpdateFile, UpdateFileError},
        upload_file::{UploadFile, UploadedFileData, upload_file},
        upload_file_presigned::{CreatePresigned, create_presigned_upload},
    },
    processing::{ProcessingConfig, ProcessingLayer},
    search::models::{FileSearchRequest, FileSearchResultResponse},
    tasks::background_task::background_task,
    utils::file::get_file_name_ext,
};
use mime::Mime;
use std::{str::FromStr, time::Duration};
use tracing::Instrument;

pub const FILE_TAG: &str = "File";

/// Upload file
///
/// Uploads a new document to the provided document box folder.
///
/// If the asynchronous option is specified a task will be returned
/// otherwise the completed file upload will be returned directly
///
/// In a browser environment its recommend to use the async option to
/// prevent running into browser timeouts if the processing takes too long.
///
/// In a reverse proxy + browser situation prefer using the presigned file upload
/// endpoint otherwise browsers may timeout while your server transfers the file
///
/// Synchronous uploads return [UploadedFile]
/// Asynchronous uploads return [UploadTaskResponse]
///
/// This endpoint is not available in the serverless version of docbox, instead use
/// the presigned endpoint /box/{scope}/file/presigned
///
#[utoipa::path(
    post,
    operation_id = "file_upload",
    tag = FILE_TAG,
    path = "/box/{scope}/file",
    responses(
        (status = 200, description = "Upload or task created successfully", body = FileUploadResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 404, description = "Target folder could not be found", body = HttpErrorResponse),
        (status = 409, description = "Fixed ID is already in use", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    request_body(content = UploadFileRequest, description = "Multipart upload", content_type = "multipart/form-data"),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope to create the file within"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope))]
#[allow(clippy::too_many_arguments)]
pub async fn upload(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantStorage(storage): TenantStorage,
    TenantEvents(events): TenantEvents,
    //
    Extension(processing): Extension<ProcessingLayer>,
    //
    Path(DocumentBoxScope(scope)): Path<DocumentBoxScope>,
    Garde(TypedMultipart(req)): Garde<TypedMultipart<UploadFileRequest>>,
) -> HttpResult<FileUploadResponse> {
    let folder = Folder::find_by_id(&db, &scope, req.folder_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFolderError::UnknownTargetFolder)?;

    if let Some(fixed_id) = req.fixed_id
        && File::find(&db, &scope, fixed_id)
            .await
            .map_err(|error| {
                tracing::error!(?error, "failed to check for duplicate files");
                HttpCommonError::ServerError
            })?
            .is_some()
    {
        return Err(DynHttpError::from(HttpFileError::FileIdInUse));
    }

    let content_type = req.mime.or(req.file.metadata.content_type);

    let mut mime = match content_type {
        Some(value) => Mime::from_str(&value).map_err(|_| HttpFileError::InvalidMimeType)?,
        // Fallback to default mime type when none is provided
        None => mime::APPLICATION_OCTET_STREAM,
    };

    // Attempt to guess the file mime type when application/octet-stream is specified
    // (Likely from old browsers)
    if mime == mime::APPLICATION_OCTET_STREAM
        && req.disable_mime_sniffing.is_none_or(|value| !value)
    {
        let guessed_mime = get_file_name_ext(&req.name).and_then(|ext| {
            let guesses = mime_guess::from_ext(&ext);
            guesses.first()
        });

        if let Some(guessed_mime) = guessed_mime {
            mime = guessed_mime
        }
    }

    // Parse task processing config
    let processing_config: Option<ProcessingConfig> = match &req.processing_config {
        Some(value) => match serde_json::from_str(value) {
            Ok(value) => value,
            Err(error) => {
                tracing::error!(?error, "failed to deserialize processing config");
                None
            }
        },
        None => None,
    };

    // Update stored editing user data
    let created_by = action_user.store_user(&db).await?;

    // Create the upload configuration
    let upload = UploadFile {
        fixed_id: req.fixed_id,
        parent_id: req.parent_id,
        folder_id: folder.id,
        document_box: folder.document_box.clone(),
        name: req.name,
        mime,
        file_bytes: req.file.contents,
        created_by: created_by.as_ref().map(|value| value.id.to_string()),
        file_key: None,
        processing_config,
    };

    // Handle synchronous request waiting for the task to complete before responding
    if !req.asynchronous.unwrap_or_default() {
        let data = upload_file(&db, &search, &storage, &processing, &events, upload)
            .await
            .map_err(|error| {
                tracing::error!(?error, "failed to upload file");
                HttpFileError::UploadFileError(error)
            })?;
        let result = map_uploaded_file(data, &created_by);
        return Ok(Json(FileUploadResponse::Sync(Box::new(result))));
    }

    let span = tracing::Span::current();

    // Spawn background task
    let (task_id, created_at) = background_task(
        db.clone(),
        scope.clone(),
        async move {
            let result = upload_file(&db, &search, &storage, &processing, &events, upload)
                .await
                .map_err(|error| {
                    tracing::error!(?error, "failed to upload file");
                    DynHttpError::from(HttpFileError::UploadFileError(error))
                })
                // Map the response into the desired format
                .map(|data| map_uploaded_file(data, &created_by))
                // Serialize the response for storage
                .and_then(|value| {
                    serde_json::to_value(&value).map_err(|error| {
                        tracing::error!(?error, "failed to serialize upload task outcome");
                        DynHttpError::from(HttpCommonError::ServerError)
                    })
                });

            match result {
                Ok(value) => (TaskStatus::Completed, value),
                Err(error) => (
                    TaskStatus::Failed,
                    serde_json::json!({ "error": error.to_string() }),
                ),
            }
        }
        // Ensure the logging span is passed onto the background task so that
        // logging context continues
        .instrument(span),
    )
    .await
    .map_err(|error| {
        tracing::error!(?error, "failed to create background task");
        HttpCommonError::ServerError
    })?;

    Ok(Json(FileUploadResponse::Async(UploadTaskResponse {
        task_id,
        created_at,
    })))
}

/// Map a [UploadedFileData] output from the core layer into the [UploadedFile]
/// HTTP response format
fn map_uploaded_file(data: UploadedFileData, created_by: &Option<User>) -> UploadedFile {
    let UploadedFileData {
        file,
        generated,
        additional_files,
    } = data;

    UploadedFile {
        file: FileWithExtra {
            file,
            created_by: created_by.clone(),
            last_modified_at: None,
            last_modified_by: None,
        },
        generated,

        // Map created file children
        additional_files: additional_files
            .into_iter()
            .map(|data| map_uploaded_file(data, created_by))
            .collect(),
    }
}

/// Create presigned file upload
///
/// Creates a new "presigned" upload, where the file is uploaded
/// directly to storage and processed asynchronously.
///
/// Use the task ID from the response to poll the file processing
/// progress.
#[utoipa::path(
    post,
    operation_id = "file_create_presigned",
    tag = FILE_TAG,
    path = "/box/{scope}/file/presigned",
    responses(
        (status = 201, description = "Created presigned upload successfully", body = PresignedUploadResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 404, description = "Target folder could not be found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope to create the file within"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, ?req))]
pub async fn create_presigned(
    action_user: ActionUser,
    Extension(MaxFileSizeBytes(max_file_size)): Extension<MaxFileSizeBytes>,
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path(DocumentBoxScope(scope)): Path<DocumentBoxScope>,
    Garde(Json(req)): Garde<Json<CreatePresignedRequest>>,
) -> Result<(StatusCode, Json<PresignedUploadResponse>), DynHttpError> {
    if req.size > max_file_size {
        return Err(HttpFileError::FileTooLarge(req.size, max_file_size).into());
    }

    let folder = Folder::find_by_id(&db, &scope, req.folder_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query folder");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFolderError::UnknownTargetFolder)?;

    // Update stored editing user data
    let created_by = action_user.store_user(&db).await?;

    let mut mime = req.mime.unwrap_or(mime::APPLICATION_OCTET_STREAM);

    // Attempt to guess the file mime type when application/octet-stream is specified
    // (Likely from old browsers)
    if mime == mime::APPLICATION_OCTET_STREAM
        && req.disable_mime_sniffing.is_none_or(|value| !value)
    {
        let guessed_mime = get_file_name_ext(&req.name).and_then(|ext| {
            let guesses = mime_guess::from_ext(&ext);
            guesses.first()
        });

        if let Some(guessed_mime) = guessed_mime {
            mime = guessed_mime
        }
    }

    let response = create_presigned_upload(
        &db,
        &storage,
        CreatePresigned {
            name: req.name,
            document_box: scope,
            folder,
            size: req.size,
            mime,
            created_by: created_by.map(|user| user.id),
            parent_id: req.parent_id,
            processing_config: req.processing_config,
        },
    )
    .await
    .map_err(|error| {
        tracing::error!(?error, "failed to create presigned upload");
        HttpCommonError::ServerError
    })?;

    Ok((
        StatusCode::CREATED,
        Json(PresignedUploadResponse {
            task_id: response.task_id,
            method: response.method,
            uri: response.uri,
            headers: response.headers,
        }),
    ))
}

/// Get presigned file upload
///
/// Gets the current state of a presigned upload either pending or
/// complete, when complete the uploaded file and generated files
/// are returned
#[utoipa::path(
    get,
    operation_id = "file_get_presigned",
    tag = FILE_TAG,
    path = "/box/{scope}/file/presigned/{task_id}",
    responses(
        (status = 200, description = "Obtained presigned upload successfully", body = PresignedStatusResponse),
        (status = 404, description = "Presigned upload not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("task_id" = Uuid, Path, description = "ID of the task to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %task_id))]
pub async fn get_presigned(
    TenantDb(db): TenantDb,
    Path((scope, task_id)): Path<(DocumentBoxScope, PresignedUploadTaskId)>,
) -> HttpResult<PresignedStatusResponse> {
    let DocumentBoxScope(scope) = scope;

    let task = PresignedUploadTask::find(&db, &scope, task_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query presigned upload");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownTask)?;

    let file_id = match task.status {
        PresignedTaskStatus::Pending => return Ok(Json(PresignedStatusResponse::Pending)),
        PresignedTaskStatus::Completed { file_id } => file_id,
        PresignedTaskStatus::Failed { error } => {
            return Ok(Json(PresignedStatusResponse::Failed { error }));
        }
    };

    let file = File::find_with_extra(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let generated = GeneratedFile::find_all(&db, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query generated files");
            HttpCommonError::ServerError
        })?;

    Ok(Json(PresignedStatusResponse::Complete { file, generated }))
}

/// Get file by ID
///
/// Gets a specific file details, metadata and associated
/// generated files
#[utoipa::path(
    get,
    operation_id = "file_get",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}",
    responses(
        (status = 200, description = "Obtained file successfully", body = FileResponse),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id))]
pub async fn get(
    TenantDb(db): TenantDb,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
) -> HttpResult<FileResponse> {
    let DocumentBoxScope(scope) = scope;
    let file = File::find_with_extra(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let generated = GeneratedFile::find_all(&db, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query generated files");
            HttpCommonError::ServerError
        })?;

    Ok(Json(FileResponse { file, generated }))
}

/// Get file children
///
/// Get all children for the provided file, this is things like
/// attachments for processed emails
#[utoipa::path(
    get,
    operation_id = "file_get_children",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/children",
    responses(
        (status = 200, description = "Obtained children successfully", body = [FileWithExtra]),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id))]
pub async fn get_children(
    TenantDb(db): TenantDb,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
) -> HttpResult<Vec<FileWithExtra>> {
    let DocumentBoxScope(scope) = scope;

    // Request the file first to ensure scoping rules
    _ = File::find_with_extra(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let files = File::find_by_parent_file_with_extra(&db, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file children");
            HttpCommonError::ServerError
        })?;

    Ok(Json(files))
}

/// Get file edit history
///
/// Gets the edit history for the provided file
#[utoipa::path(
    get,
    operation_id = "file_edit_history",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/edit-history",
    responses(
        (status = 200, description = "Obtained edit-history successfully", body = [EditHistory]),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id))]
pub async fn get_edit_history(
    TenantDb(db): TenantDb,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
) -> HttpResult<Vec<EditHistory>> {
    let DocumentBoxScope(scope) = scope;

    _ = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let edit_history = EditHistory::all_by_file(&db, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file history");
            HttpCommonError::ServerError
        })?;

    Ok(Json(edit_history))
}

/// Update file
///
/// Updates a file, can be a name change, a folder move, or both
#[utoipa::path(
    put,
    operation_id = "file_update",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}",
    responses(
        (status = 200, description = "Obtained edit-history successfully", body = [EditHistory]),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, ?req))]
pub async fn update(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
    Garde(Json(req)): Garde<Json<UpdateFileRequest>>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let file = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    // Update stored editing user data
    let user = action_user.store_user(&db).await?;
    let user_id = user.as_ref().map(|value| value.id.to_string());

    let update = UpdateFile {
        folder_id: req.folder_id,
        name: req.name,
        pinned: req.pinned,
    };

    docbox_core::files::update_file::update_file(&db, &search, &scope, file, user_id, update)
        .await
        .map_err(|error| match error {
            UpdateFileError::UnknownTargetFolder => {
                DynHttpError::from(HttpFolderError::UnknownTargetFolder)
            }
            _ => DynHttpError::from(HttpCommonError::ServerError),
        })?;

    Ok(StatusCode::OK)
}

/// Get file raw
///
/// Requests the raw contents of a file, this is used for downloading
/// the file or viewing it in the browser or simply requesting its content
#[utoipa::path(
    get,
    operation_id = "file_get_raw",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/raw",
    responses(
        (status = 200, description = "Obtained raw file successfully", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, ?query))]
pub async fn get_raw(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
    Query(query): Query<RawFileQuery>,
) -> Result<Response<Body>, DynHttpError> {
    let DocumentBoxScope(scope) = scope;

    let file = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let byte_stream = storage.get_file(&file.file_key).await.map_err(|error| {
        tracing::error!(?error, "failed to get file from storage");
        HttpCommonError::ServerError
    })?;

    let body = axum::body::Body::from_stream(byte_stream);

    let ty = if query.download {
        "attachment"
    } else {
        "inline"
    };

    let disposition = format!("{};filename=\"{}\"", ty, file.name);

    let csp = match mime::Mime::from_str(&file.mime) {
        // Images are served with a strict image only content security policy
        Ok(mime) if mime.type_() == mime::IMAGE => {
            "default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;"
        }
        // Default policy
        _ => "script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'",
    };

    Ok(Response::builder()
        .header(header::CONTENT_TYPE, file.mime)
        .header(header::CONTENT_SECURITY_POLICY, csp)
        .header(
            header::CONTENT_DISPOSITION,
            HeaderValue::from_str(&disposition)?,
        )
        .body(body)?)
}

/// Get file raw presigned
///
/// Requests the raw contents of a file as a presigned URL, used for
/// letting the client directly download a file from AWS instead of
/// downloading through the server
#[utoipa::path(
    post,
    operation_id = "file_get_raw_presigned",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/raw-presigned",
    responses(
        (status = 200, description = "Obtained raw file successfully"),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to download"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, ?req))]
pub async fn get_raw_presigned(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
    Json(req): Json<GetPresignedRequest>,
) -> HttpResult<PresignedDownloadResponse> {
    let DocumentBoxScope(scope) = scope;

    let file = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let expires_at = req.expires_at.unwrap_or(900);
    let expires_at = Duration::from_secs(expires_at as u64);

    let (signed_request, expires_at) = storage
        .create_presigned_download(&file.file_key, expires_at)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to created file presigned download");
            HttpCommonError::ServerError
        })?;

    Ok(Json(PresignedDownloadResponse {
        method: signed_request.method().to_string(),
        uri: signed_request.uri().to_string(),
        headers: signed_request
            .headers()
            .map(|(key, value)| (key.to_string(), value.to_string()))
            .collect(),
        expires_at,
    }))
}

/// Get file raw named
///
/// Requests the raw contents of a file, this is used for downloading
/// the file or viewing it in the browser or simply requesting its content
///
/// This is identical to [get_raw] except it takes an additional catch-all
/// tail parameter that's used to give a file name to the browser for things
/// like the in-browser PDF viewers. Browsers (Chrome) don't always listen to the
/// Content-Disposition file name so this is required
#[utoipa::path(
    get,
    operation_id = "file_get_raw_named",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/raw/{file_name}",
    responses(
        (status = 200, description = "Obtained raw file successfully", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        ("file_name" = String, Path, description = "User defined file name for the download", allow_reserved = true),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, ?query))]
pub async fn get_raw_named(
    db: TenantDb,
    storage: TenantStorage,
    Path((scope, file_id, _tail)): Path<(DocumentBoxScope, FileId, String)>,
    query: Query<RawFileQuery>,
) -> Result<Response<Body>, DynHttpError> {
    get_raw(db, storage, Path((scope, file_id)), query).await
}

/// Search
///
/// Search within the contents of the file
#[utoipa::path(
    post,
    operation_id = "file_search",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/search",
    responses(
        (status = 200, description = "Searched successfully", body = FileSearchResultResponse),
        (status = 400, description = "Malformed or invalid request not meeting validation requirements", body = HttpErrorResponse),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, ?req))]
pub async fn search(
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
    Json(req): Json<FileSearchRequest>,
) -> HttpResult<FileSearchResultResponse> {
    let DocumentBoxScope(scope) = scope;

    // Assert the file exists
    _ = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    let result = search
        .search_index_file(&scope, file_id, req)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to search document box");
            HttpCommonError::ServerError
        })?;

    Ok(Json(FileSearchResultResponse {
        total_hits: result.total_hits,
        results: result.results,
    }))
}

/// Delete file by ID
///
/// Deletes the provided file
#[utoipa::path(
    delete,
    operation_id = "file_delete",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}",
    responses(
        (status = 204, description = "Deleted file successfully"),
        (status = 404, description = "File not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to delete"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id))]
pub async fn delete(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    TenantSearch(search): TenantSearch,
    TenantEvents(events): TenantEvents,
    Path((scope, file_id)): Path<(DocumentBoxScope, FileId)>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let file = File::find(&db, &scope, file_id)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::UnknownFile)?;

    delete_file(&db, &storage, &search, &events, file, scope)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to delete file");
            HttpCommonError::ServerError
        })?;

    Ok(StatusCode::NO_CONTENT)
}

/// Get generated file
///
/// Requests metadata about a specific generated file type for
/// a file, will return the details about the generated file
/// if it exists
#[utoipa::path(
    get,
    operation_id = "file_get_generated",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/generated/{type}",
    responses(
        (status = 200, description = "Obtained generated file successfully", body = GeneratedFile),
        (status = 404, description = "Generated file not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        ("type" = GeneratedFileType, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, %generated_type))]
pub async fn get_generated(
    TenantDb(db): TenantDb,
    Path((scope, file_id, generated_type)): Path<(DocumentBoxScope, FileId, GeneratedFileType)>,
) -> HttpResult<GeneratedFile> {
    let DocumentBoxScope(scope) = scope;

    let file = GeneratedFile::find(&db, &scope, file_id, generated_type)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query generated file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::NoMatchingGenerated)?;

    Ok(Json(file))
}

/// Get generated file raw
///
/// Request the contents of a specific generated file type
/// for a file, will return the file contents
#[utoipa::path(
    get,
    operation_id = "file_get_generated_raw",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/generated/{type}/raw",
    responses(
        (status = 200, description = "Obtained raw file successfully", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "Generated file not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        ("type" = GeneratedFileType, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, %generated_type))]
pub async fn get_generated_raw(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path((scope, file_id, generated_type)): Path<(DocumentBoxScope, FileId, GeneratedFileType)>,
) -> Result<Response<Body>, DynHttpError> {
    let DocumentBoxScope(scope) = scope;

    let file = GeneratedFile::find(&db, &scope, file_id, generated_type)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query generated file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::NoMatchingGenerated)?;

    let byte_stream = storage.get_file(&file.file_key).await.map_err(|error| {
        tracing::error!(?error, "failed to file from storage");
        HttpCommonError::ServerError
    })?;

    let body = axum::body::Body::from_stream(byte_stream);

    let csp = match mime::Mime::from_str(&file.mime) {
        // Images are served with a strict image only content security policy
        Ok(mime) if mime.type_() == mime::IMAGE => "default-src 'none'; img-src 'self' data:;",
        // Default policy
        _ => "script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'",
    };

    Ok(Response::builder()
        .header(header::CONTENT_TYPE, file.mime)
        .header(header::CONTENT_SECURITY_POLICY, csp)
        .header(
            header::CONTENT_DISPOSITION,
            HeaderValue::from_str("inline;filename=\"preview.pdf\"")?,
        )
        .body(body)?)
}

/// Get generated file raw presigned
///
/// Requests the raw contents of a generated file as a presigned URL,
/// used for letting the client directly download a file from AWS
/// instead of downloading through the server and gateway
#[utoipa::path(
    post,
    operation_id = "file_get_generated_raw_presigned",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/generated/{type}/raw-presigned",
    responses(
        (status = 200, description = "Obtained raw file successfully"),
        (status = 404, description = "Generated file not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        ("type" = GeneratedFileType, Path, description = "ID of the file to query"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, %generated_type, ?req))]
pub async fn get_generated_raw_presigned(
    TenantDb(db): TenantDb,
    TenantStorage(storage): TenantStorage,
    Path((scope, file_id, generated_type)): Path<(DocumentBoxScope, FileId, GeneratedFileType)>,
    Json(req): Json<GetPresignedRequest>,
) -> HttpResult<PresignedDownloadResponse> {
    let DocumentBoxScope(scope) = scope;

    let file = GeneratedFile::find(&db, &scope, file_id, generated_type)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to query generated file");
            HttpCommonError::ServerError
        })?
        .ok_or(HttpFileError::NoMatchingGenerated)?;

    let expires_at = req.expires_at.unwrap_or(900);
    let expires_at = Duration::from_secs(expires_at as u64);

    let (signed_request, expires_at) = storage
        .create_presigned_download(&file.file_key, expires_at)
        .await
        .map_err(|_| HttpCommonError::ServerError)?;

    Ok(Json(PresignedDownloadResponse {
        method: signed_request.method().to_string(),
        uri: signed_request.uri().to_string(),
        headers: signed_request
            .headers()
            .map(|(key, value)| (key.to_string(), value.to_string()))
            .collect(),
        expires_at,
    }))
}

/// Get generated file raw named
///
/// Request the contents of a specific generated file type
/// for a file, will return the file contents
///
/// See [get_raw_named] for reasoning
#[utoipa::path(
    get,
    operation_id = "file_get_generated_raw_named",
    tag = FILE_TAG,
    path = "/box/{scope}/file/{file_id}/generated/{type}/raw/{file_name}",
    responses(
        (status = 200, description = "Obtained raw file successfully", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "Generated file not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the file resides within"),
        ("file_id" = Uuid, Path, description = "ID of the file to query"),
        ("type" = GeneratedFileType, Path, description = "ID of the file to query"),
        ("file_name" = String, Path, description = "User defined file name for the download", allow_reserved = true),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %file_id, %generated_type))]
pub async fn get_generated_raw_named(
    db: TenantDb,
    storage: TenantStorage,
    Path((scope, file_id, generated_type, _tail)): Path<(
        DocumentBoxScope,
        FileId,
        GeneratedFileType,
        String,
    )>,
) -> Result<Response<Body>, DynHttpError> {
    get_generated_raw(db, storage, Path((scope, file_id, generated_type))).await
}