switchy_upnp 0.2.0

Switchy UPnP 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
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
//! Actix-web API endpoints for `UPnP` device control.
//!
//! This module provides HTTP REST API endpoints for discovering and controlling `UPnP` devices.
//! Requires the `api` feature to be enabled.

#![allow(clippy::needless_for_each)]

use std::collections::BTreeMap;

use actix_web::{
    Result, Scope,
    dev::{ServiceFactory, ServiceRequest},
    error::{ErrorBadRequest, ErrorFailedDependency, ErrorInternalServerError},
    route,
    web::{self, Json},
};
use futures::TryStreamExt;
use serde::Deserialize;

use crate::{
    ActionError, MediaInfo, PositionInfo, ScanError, TransportInfo, UpnpDeviceScannerError,
    cache::get_device_and_service_from_url, devices, get_device_and_service, get_media_info,
    get_position_info, get_transport_info, get_volume, models::UpnpDevice, pause, play,
    scan_devices, seek, set_volume, subscribe_events,
};

/// Binds all `UPnP` API endpoints to the provided Actix-web scope.
///
/// This function registers all `UPnP` control endpoints (scan, transport info, media info,
/// position info, volume control, subscriptions, and playback control) to the given scope.
pub fn bind_services<
    T: ServiceFactory<ServiceRequest, Config = (), Error = actix_web::Error, InitError = ()>,
>(
    scope: Scope<T>,
) -> Scope<T> {
    scope
        .service(scan_devices_endpoint)
        .service(get_transport_info_endpoint)
        .service(get_media_info_endpoint)
        .service(get_position_info_endpoint)
        .service(get_volume_endpoint)
        .service(set_volume_endpoint)
        .service(subscribe_endpoint)
        .service(pause_endpoint)
        .service(play_endpoint)
        .service(seek_endpoint)
}

/// `OpenAPI` specification generator for `UPnP` API endpoints.
///
/// This struct is used with `utoipa` to generate `OpenAPI` documentation
/// for all `UPnP` control endpoints when the `openapi` feature is enabled.
#[cfg(feature = "openapi")]
#[derive(utoipa::OpenApi)]
#[openapi(
    tags((name = "UPnP")),
    paths(
        scan_devices_endpoint,
        get_transport_info_endpoint,
        get_media_info_endpoint,
        get_position_info_endpoint,
        get_volume_endpoint,
        set_volume_endpoint,
        subscribe_endpoint,
        pause_endpoint,
        play_endpoint,
        seek_endpoint,
    ),
    components(schemas(
        MediaInfo,
        PositionInfo,
        TransportInfo,
        crate::TrackMetadata,
        crate::TrackMetadataItem,
        crate::TrackMetadataItemResource,
        UpnpDevice,
        crate::models::UpnpService,
    ))
)]
pub struct Api;

impl From<ActionError> for actix_web::Error {
    fn from(e: ActionError) -> Self {
        match &e {
            ActionError::Rupnp(rupnp_err) => {
                ErrorFailedDependency(format!("UPnP error: {rupnp_err:?}"))
            }
            ActionError::MissingProperty(_property) => ErrorInternalServerError(e.to_string()),
            ActionError::Roxml(roxmltree_err) => {
                ErrorFailedDependency(format!("roxmltree error: {roxmltree_err:?}"))
            }
        }
    }
}

impl From<ScanError> for actix_web::Error {
    fn from(e: ScanError) -> Self {
        ErrorFailedDependency(e.to_string())
    }
}

impl From<UpnpDeviceScannerError> for actix_web::Error {
    fn from(e: UpnpDeviceScannerError) -> Self {
        ErrorFailedDependency(e.to_string())
    }
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/scan-devices",
        description = "Scan the network for `UPnP` devices",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
        ),
        responses(
            (
                status = 200,
                description = "List of `UPnP` devices",
                body = Vec<UpnpDevice>,
            )
        )
    )
)]
#[route("/scan-devices", method = "GET")]
/// Scans the network for `UPnP` devices and returns discovered devices.
///
/// # Errors
///
/// * If device discovery fails
pub async fn scan_devices_endpoint() -> Result<Json<Vec<UpnpDevice>>> {
    scan_devices().await?;
    Ok(Json(devices().await))
}

/// Query parameters for retrieving `UPnP` transport information.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTransportInfoQuery {
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        get,
        path = "/transport-info",
        description = "Get the current `UPnP` transport info",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to get transport info from"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to get transport info from"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to get transport info from"),
        ),
        responses(
            (
                status = 200,
                description = "The current `UPnP` transport info",
                body = TransportInfo,
            )
        )
    )
)]
#[route("/transport-info", method = "GET")]
/// Retrieves transport information for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn get_transport_info_endpoint(
    query: web::Query<GetTransportInfoQuery>,
) -> Result<Json<TransportInfo>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        get_transport_info(&service, device.url(), query.instance_id).await?,
    ))
}

/// Query parameters for retrieving `UPnP` media information.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetMediaInfoQuery {
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        get,
        path = "/media-info",
        description = "Get the current `UPnP` media info",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to get media info from"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to get media info from"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to get media info from"),
        ),
        responses(
            (
                status = 200,
                description = "The current `UPnP` media info",
                body = MediaInfo,
            )
        )
    )
)]
#[route("/media-info", method = "GET")]
/// Retrieves media information for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn get_media_info_endpoint(
    query: web::Query<GetMediaInfoQuery>,
) -> Result<Json<MediaInfo>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        get_media_info(&service, device.url(), query.instance_id).await?,
    ))
}

/// Query parameters for retrieving `UPnP` position information.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPositionInfoQuery {
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        get,
        path = "/position-info",
        description = "Get the current `UPnP` position info",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to get position info from"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to get position info from"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to get position info from"),
        ),
        responses(
            (
                status = 200,
                description = "The current `UPnP` position info",
                body = PositionInfo,
            )
        )
    )
)]
#[route("/position-info", method = "GET")]
/// Retrieves playback position information for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn get_position_info_endpoint(
    query: web::Query<GetPositionInfoQuery>,
) -> Result<Json<PositionInfo>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        get_position_info(&service, device.url(), query.instance_id).await?,
    ))
}

/// Query parameters for retrieving `UPnP` volume information.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetVolumeQuery {
    /// Audio channel to get volume for (defaults to "Master").
    channel: Option<String>,
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        get,
        path = "/volume",
        description = "Get the current `UPnP` volume info for a device",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("channel" = Option<String>, Query, description = "`UPnP` device channel to get volume info from"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to get volume info from"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to get volume info from"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to get volume info from"),
        ),
        responses(
            (
                status = 200,
                description = "The current `UPnP` volume info",
                body = BTreeMap<String, String>,
            )
        )
    )
)]
#[route("/volume", method = "GET")]
/// Retrieves current volume values for a `UPnP` `RenderingControl` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn get_volume_endpoint(
    query: web::Query<GetVolumeQuery>,
) -> Result<Json<BTreeMap<String, String>>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:RenderingControl")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:RenderingControl")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        get_volume(
            &service,
            device.url(),
            query.instance_id,
            query.channel.as_deref().unwrap_or("Master"),
        )
        .await?,
    ))
}

/// Query parameters for setting `UPnP` volume.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetVolumeQuery {
    /// Audio channel to set volume for (defaults to "Master").
    channel: Option<String>,
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
    /// Volume level to set (0-100).
    value: u8,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/volume",
        description = "Set the current `UPnP` volume for a device",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("channel" = Option<String>, Query, description = "`UPnP` device channel to get volume info from"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to get volume info from"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to get volume info from"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to get volume info from"),
            ("value" = u8, Query, description = "Integer to set the device volume to"),
        ),
        responses(
            (
                status = 200,
                description = "The set volume action response",
                body = BTreeMap<String, String>,
            )
        )
    )
)]
#[route("/volume", method = "POST")]
/// Sets the volume for a `UPnP` `RenderingControl` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn set_volume_endpoint(
    query: web::Query<SetVolumeQuery>,
) -> Result<Json<BTreeMap<String, String>>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:RenderingControl")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:RenderingControl")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        set_volume(
            &service,
            device.url(),
            query.instance_id,
            query.channel.as_deref().unwrap_or("Master"),
            query.value,
        )
        .await?,
    ))
}

/// Query parameters for subscribing to `UPnP` service events.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscribeQuery {
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// Service ID to subscribe to (e.g., "urn:upnp-org:serviceId:AVTransport").
    service_id: String,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/subscribe",
        description = "Subscribe to the specified device's service",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to subscribe to"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to subscribe to"),
            ("serviceId" = String, Query, description = "`UPnP` device service ID to subscribe to"),
        ),
        responses(
            (
                status = 200,
                description = "The subscribe SID",
                body = String,
            )
        )
    )
)]
#[route("/subscribe", method = "POST")]
/// Subscribes to event notifications for a `UPnP` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the event subscription call fails
pub async fn subscribe_endpoint(query: web::Query<SubscribeQuery>) -> Result<Json<String>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, &query.service_id)?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, &query.service_id)?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    let (sid, mut stream) = subscribe_events(&service, device.url()).await?;

    switchy_async::runtime::Handle::current().spawn_with_name(
        &format!("upnp: api subscribe {sid}"),
        {
            let sid = sid.clone();
            async move {
                while let Ok(Some(event)) = stream.try_next().await {
                    log::info!("Received subscription event for sid={sid}: {event:?}");
                }
                log::info!("Stream ended for sid={sid}");
            }
        },
    );

    Ok(Json(sid))
}

/// Query parameters for pausing `UPnP` playback.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PauseQuery {
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/pause",
        description = "Pause the specified device's `AVTransport`",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to pause"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to pause"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to pause"),
        ),
        responses(
            (
                status = 200,
                description = "The pause action response",
                body = String,
            )
        )
    )
)]
#[route("/pause", method = "POST")]
/// Pauses playback for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn pause_endpoint(
    query: web::Query<PauseQuery>,
) -> Result<Json<BTreeMap<String, String>>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        pause(&service, device.url(), query.instance_id).await?,
    ))
}

/// Query parameters for starting `UPnP` playback.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlayQuery {
    /// Playback speed multiplier (defaults to 1.0).
    speed: Option<f64>,
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/play",
        description = "Play the specified device's `AVTransport`",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("speed" = Option<f64>, Query, description = "Speed to play the playback at"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to play"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to play"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to play"),
        ),
        responses(
            (
                status = 200,
                description = "The play action response",
                body = String,
            )
        )
    )
)]
#[route("/play", method = "POST")]
/// Starts playback for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn play_endpoint(query: web::Query<PlayQuery>) -> Result<Json<BTreeMap<String, String>>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        play(
            &service,
            device.url(),
            query.instance_id,
            query.speed.unwrap_or(1.0),
        )
        .await?,
    ))
}

/// Query parameters for seeking within `UPnP` playback.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SeekQuery {
    /// Target position in seconds.
    position: f64,
    /// Unique device name of the `UPnP` device.
    device_udn: Option<String>,
    /// URL of the `UPnP` device.
    device_url: Option<String>,
    /// `UPnP` instance ID.
    instance_id: u32,
    /// Seek unit type (defaults to `ABS_TIME`).
    unit: Option<String>,
}

#[cfg_attr(
    feature = "openapi", utoipa::path(
        tags = ["UPnP"],
        post,
        path = "/seek",
        description = "Seek the specified device's `AVTransport`",
        params(
            ("moosicbox-profile" = String, Header, description = "MoosicBox profile"),
            ("position" = f64, Query, description = "Seek position to seek the playback to"),
            ("deviceUdn" = Option<String>, Query, description = "`UPnP` device UDN to seek"),
            ("deviceUrl" = Option<String>, Query, description = "`UPnP` device URL to seek"),
            ("instanceId" = u32, Query, description = "`UPnP` instance ID to seek"),
            ("unit" = Option<String>, Query, description = "Seek unit"),
        ),
        responses(
            (
                status = 200,
                description = "The seek action response",
                body = String,
            )
        )
    )
)]
#[route("/seek", method = "POST")]
/// Seeks playback position for a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If neither `device_udn` nor `device_url` is provided in the query
/// * If the target device or service is not found
/// * If the `UPnP` action call fails
pub async fn seek_endpoint(query: web::Query<SeekQuery>) -> Result<Json<BTreeMap<String, String>>> {
    let (device, service) = if let Some(udn) = &query.device_udn {
        get_device_and_service(udn, "urn:upnp-org:serviceId:AVTransport")?
    } else if let Some(url) = &query.device_url {
        get_device_and_service_from_url(url, "urn:upnp-org:serviceId:AVTransport")?
    } else {
        return Err(ErrorBadRequest("Must pass device_udn or device_url"));
    };
    Ok(Json(
        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        seek(
            &service,
            device.url(),
            query.instance_id,
            query.unit.as_deref().unwrap_or("ABS_TIME"),
            query.position as u32,
        )
        .await?,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test_log::test]
    fn test_action_error_missing_property_converts_to_internal_server_error() {
        let error = ActionError::MissingProperty("TestProperty".to_string());
        let actix_error: actix_web::Error = error.into();
        // ErrorInternalServerError returns a 500 status
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[test_log::test]
    fn test_scan_error_converts_to_failed_dependency() {
        let error = ScanError::RenderingControlNotFound;
        let actix_error: actix_web::Error = error.into();
        // ErrorFailedDependency returns 424
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_scan_error_device_udn_not_found_message() {
        let error = ScanError::DeviceUdnNotFound {
            device_udn: "uuid:test-device".to_string(),
        };
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_scan_error_device_url_not_found_message() {
        let error = ScanError::DeviceUrlNotFound {
            device_url: "http://192.168.1.100:8080".to_string(),
        };
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_scan_error_service_id_not_found() {
        let error = ScanError::ServiceIdNotFound {
            service_id: "urn:upnp-org:serviceId:AVTransport".to_string(),
        };
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_scan_error_media_renderer_not_found() {
        let error = ScanError::MediaRendererNotFound;
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_upnp_device_scanner_error_no_outputs_converts_to_failed_dependency() {
        let error = UpnpDeviceScannerError::NoOutputs;
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }

    #[test_log::test]
    fn test_action_error_roxml_converts_to_failed_dependency() {
        // Create an actual roxmltree error by parsing invalid XML
        let parse_result = roxmltree::Document::parse("<invalid");
        let roxml_error = parse_result.unwrap_err();
        let error = ActionError::Roxml(roxml_error);
        let actix_error: actix_web::Error = error.into();
        let response = actix_error.error_response();
        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::FAILED_DEPENDENCY
        );
    }
}