headless_lms_server/controllers/cms/
organizations.rs

1//! Controllers for requests starting with `/api/v0/cms/organizations`.
2
3use crate::prelude::*;
4
5/**
6POST `/api/v0/cms/organizations/:organization_id/upload` - Uploads a media (image, audio, file) for the course from Gutenberg page edit.
7
8Put the the contents of the media in a form and add a content type header multipart/form-data.
9# Example
10
11Request:
12```http
13POST /api/v0/cms/pages/d86cf910-4d26-40e9-8c9c-1cc35294fdbb/upload HTTP/1.1
14Content-Type: multipart/form-data
15
16BINARY_DATA
17```
18*/
19
20#[instrument(skip(payload, request, pool, file_store, app_conf))]
21async fn add_media(
22    organization_id: web::Path<Uuid>,
23    payload: Multipart,
24    request: HttpRequest,
25    pool: web::Data<PgPool>,
26    user: AuthUser,
27    file_store: web::Data<dyn FileStore>,
28    app_conf: web::Data<ApplicationConfiguration>,
29) -> ControllerResult<web::Json<UploadResult>> {
30    let mut conn = pool.acquire().await?;
31    let token = authorize(
32        &mut conn,
33        Act::Edit,
34        Some(user.id),
35        Res::Organization(*organization_id),
36    )
37    .await?;
38    let organization = models::organizations::get_organization(&mut conn, *organization_id).await?;
39
40    let media_path = upload_file_from_cms(
41        request.headers(),
42        payload,
43        StoreKind::Organization(organization.id),
44        file_store.as_ref(),
45        &mut conn,
46        user,
47    )
48    .await?;
49    let download_url = file_store.get_download_url(media_path.as_path(), app_conf.as_ref());
50    token.authorized_ok(web::Json(UploadResult { url: download_url }))
51}
52
53/**
54Add a route for each controller in this module.
55
56The name starts with an underline in order to appear before other functions in the module documentation.
57
58We add the routes by calling the route method instead of using the route annotations because this method preserves the function signatures for documentation.
59*/
60pub fn _add_routes(cfg: &mut ServiceConfig) {
61    cfg.route("/{organization_id}/upload", web::post().to(add_media));
62}