moosicbox_scan 0.1.0

MoosicBox scan package
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
use std::str::FromStr;

use actix_web::{
    delete,
    dev::{ServiceFactory, ServiceRequest},
    error::{ErrorBadRequest, ErrorInternalServerError},
    post,
    web::{self, Json},
    Result, Scope,
};
use moosicbox_auth::NonTunnelRequestAuthorized;
use moosicbox_database::profiles::LibraryDatabase;
use moosicbox_music_api::MusicApis;
use serde::Deserialize;
use serde_json::Value;

use crate::{disable_scan_origin, enable_scan_origin, run_scan, ScanError, ScanOrigin};

pub fn bind_services<
    T: ServiceFactory<ServiceRequest, Config = (), Error = actix_web::Error, InitError = ()>,
>(
    scope: Scope<T>,
) -> Scope<T> {
    let scope = scope
        .service(run_scan_endpoint)
        .service(start_scan_endpoint)
        .service(enable_scan_origin_endpoint)
        .service(disable_scan_origin_endpoint);

    #[cfg(feature = "local")]
    let scope = scope
        .service(get_scan_origins_endpoint)
        .service(run_scan_path_endpoint)
        .service(get_scan_paths_endpoint)
        .service(add_scan_path_endpoint)
        .service(remove_scan_path_endpoint);

    scope
}

#[cfg(feature = "openapi")]
#[derive(utoipa::OpenApi)]
#[openapi(
    tags((name = "Scan")),
    paths(
        run_scan_endpoint,
        start_scan_endpoint,
        run_scan_path_endpoint,
        get_scan_origins_endpoint,
        enable_scan_origin_endpoint,
        disable_scan_origin_endpoint,
        get_scan_paths_endpoint,
        add_scan_path_endpoint,
        remove_scan_path_endpoint,
    ),
    components(schemas(
        ScanOrigin,
    ))
)]
pub struct Api;

#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ScanQuery {
    origins: Option<String>,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        post,
        path = "/run-scan",
        description = "Run a scan for the specified origin(s)",
        params(
            ("origins" = Option<String>, Query, description = "Comma-separated list of ScanOrigins"),
        ),
        responses(
            (
                status = 200,
                description = "The scan has successfully ran",
                body = Value,
            )
        )
    )
)]
#[post("/run-scan")]
pub async fn run_scan_endpoint(
    query: web::Query<ScanQuery>,
    db: LibraryDatabase,
    music_apis: MusicApis,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    let origins = query
        .origins
        .as_ref()
        .map(|origins| {
            origins
                .split(',')
                .map(|s| s.trim())
                .map(|s| {
                    ScanOrigin::from_str(s)
                        .map_err(|_e| ErrorBadRequest(format!("Invalid ScanOrigin value: {s}")))
                })
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?;

    run_scan(origins, &db, music_apis)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to scan: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        post,
        path = "/start-scan",
        description = "Start a scan for the specified origin(s)",
        params(
            ("origins" = Option<String>, Query, description = "Comma-separated list of ScanOrigins"),
        ),
        responses(
            (
                status = 200,
                description = "The scan has successfully started",
                body = Value,
            )
        )
    )
)]
#[post("/start-scan")]
pub async fn start_scan_endpoint(
    query: web::Query<ScanQuery>,
    db: LibraryDatabase,
    music_apis: MusicApis,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    let origins = query
        .origins
        .as_ref()
        .map(|origins| {
            origins
                .split(',')
                .map(|s| s.trim())
                .map(|s| {
                    ScanOrigin::from_str(s)
                        .map_err(|_e| ErrorBadRequest(format!("Invalid ScanOrigin value: {s}")))
                })
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?;

    moosicbox_task::spawn("scan", async move {
        run_scan(origins, &db, music_apis).await.map_err(|e| {
            moosicbox_assert::die_or_error!("Scan error: {e:?}");
            e
        })?;

        Ok::<_, ScanError>(())
    });

    Ok(Json(serde_json::json!({"success": true})))
}

#[cfg(feature = "local")]
#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ScanPathQuery {
    path: String,
}

#[cfg(feature = "local")]
#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        post,
        path = "/run-scan-path",
        description = "Run a local scan on the specific path",
        params(
            ("path" = String, Query, description = "Local file path to scan"),
        ),
        responses(
            (
                status = 200,
                description = "The scan has successfully ran",
                body = Value,
            )
        )
    )
)]
#[post("/run-scan-path")]
pub async fn run_scan_path_endpoint(
    query: web::Query<ScanPathQuery>,
    db: LibraryDatabase,
    music_apis: MusicApis,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    let scanner = crate::Scanner::new(crate::event::ScanTask::Local {
        paths: vec![query.path.clone()],
    })
    .await;

    scanner
        .scan(music_apis, &db)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to scan: {e:?}")))?;

    crate::local::scan(&query.path, &db, crate::CANCELLATION_TOKEN.clone(), scanner)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to scan: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}

#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GetScanOriginsQuery {}

#[cfg(feature = "local")]
#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        get,
        path = "/scan-origins",
        description = "Get the enabled scan origins",
        params(),
        responses(
            (
                status = 200,
                description = "The enabled scan origins",
                body = Value,
            )
        )
    )
)]
#[actix_web::get("/scan-origins")]
pub async fn get_scan_origins_endpoint(
    _query: web::Query<GetScanOriginsQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    let origins = crate::get_scan_origins(&db)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to get scan origins: {e:?}")))?;

    Ok(Json(serde_json::json!({"origins": origins})))
}

#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct EnableScanOriginQuery {
    origin: ScanOrigin,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        post,
        path = "/scan-origins",
        description = "Enable a scan origin",
        params(
            ("origin" = ScanOrigin, Query, description = "ScanOrigin to enable"),
        ),
        responses(
            (
                status = 200,
                description = "The ScanOrigin was successfully enabled",
                body = Value,
            )
        )
    )
)]
#[post("/scan-origins")]
pub async fn enable_scan_origin_endpoint(
    query: web::Query<EnableScanOriginQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    enable_scan_origin(&db, query.origin)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to enable scan origin: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}

#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DisableScanOriginQuery {
    origin: ScanOrigin,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        delete,
        path = "/scan-origins",
        description = "Disable a scan origin",
        params(
            ("origin" = ScanOrigin, Query, description = "ScanOrigin to disable"),
        ),
        responses(
            (
                status = 200,
                description = "The ScanOrigin was successfully disabled",
                body = Value,
            )
        )
    )
)]
#[delete("/scan-origins")]
pub async fn disable_scan_origin_endpoint(
    query: web::Query<DisableScanOriginQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    disable_scan_origin(&db, query.origin)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to disable scan origin: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}

#[cfg(feature = "local")]
#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GetScanPathsQuery {}

#[cfg(feature = "local")]
#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        get,
        path = "/scan-paths",
        description = "Get the enabled local scan paths",
        params(),
        responses(
            (
                status = 200,
                description = "The enabled local scan paths",
                body = Value,
            )
        )
    )
)]
#[actix_web::get("/scan-paths")]
pub async fn get_scan_paths_endpoint(
    _query: web::Query<GetScanPathsQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    let paths = crate::get_scan_paths(&db)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to get scan paths: {e:?}")))?;

    Ok(Json(serde_json::json!({"paths": paths})))
}

#[cfg(feature = "local")]
#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AddScanPathQuery {
    path: String,
}

#[cfg(feature = "local")]
#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        post,
        path = "/scan-paths",
        description = "Enable a local scan path",
        params(
            ("origin" = String, Query, description = "Local scan path to enable"),
        ),
        responses(
            (
                status = 200,
                description = "The local scan path was successfully enabled",
                body = Value,
            )
        )
    )
)]
#[post("/scan-paths")]
pub async fn add_scan_path_endpoint(
    query: web::Query<AddScanPathQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    static REGEX: std::sync::LazyLock<regex::Regex> =
        std::sync::LazyLock::new(|| regex::Regex::new(r"/mnt/(\w+)").unwrap());

    let path = if std::env::consts::OS == "windows" {
        REGEX
            .replace(&query.path, |caps: &regex::Captures| {
                format!("{}:", caps[1].to_uppercase())
            })
            .replace('/', "\\")
    } else {
        query.path.clone()
    };

    crate::add_scan_path(&db, &path)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to add scan path: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}

#[cfg(feature = "local")]
#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RemoveScanPathQuery {
    path: String,
}

#[cfg(feature = "local")]
#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["Scan"],
        delete,
        path = "/scan-paths",
        description = "Disable a local scan path",
        params(
            ("origin" = String, Query, description = "Local scan path to disable"),
        ),
        responses(
            (
                status = 200,
                description = "The local scan path was successfully disabled",
                body = Value,
            )
        )
    )
)]
#[delete("/scan-paths")]
pub async fn remove_scan_path_endpoint(
    query: web::Query<RemoveScanPathQuery>,
    db: LibraryDatabase,
    _: NonTunnelRequestAuthorized,
) -> Result<Json<Value>> {
    crate::remove_scan_path(&db, &query.path)
        .await
        .map_err(|e| ErrorInternalServerError(format!("Failed to remove scan path: {e:?}")))?;

    Ok(Json(serde_json::json!({"success": true})))
}