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
//! Link related endpoints

use crate::{
    error::{DynHttpError, HttpCommonError, HttpErrorResponse, HttpResult, HttpStatusResult},
    middleware::{
        action_user::{ActionUser, UserParams},
        tenant::{TenantDb, TenantEvents, TenantParams, TenantSearch},
    },
    models::{
        document_box::DocumentBoxScope,
        file::BinaryResponse,
        folder::HttpFolderError,
        link::{CreateLink, HttpLinkError, LinkMetadataResponse, UpdateLinkRequest},
    },
};
use axum::{
    Extension, Json,
    body::Body,
    extract::Path,
    http::{Response, StatusCode, header},
};
use axum_valid::Garde;
use docbox_core::{
    database::models::{
        edit_history::EditHistory,
        folder::Folder,
        link::{Link, LinkId, LinkWithExtra},
    },
    links::get_link_metadata::get_link_metadata,
};
use docbox_core::{
    database::{DbPool, models::document_box::DocumentBoxScopeRawRef},
    links::{
        create_link::{CreateLinkData, safe_create_link},
        delete_link::delete_link,
        get_link_metadata::GetLinkMetadataError,
        resolve_website::ResolveWebsiteService,
        update_link::{UpdateLink, UpdateLinkError},
    },
};
use std::sync::Arc;

pub const LINK_TAG: &str = "Link";

/// Create link
///
/// Creates a new link within the provided document box
#[utoipa::path(
    post,
    operation_id = "link_create",
    tag = LINK_TAG,
    path = "/box/{scope}/link",
    responses(
        (status = 201, description = "Link created successfully", body = LinkWithExtra),
        (status = 404, description = "Destination folder not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope to create the link within"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope))]
pub async fn create(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantEvents(events): TenantEvents,
    Path(DocumentBoxScope(scope)): Path<DocumentBoxScope>,
    Garde(Json(req)): Garde<Json<CreateLink>>,
) -> Result<(StatusCode, Json<LinkWithExtra>), DynHttpError> {
    let folder_id = req.folder_id;
    let folder = Folder::find_by_id(&db, &scope, folder_id)
        .await
        // Failed to query destination folder
        .map_err(|error| {
            tracing::error!(?error, "failed to query link destination folder");
            HttpCommonError::ServerError
        })?
        // Destination folder was not found
        .ok_or(HttpFolderError::UnknownFolder)?;

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

    // Make the create query
    let create = CreateLinkData {
        folder,
        name: req.name,
        value: req.value,
        created_by: created_by.as_ref().map(|value| value.id.to_string()),
    };

    // Perform Link creation
    let link = safe_create_link(&db, search, &events, create)
        .await
        .map_err(|error| {
            tracing::error!(?error, "failed to create link");
            HttpLinkError::CreateError(error)
        })?;

    Ok((
        StatusCode::CREATED,
        Json(LinkWithExtra {
            link,
            created_by,
            last_modified_at: None,
            last_modified_by: None,
        }),
    ))
}

/// Get link by ID
///
/// Request a specific link by ID
#[utoipa::path(
    get,
    operation_id = "link_get",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}",
    responses(
        (status = 200, description = "Link obtained successfully", body = LinkWithExtra),
        (status = 404, description = "Link not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id))]
pub async fn get(
    TenantDb(db): TenantDb,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
) -> HttpResult<LinkWithExtra> {
    let DocumentBoxScope(scope) = scope;

    let link = Link::find_with_extra(&db, &scope, link_id)
        .await
        // Failed to query link
        .map_err(|error| {
            tracing::error!(?error, "failed to query link");
            HttpCommonError::ServerError
        })?
        // Link not found
        .ok_or(HttpLinkError::UnknownLink)?;

    Ok(Json(link))
}

/// Get link website metadata
///
/// Requests metadata for the link. This will make a request
/// to the site at the link value to extract metadata from
/// the website itself such as title, and OGP metadata
#[utoipa::path(
    get,
    operation_id = "link_get_metadata",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}/metadata",
    responses(
        (status = 200, description = "Obtained link metadata successfully", body = LinkWithExtra),
        (status = 404, description = "Link not found or failed to resolve metadata", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id))]
pub async fn get_metadata(
    TenantDb(db): TenantDb,
    Extension(website_service): Extension<Arc<ResolveWebsiteService>>,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
) -> HttpResult<LinkMetadataResponse> {
    let DocumentBoxScope(scope) = scope;

    let link = find_link(&db, &scope, link_id).await?;

    let (_, resolved) = get_link_metadata(&db, &website_service, &link)
        .await
        .map_err(|error| match error {
            GetLinkMetadataError::ParseUrl(_) => HttpLinkError::InvalidLinkUrl,
            GetLinkMetadataError::FailedResolve => HttpLinkError::FailedResolve,
        })?;

    Ok(Json(LinkMetadataResponse {
        title: resolved.title,
        og_title: resolved.og_title,
        og_description: resolved.og_description,
        favicon: resolved.best_favicon.is_some(),
        image: resolved.og_image.is_some(),
    }))
}

/// Get link favicon
///
/// Obtain the favicon image for the website that the link points to
/// the image data is streamed directly from the target website
#[utoipa::path(
    get,
    operation_id = "link_get_favicon",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}/favicon",
    responses(
        (status = 200, description = "Streamed link favicon binary data", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "Link not found or no favicon was found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id))]
pub async fn get_favicon(
    TenantDb(db): TenantDb,
    Extension(website_service): Extension<Arc<ResolveWebsiteService>>,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
) -> Result<Response<Body>, DynHttpError> {
    let DocumentBoxScope(scope) = scope;

    let link = find_link(&db, &scope, link_id).await?;

    let (url, website_metadata) = get_link_metadata(&db, &website_service, &link)
        .await
        .map_err(|error| match error {
            GetLinkMetadataError::ParseUrl(_) => HttpLinkError::InvalidLinkUrl,
            GetLinkMetadataError::FailedResolve => HttpLinkError::FailedResolve,
        })?;

    let favicon = website_service
        .service
        .resolve_favicon(&url, website_metadata.best_favicon)
        .await
        .ok_or(HttpLinkError::NoFavicon)?;

    let body = axum::body::Body::from_stream(favicon.stream);

    Ok(Response::builder()
        .header(header::CONTENT_TYPE, favicon.content_type.to_string())
        .header(
            header::CONTENT_SECURITY_POLICY,
            "default-src 'none'; img-src 'self' data:;",
        )
        .header(
            header::CACHE_CONTROL,
            "public, max-age=3600, stale-while-revalidate=86400",
        )
        .body(body)?)
}

/// Get link social image
///
/// Obtain the "Social Image" for the website, this resolves the website
/// metadata and finds the OGP metadata image responding with the image
/// directly. The image data is streamed directly from the target
/// website
#[utoipa::path(
    get,
    operation_id = "link_get_image",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}/image",
    responses(
        (status = 200, description = "Streamed link social image binary data", content_type = "application/octet-stream", body = BinaryResponse),
        (status = 404, description = "Link not found or no image was found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to request"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id))]
pub async fn get_image(
    TenantDb(db): TenantDb,
    Extension(website_service): Extension<Arc<ResolveWebsiteService>>,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
) -> Result<Response<Body>, DynHttpError> {
    let DocumentBoxScope(scope) = scope;

    let link = find_link(&db, &scope, link_id).await?;

    let (url, website_metadata) = get_link_metadata(&db, &website_service, &link)
        .await
        .map_err(|error| match error {
            GetLinkMetadataError::ParseUrl(_) => HttpLinkError::InvalidLinkUrl,
            GetLinkMetadataError::FailedResolve => HttpLinkError::FailedResolve,
        })?;

    let og_image = website_metadata.og_image.ok_or(HttpLinkError::NoImage)?;
    let og_image = website_service
        .service
        .resolve_image(&url, &og_image)
        .await
        .ok_or(HttpLinkError::NoImage)?;

    let body = axum::body::Body::from_stream(og_image.stream);

    Ok(Response::builder()
        .header(header::CONTENT_TYPE, og_image.content_type.to_string())
        .header(
            header::CONTENT_SECURITY_POLICY,
            "default-src 'none'; img-src 'self' data:;",
        )
        .header(
            header::CACHE_CONTROL,
            "public, max-age=3600, stale-while-revalidate=86400",
        )
        .body(body)?)
}

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

    // Ensure the link itself exists
    _ = find_link(&db, &scope, link_id).await?;

    let history = EditHistory::all_by_link(&db, link_id)
        .await
        // Failed to query edit history
        .map_err(|error| {
            tracing::error!(?error, "failed to query link edit history");
            HttpCommonError::ServerError
        })?;

    Ok(Json(history))
}

/// Update link
///
/// Updates a link, can be a name change, value change, a folder move, or all
#[utoipa::path(
    put,
    operation_id = "link_update",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}",
    responses(
        (status = 200, description = "Updated link successfully"),
        (status = 404, description = "Link not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to request"),
        TenantParams,
        UserParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id, ?req))]
pub async fn update(
    action_user: ActionUser,
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
    Garde(Json(req)): Garde<Json<UpdateLinkRequest>>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let link = find_link(&db, &scope, link_id).await?;

    // 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 = UpdateLink {
        folder_id: req.folder_id,
        name: req.name,
        value: req.value,
        pinned: req.pinned,
    };

    docbox_core::links::update_link::update_link(&db, &search, &scope, link, user_id, update)
        .await
        .map_err(|error| match error {
            UpdateLinkError::UnknownTargetFolder => {
                DynHttpError::from(HttpFolderError::UnknownTargetFolder)
            }
            _ => DynHttpError::from(HttpCommonError::ServerError),
        })?;

    Ok(StatusCode::OK)
}

/// Delete a link by ID
///
/// Deletes a specific link using its ID
#[utoipa::path(
    delete,
    operation_id = "link_delete",
    tag = LINK_TAG,
    path = "/box/{scope}/link/{link_id}",
    responses(
        (status = 204, description = "Deleted link successfully"),
        (status = 404, description = "Link not found", body = HttpErrorResponse),
        (status = 500, description = "Internal server error", body = HttpErrorResponse)
    ),
    params(
        ("scope" = DocumentBoxScope, Path, description = "Scope the link resides within"),
        ("link_id" = Uuid, Path, description = "ID of the link to delete"),
        TenantParams
    )
)]
#[tracing::instrument(skip_all, fields(%scope, %link_id))]
pub async fn delete(
    TenantDb(db): TenantDb,
    TenantSearch(search): TenantSearch,
    TenantEvents(events): TenantEvents,
    Path((scope, link_id)): Path<(DocumentBoxScope, LinkId)>,
) -> HttpStatusResult {
    let DocumentBoxScope(scope) = scope;

    let link = find_link(&db, &scope, link_id).await?;

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

    Ok(StatusCode::NO_CONTENT)
}

/// Resolves a link handles mapping the various link failure
/// errors into HTTP errors
async fn find_link(
    db: &DbPool,
    scope: DocumentBoxScopeRawRef<'_>,
    link_id: LinkId,
) -> Result<Link, DynHttpError> {
    let link = Link::find(db, scope, link_id)
        .await
        // Failed to query link
        .map_err(|error| {
            tracing::error!(?error, "failed to query link");
            HttpCommonError::ServerError
        })?
        // Link not found
        .ok_or(HttpLinkError::UnknownLink)?;

    Ok(link)
}