switchy_upnp 0.3.0

Switchy UPnP package
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
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
//! UPnP/DLNA device discovery and control library.
//!
//! This crate provides functionality for discovering and controlling UPnP/DLNA devices
//! on the local network. It supports device scanning, media playback control, volume
//! management, and event subscriptions for `UPnP` `AVTransport` and `RenderingControl` services.
//!
//! # Features
//!
//! * `api` - Actix-web API endpoints for `UPnP` operations
//! * `listener` - Event listener service for monitoring `UPnP` device state changes
//! * `player` - `UPnP` player implementation for media playback
//! * `openapi` - OpenAPI/utoipa schema support
//! * `simulator` - Simulated `UPnP` devices for testing
//!
//! # Examples
//!
//! Scanning for `UPnP` devices on the network:
//!
//! ```rust,no_run
//! # use switchy_upnp::{scan_devices, devices};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Scan the network for UPnP devices
//! scan_devices().await?;
//!
//! // Get the list of discovered devices
//! let upnp_devices = devices().await;
//! for device in upnp_devices {
//!     println!("Found device: {} ({})", device.name, device.udn);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Controlling playback on a `UPnP` device:
//!
//! ```rust,no_run
//! # use switchy_upnp::{get_device_and_service, play, pause, set_volume};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let device_udn = "uuid:device-id";
//! # let service_id = "urn:upnp-org:serviceId:AVTransport";
//! // Get device and AVTransport service
//! let (device, service) = get_device_and_service(device_udn, service_id)?;
//! let url = device.url();
//!
//! // Start playback
//! play(&service, url, 0, 1.0).await?;
//!
//! // Pause playback
//! pause(&service, url, 0).await?;
//!
//! // Set volume to 50%
//! # let rendering_control_service = service;
//! set_volume(&rendering_control_service, url, 0, "Master", 50).await?;
//! # Ok(())
//! # }
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions, clippy::struct_field_names)]

#[cfg(feature = "api")]
pub mod api;

pub mod models;

mod scanner;

use async_recursion::async_recursion;
use futures::prelude::*;
use itertools::Itertools;
use models::{UpnpDevice, UpnpService};
pub use rupnp::{Device, DeviceSpec, Service, http::Uri, ssdp::SearchTarget};
use scanner::UpnpScanner;
use serde::Serialize;
use std::{
    collections::BTreeMap,
    sync::{Arc, LazyLock},
    time::Duration,
};
use switchy_async::sync::Mutex;
use thiserror::Error;

mod cache {
    //! Internal cache for storing discovered `UPnP` devices and their services.
    //!
    //! This module maintains mappings of devices by both URL and UDN (Unique Device Name)
    //! to enable fast lookups during `UPnP` operations.

    use std::{
        collections::BTreeMap,
        sync::{LazyLock, RwLock},
    };

    use rupnp::{Device, Service};

    use crate::ScanError;

    /// Mapping of a device and its associated services.
    #[derive(Debug, Clone)]
    struct DeviceMapping {
        device: Device,
        services: BTreeMap<String, Service>,
    }

    static DEVICE_URL_MAPPINGS: LazyLock<RwLock<BTreeMap<String, DeviceMapping>>> =
        LazyLock::new(|| RwLock::new(BTreeMap::new()));

    static DEVICE_MAPPINGS: LazyLock<RwLock<BTreeMap<String, DeviceMapping>>> =
        LazyLock::new(|| RwLock::new(BTreeMap::new()));

    /// Retrieves a cached device by its URL.
    ///
    /// # Errors
    ///
    /// * If no device with the specified URL is found in the cache
    pub fn get_device_from_url(url: &str) -> Result<Device, ScanError> {
        Ok(DEVICE_MAPPINGS
            .read()
            .unwrap()
            .get(url)
            .ok_or_else(|| ScanError::DeviceUrlNotFound {
                device_url: url.to_string(),
            })?
            .device
            .clone())
    }

    /// Retrieves a cached device by its UDN.
    ///
    /// # Errors
    ///
    /// * If no device with the specified UDN is found in the cache
    pub fn get_device(udn: &str) -> Result<Device, ScanError> {
        Ok(DEVICE_MAPPINGS
            .read()
            .unwrap()
            .get(udn)
            .ok_or_else(|| ScanError::DeviceUdnNotFound {
                device_udn: udn.to_string(),
            })?
            .device
            .clone())
    }

    /// Inserts a device into the cache, indexed by both URL and UDN.
    pub fn insert_device(device: Device) {
        DEVICE_URL_MAPPINGS.write().unwrap().insert(
            device.url().to_string(),
            DeviceMapping {
                device: device.clone(),
                services: BTreeMap::new(),
            },
        );
        DEVICE_MAPPINGS.write().unwrap().insert(
            device.udn().to_owned(),
            DeviceMapping {
                device,
                services: BTreeMap::new(),
            },
        );
    }

    /// Retrieves a cached service by device UDN and service ID.
    ///
    /// # Errors
    ///
    /// * If no device with the specified UDN is found in the cache
    /// * If no service with the specified service ID is found on the device
    pub fn get_service(device_udn: &str, service_id: &str) -> Result<Service, ScanError> {
        Ok(DEVICE_MAPPINGS
            .read()
            .unwrap()
            .get(device_udn)
            .ok_or_else(|| ScanError::DeviceUdnNotFound {
                device_udn: device_udn.to_string(),
            })?
            .services
            .get(service_id)
            .ok_or_else(|| ScanError::ServiceIdNotFound {
                service_id: service_id.to_string(),
            })?
            .clone())
    }

    /// Retrieves a cached device and service by device UDN and service ID.
    ///
    /// # Errors
    ///
    /// * If no device with the specified UDN is found in the cache
    /// * If no service with the specified service ID is found on the device
    pub fn get_device_and_service(
        device_udn: &str,
        service_id: &str,
    ) -> Result<(Device, Service), ScanError> {
        let devices = DEVICE_MAPPINGS.read().unwrap();
        let device = devices
            .get(device_udn)
            .ok_or_else(|| ScanError::DeviceUdnNotFound {
                device_udn: device_udn.to_string(),
            })?;
        let resp = (
            device.device.clone(),
            device
                .services
                .get(service_id)
                .ok_or_else(|| ScanError::ServiceIdNotFound {
                    service_id: service_id.to_string(),
                })?
                .clone(),
        );
        drop(devices);

        Ok(resp)
    }

    /// Retrieves a cached device and service by device URL and service ID.
    ///
    /// # Errors
    ///
    /// * If no device with the specified URL is found in the cache
    /// * If no service with the specified service ID is found on the device
    pub fn get_device_and_service_from_url(
        device_url: &str,
        service_id: &str,
    ) -> Result<(Device, Service), ScanError> {
        let devices = DEVICE_URL_MAPPINGS.read().unwrap();
        let device = devices
            .get(device_url)
            .ok_or_else(|| ScanError::DeviceUrlNotFound {
                device_url: device_url.to_string(),
            })?;
        let resp = (
            device.device.clone(),
            device
                .services
                .get(service_id)
                .ok_or_else(|| ScanError::ServiceIdNotFound {
                    service_id: service_id.to_string(),
                })?
                .clone(),
        );
        drop(devices);

        Ok(resp)
    }

    /// Inserts a service into the cache for a specific device.
    ///
    /// The service is added to both the URL-indexed and UDN-indexed device mappings.
    pub fn insert_service(device: &Device, service: &Service) {
        if let Some(device_mapping) = DEVICE_URL_MAPPINGS
            .write()
            .as_mut()
            .unwrap()
            .get_mut(device.url().to_string().as_str())
        {
            device_mapping
                .services
                .insert(service.service_id().to_owned(), service.clone());
        }
        if let Some(device_mapping) = DEVICE_MAPPINGS
            .write()
            .as_mut()
            .unwrap()
            .get_mut(device.udn())
        {
            device_mapping
                .services
                .insert(service.service_id().to_owned(), service.clone());
        }
    }
}

/// Retrieves a cached `UPnP` device by its unique device name (UDN).
///
/// # Errors
///
/// * If a `Device` is not found with the given `udn`
pub fn get_device(udn: &str) -> Result<Device, ScanError> {
    cache::get_device(udn)
}

/// Retrieves a cached `UPnP` service by device UDN and service ID.
///
/// # Errors
///
/// * If a `Service` is not found with the given `device_udn` and `service_id`
pub fn get_service(device_udn: &str, service_id: &str) -> Result<Service, ScanError> {
    cache::get_service(device_udn, service_id)
}

/// Retrieves a cached `UPnP` device and service by device UDN and service ID.
///
/// # Errors
///
/// * If a `Device` or `Service` is not found with the given `device_udn` and `service_id`
pub fn get_device_and_service(
    device_udn: &str,
    service_id: &str,
) -> Result<(Device, Service), ScanError> {
    cache::get_device_and_service(device_udn, service_id)
}

/// Retrieves a cached `UPnP` device by its URL.
///
/// # Errors
///
/// * If a `Device` is not found with the given `url`
pub fn get_device_from_url(url: &str) -> Result<Device, ScanError> {
    cache::get_device_from_url(url)
}

/// Retrieves a cached `UPnP` device and service by device URL and service ID.
///
/// # Errors
///
/// * If a `Device` or `Service` is not found with the given `device_url` and `service_id`
pub fn get_device_and_service_from_url(
    device_url: &str,
    service_id: &str,
) -> Result<(Device, Service), ScanError> {
    cache::get_device_and_service_from_url(device_url, service_id)
}

/// Errors that can occur when executing `UPnP` actions.
#[derive(Debug, Error)]
pub enum ActionError {
    /// Error parsing XML response from `UPnP` device.
    #[error(transparent)]
    Roxml(#[from] roxmltree::Error),
    /// Error from the underlying `UPnP` library.
    #[error(transparent)]
    Rupnp(#[from] rupnp::Error),
    /// Required property missing from `UPnP` action response.
    #[error("Missing property \"{0}\"")]
    MissingProperty(String),
}

/// Errors that can occur when scanning for `UPnP` devices and services.
#[derive(Debug, Error)]
pub enum ScanError {
    /// `RenderingControl` service not found on the device.
    #[error("Failed to find `RenderingControl` service")]
    RenderingControlNotFound,
    /// `MediaRenderer` service not found on the device.
    #[error("Failed to find MediaRenderer service")]
    MediaRendererNotFound,
    /// `UPnP` device with the specified UDN not found in cache.
    #[error("Failed to find UPnP Device device_udn={device_udn}")]
    DeviceUdnNotFound {
        /// The device UDN that was not found.
        device_udn: String,
    },
    /// `UPnP` device with the specified URL not found in cache.
    #[error("Failed to find UPnP Device device_url={device_url}")]
    DeviceUrlNotFound {
        /// The device URL that was not found.
        device_url: String,
    },
    /// `UPnP` service with the specified service ID not found on the device.
    #[error("Failed to find UPnP Service service_id={service_id}")]
    ServiceIdNotFound {
        /// The service ID that was not found.
        service_id: String,
    },
    /// Error from the underlying `UPnP` library.
    #[error(transparent)]
    Rupnp(#[from] rupnp::Error),
}

/// Converts a duration string in the format "HH:MM:SS" to seconds.
///
/// # Panics
///
/// * If the duration str is an invalid format
#[must_use]
pub fn str_to_duration(duration: &str) -> u32 {
    let time_components = duration
        .split(':')
        .map(str::parse)
        .collect::<Result<Vec<u32>, std::num::ParseIntError>>()
        .expect("Failed to parse time...");

    time_components[0] * 60 * 60 + time_components[1] * 60 + time_components[2]
}

/// Converts a duration in seconds to a string in the format "HH:MM:SS".
#[must_use]
pub fn duration_to_string(duration: u32) -> String {
    format!(
        "{:0>2}:{:0>2}:{:0>2}",
        (duration / 60) / 60,
        (duration / 60) % 60,
        duration % 60
    )
}

static DIDL_LITE_NS: &str = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
static UPNP_NS: &str = "urn:schemas-upnp-org:metadata-1-0/upnp/";
static DC_NS: &str = "http://purl.org/dc/elements/1.1/";
static SEC_NS: &str = "http://www.sec.co.kr/";

/// Sets the AV transport URI for a `UPnP` device with metadata.
///
/// # Errors
///
/// * If the action failed to execute
///
/// # Examples
///
/// ```rust,no_run
/// # use switchy_upnp::{get_device_and_service, set_av_transport_uri};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let device_udn = "uuid:device-id";
/// let (device, service) =
///     get_device_and_service(device_udn, "urn:upnp-org:serviceId:AVTransport")?;
/// set_av_transport_uri(
///     &service,
///     device.url(),
///     0,
///     "https://example.com/track.flac",
///     "flac",
///     Some("Track Title"),
///     Some("Creator"),
///     Some("Artist"),
///     Some("Album"),
///     Some(1),
///     Some(211),
///     None,
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn set_av_transport_uri(
    service: &Service,
    device_url: &Uri,
    instance_id: u32,
    transport_uri: &str,
    format: &str,
    title: Option<&str>,
    creator: Option<&str>,
    artist: Option<&str>,
    album: Option<&str>,
    original_track_number: Option<u32>,
    duration: Option<u32>,
    size: Option<u64>,
) -> Result<BTreeMap<String, String>, ActionError> {
    static BRACKET_WHITESPACE: LazyLock<regex::Regex> =
        LazyLock::new(|| regex::Regex::new(r">\s+<").expect("Invalid Regex"));
    static BETWEEN_WHITESPACE: LazyLock<regex::Regex> =
        LazyLock::new(|| regex::Regex::new(r"\s{2,}").expect("Invalid Regex"));

    // Remove extraneous whitespace
    fn compress_xml(xml: &str) -> String {
        BETWEEN_WHITESPACE
            .replace_all(
                BRACKET_WHITESPACE.replace_all(xml.trim(), "><").as_ref(),
                " ",
            )
            .to_string()
            .replace(['\r', '\n'], "")
            .replace("\" >", "\">")
    }

    fn escape_xml(xml: &str) -> String {
        xml::escape::escape_str_attribute(xml).to_string()
    }

    let headers = "*";

    let transport_uri = xml::escape::escape_str_attribute(transport_uri);

    let metadata = format!(
        r#"
        <DIDL-Lite
            xmlns="{DIDL_LITE_NS}"
            xmlns:dc="{DC_NS}"
            xmlns:sec="{SEC_NS}"
            xmlns:upnp="{UPNP_NS}">
            <item id="0" parentID="-1" restricted="false">
                <upnp:class>object.item.audioItem.musicTrack</upnp:class>
                {title}
                {creator}
                {artist}
                {album}
                {original_track_number}
                <res{duration}{size} protocolInfo="http-get:*:audio/{format}:{headers}">{transport_uri}</res>
            </item>
        </DIDL-Lite>
        "#,
        title = title
            .map(xml::escape::escape_str_attribute)
            .map_or_else(String::new, |x| format!("<dc:title>{x}</dc:title>")),
        creator = creator
            .map(xml::escape::escape_str_attribute)
            .map_or_else(String::new, |x| format!("<dc:creator>{x}</dc:creator>")),
        artist = artist
            .map(xml::escape::escape_str_attribute)
            .map_or_else(String::new, |x| format!("<upnp:artist>{x}</upnp:artist>")),
        album = album
            .map(xml::escape::escape_str_attribute)
            .map_or_else(String::new, |x| format!("<upnp:album>{x}</upnp:album>")),
        original_track_number = original_track_number.map_or_else(String::new, |x| format!(
            "<upnp:originalTrackNumber>{x}</upnp:originalTrackNumber>"
        )),
        duration = duration.map_or_else(String::new, |x| format!(
            " duration=\"{}\"",
            duration_to_string(x)
        )),
        size = size.map_or_else(String::new, |x| format!(" size=\"{x}\"")),
    );

    let metadata = escape_xml(&compress_xml(&metadata));

    let args = format!(
        r"
        <InstanceID>{instance_id}</InstanceID>
        <CurrentURI>{transport_uri}</CurrentURI>
        <CurrentURIMetaData>{metadata}</CurrentURIMetaData>
        "
    );
    let args = compress_xml(&args);
    log::debug!("set_av_transport_uri args={args}");

    Ok(service
        .action(device_url, "SetAVTransportURI", &args)
        .await?
        .into_iter()
        .collect())
}

/// Parsed track metadata from `UPnP` `DIDL-Lite` XML.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TrackMetadata {
    /// List of track metadata items parsed from the XML.
    items: Vec<TrackMetadataItem>,
}

/// A single track metadata item from `UPnP` `DIDL-Lite` XML.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TrackMetadataItem {
    /// `UPnP` class of the item (e.g., "object.item.audioItem.musicTrack").
    upnp_class: Option<String>,
    /// Artist name from `UPnP` metadata.
    upnp_artist: Option<String>,
    /// Album name from `UPnP` metadata.
    upnp_album: Option<String>,
    /// Original track number from `UPnP` metadata.
    upnp_original_track_number: Option<String>,
    /// Track title from Dublin Core metadata.
    dc_title: Option<String>,
    /// Creator name from Dublin Core metadata.
    dc_creator: Option<String>,
    /// Resource information for the track.
    res: TrackMetadataItemResource,
}

/// Resource information for a track metadata item.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TrackMetadataItemResource {
    /// Duration of the track in seconds.
    duration: Option<u32>,
    /// Protocol information describing the resource format.
    protocol_info: Option<String>,
    /// URI of the media resource.
    source: String,
}

// "<DIDL-Lite xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:sec=\"http://www.sec.co.kr/\" xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\">
//     <item id=\"0\" parentID=\"-1\" restricted=\"false\">
//         <upnp:class>object.item.audioItem.musicTrack</upnp:class>
//         <dc:title>Friday</dc:title>
//         <dc:creator>Rebecca Black</dc:creator>
//         <upnp:artist>Rebecca Black</upnp:artist>
//         <upnp:album>Friday</upnp:album>
//         <upnp:originalTrackNumber>1</upnp:originalTrackNumber>
//         <res duration=\"00:03:31\" protocolInfo=\"http-get:*:audio/flac:*\">http://192.168.254.137:8001/track?trackId=12911&amp;source=LIBRARY</res>
//     </item>
// </DIDL-Lite>"
fn parse_track_metadata(track_metadata: &str) -> Result<TrackMetadata, ActionError> {
    let doc = roxmltree::Document::parse(track_metadata)?;

    let items = doc
        .descendants()
        .filter(|x| x.tag_name().name().to_lowercase() == "item")
        .map(|x| {
            let upnp_class = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == UPNP_NS)
                    && x.tag_name().name().to_lowercase() == "class"
            });
            let upnp_artist = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == UPNP_NS)
                    && x.tag_name().name().to_lowercase() == "artist"
            });
            let upnp_album = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == UPNP_NS)
                    && x.tag_name().name().to_lowercase() == "album"
            });
            let upnp_original_track_number = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == UPNP_NS)
                    && x.tag_name().name().to_lowercase() == "originaltracknumber"
            });
            let dc_title = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == DC_NS)
                    && x.tag_name().name().to_lowercase() == "title"
            });
            let dc_creator = x.descendants().find(|x| {
                x.tag_name().namespace().is_some_and(|n| n == DC_NS)
                    && x.tag_name().name().to_lowercase() == "creator"
            });
            let res = x
                .descendants()
                .find(|x| {
                    x.tag_name().namespace().is_some_and(|n| n == DIDL_LITE_NS)
                        && x.tag_name().name().to_lowercase() == "res"
                })
                .ok_or_else(|| ActionError::MissingProperty("Missing res".into()))?;
            Ok(TrackMetadataItem {
                upnp_class: upnp_class.and_then(|x| x.text()).map(ToOwned::to_owned),
                upnp_artist: upnp_artist.and_then(|x| x.text()).map(ToOwned::to_owned),
                upnp_album: upnp_album.and_then(|x| x.text()).map(ToOwned::to_owned),
                upnp_original_track_number: upnp_original_track_number
                    .and_then(|x| x.text())
                    .map(ToOwned::to_owned),
                dc_title: dc_title.and_then(|x| x.text()).map(ToOwned::to_owned),
                dc_creator: dc_creator.and_then(|x| x.text()).map(ToOwned::to_owned),
                res: TrackMetadataItemResource {
                    duration: res.attribute("duration").map(str_to_duration),
                    protocol_info: res.attribute("protocolInfo").map(ToOwned::to_owned),
                    source: res
                        .text()
                        .ok_or_else(|| ActionError::MissingProperty("Missing res value".into()))?
                        .to_owned(),
                },
            })
        })
        .collect::<Result<Vec<_>, ActionError>>();

    Ok(TrackMetadata { items: items? })
}

/// `UPnP` `AVTransport` service transport information.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TransportInfo {
    /// Current transport status (e.g., "OK", "`ERROR_OCCURRED`").
    pub current_transport_status: String,
    /// Current transport state (e.g., "PLAYING", "`PAUSED_PLAYBACK`", "STOPPED").
    pub current_transport_state: String,
    /// Current playback speed (typically "1" for normal speed).
    pub current_speed: String,
}

/// Retrieves transport information from a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
/// * If the transport info is missing the required properties
pub async fn get_transport_info(
    service: &Service,
    url: &Uri,
    instance_id: u32,
) -> Result<TransportInfo, ActionError> {
    let map = service
        .action(
            url,
            "GetTransportInfo",
            &format!("<InstanceID>{instance_id}</InstanceID>"),
        )
        .await?;

    Ok(TransportInfo {
        current_transport_status: map
            .get("CurrentTransportStatus")
            .ok_or(ActionError::MissingProperty(
                "CurrentTransportStatus".into(),
            ))?
            .clone(),
        current_transport_state: map
            .get("CurrentTransportState")
            .ok_or(ActionError::MissingProperty("CurrentTransportState".into()))?
            .clone(),
        current_speed: map
            .get("CurrentSpeed")
            .ok_or(ActionError::MissingProperty("TrackURI".into()))?
            .clone(),
    })
}

/// `UPnP` `AVTransport` service position information.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PositionInfo {
    /// Current track number in the playlist (1-based).
    pub track: u32,
    /// Relative playback position in seconds within the current track.
    pub rel_time: u32,
    /// Absolute playback position in seconds across the entire playlist.
    pub abs_time: u32,
    /// URI of the current track.
    pub track_uri: String,
    /// Metadata for the current track.
    pub track_metadata: TrackMetadata,
    /// Relative counter value.
    pub rel_count: u32,
    /// Absolute counter value.
    pub abs_count: u32,
    /// Total duration of the current track in seconds.
    pub track_duration: u32,
}

/// Retrieves position information from a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
/// * If the position info is missing the required properties
pub async fn get_position_info(
    service: &Service,
    url: &Uri,
    instance_id: u32,
) -> Result<PositionInfo, ActionError> {
    let map = service
        .action(
            url,
            "GetPositionInfo",
            &format!("<InstanceID>{instance_id}</InstanceID>"),
        )
        .await?;

    Ok(PositionInfo {
        abs_time: str_to_duration(
            map.get("AbsTime")
                .ok_or(ActionError::MissingProperty("AbsTime".into()))?,
        ),
        rel_time: str_to_duration(
            map.get("RelTime")
                .ok_or(ActionError::MissingProperty("RelTime".into()))?,
        ),
        track_duration: str_to_duration(
            map.get("TrackDuration")
                .ok_or(ActionError::MissingProperty("TrackDuration".into()))?,
        ),
        abs_count: map
            .get("AbsCount")
            .ok_or(ActionError::MissingProperty("AbsCount".into()))?
            .parse::<u32>()
            .map_err(|e| ActionError::MissingProperty(format!("AbsCount (\"{e:?}\")")))?,
        rel_count: map
            .get("RelCount")
            .ok_or(ActionError::MissingProperty("RelCount".into()))?
            .parse::<u32>()
            .map_err(|e| ActionError::MissingProperty(format!("RelCount (\"{e:?}\")")))?,
        track: map
            .get("Track")
            .ok_or(ActionError::MissingProperty("Track".into()))?
            .parse::<u32>()
            .map_err(|e| ActionError::MissingProperty(format!("Track (\"{e:?}\")")))?,
        track_uri: map
            .get("TrackURI")
            .ok_or(ActionError::MissingProperty("TrackURI".into()))?
            .clone(),
        track_metadata: parse_track_metadata(
            map.get("TrackMetaData")
                .ok_or(ActionError::MissingProperty("TrackMetaData".into()))?,
        )?,
    })
}

/// Seeks to a specific position in the current media on a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn seek(
    service: &Service,
    url: &Uri,
    instance_id: u32,
    unit: &str,
    target: u32,
) -> Result<BTreeMap<String, String>, ActionError> {
    let target_str = duration_to_string(target);
    log::trace!("seek: seeking to target={target_str} instance_id={instance_id} unit={unit}");

    Ok(service
        .action(
            url,
            "Seek",
            &format!(
                r"
                <InstanceID>{instance_id}</InstanceID>
                <Unit>{unit}</Unit>
                <Target>{target_str}</Target>
                "
            ),
        )
        .await?
        .into_iter()
        .collect())
}

/// Retrieves the volume from a `UPnP` `RenderingControl` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn get_volume(
    service: &Service,
    url: &Uri,
    instance_id: u32,
    channel: &str,
) -> Result<BTreeMap<String, String>, ActionError> {
    Ok(service
        .action(
            url,
            "GetVolume",
            &format!("<InstanceID>{instance_id}</InstanceID><Channel>{channel}</Channel>"),
        )
        .await?
        .into_iter()
        .collect())
}

/// Sets the volume on a `UPnP` `RenderingControl` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn set_volume(
    service: &Service,
    url: &Uri,
    instance_id: u32,
    channel: &str,
    volume: u8,
) -> Result<BTreeMap<String, String>, ActionError> {
    Ok(service
        .action(
            url,
            "SetVolume",
            &format!("<InstanceID>{instance_id}</InstanceID><Channel>{channel}</Channel><DesiredVolume>{volume}</DesiredVolume>"),
        )
        .await?.into_iter()
        .collect())
}

/// `UPnP` `AVTransport` service media information.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MediaInfo {
    /// Total duration of the media in seconds.
    media_duration: u32,
    /// Recording medium type (e.g., "`NOT_IMPLEMENTED`").
    record_medium: String,
    /// Write status of the media (e.g., "`NOT_IMPLEMENTED`").
    write_status: String,
    /// Metadata for the current media URI.
    current_uri_metadata: TrackMetadata,
    /// Number of tracks in the current playlist.
    nr_tracks: u32,
    /// Playback medium type (e.g., "NETWORK", "NONE").
    play_medium: String,
    /// URI of the current media.
    current_uri: String,
}

/// Retrieves media information from a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
/// * If the media info is missing the required properties
pub async fn get_media_info(
    service: &Service,
    url: &Uri,
    instance_id: u32,
) -> Result<MediaInfo, ActionError> {
    let map = service
        .action(
            url,
            "GetMediaInfo",
            &format!("<InstanceID>{instance_id}</InstanceID>"),
        )
        .await?;

    Ok(MediaInfo {
        media_duration: str_to_duration(
            map.get("MediaDuration")
                .ok_or(ActionError::MissingProperty("MediaDuration".into()))?,
        ),
        record_medium: map
            .get("RecordMedium")
            .ok_or(ActionError::MissingProperty("MediaDuration".into()))?
            .clone(),
        write_status: map
            .get("WriteStatus")
            .ok_or(ActionError::MissingProperty("WriteStatus".into()))?
            .clone(),
        current_uri_metadata: parse_track_metadata(
            map.get("CurrentURIMetaData")
                .ok_or(ActionError::MissingProperty("CurrentURIMetaData".into()))?,
        )?,
        nr_tracks: map
            .get("NrTracks")
            .ok_or(ActionError::MissingProperty("NrTracks".into()))?
            .parse::<u32>()
            .map_err(|e| ActionError::MissingProperty(format!("NrTracks (\"{e:?}\")")))?,
        play_medium: map
            .get("PlayMedium")
            .ok_or(ActionError::MissingProperty("PlayMedium".into()))?
            .clone(),
        current_uri: map
            .get("CurrentURI")
            .ok_or(ActionError::MissingProperty("CurrentURI".into()))?
            .clone(),
    })
}

/// Subscribes to events from a `UPnP` service.
///
/// # Errors
///
/// * If the subscription failed to execute
pub async fn subscribe_events(
    service: &Service,
    url: &Uri,
) -> Result<
    (
        String,
        impl Stream<Item = Result<BTreeMap<String, String>, rupnp::Error>> + use<>,
    ),
    ScanError,
> {
    let (url, stream) = service.subscribe(url, 300).await?;

    Ok((url, stream.map(|x| x.map(|x| x.into_iter().collect()))))
}

/// Starts playback on a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn play(
    service: &Service,
    url: &Uri,
    instance_id: u32,
    speed: f64,
) -> Result<BTreeMap<String, String>, ActionError> {
    Ok(service
        .action(
            url,
            "Play",
            &format!("<InstanceID>{instance_id}</InstanceID><Speed>{speed}</Speed>"),
        )
        .await?
        .into_iter()
        .collect())
}

/// Pauses playback on a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn pause(
    service: &Service,
    url: &Uri,
    instance_id: u32,
) -> Result<BTreeMap<String, String>, ActionError> {
    Ok(service
        .action(
            url,
            "Pause",
            &format!("<InstanceID>{instance_id}</InstanceID>"),
        )
        .await?
        .into_iter()
        .collect())
}

/// Stops playback on a `UPnP` `AVTransport` service.
///
/// # Errors
///
/// * If the action failed to execute
pub async fn stop(
    service: &Service,
    url: &Uri,
    instance_id: u32,
) -> Result<BTreeMap<String, String>, ActionError> {
    Ok(service
        .action(
            url,
            "Stop",
            &format!("<InstanceID>{instance_id}</InstanceID>"),
        )
        .await?
        .into_iter()
        .collect())
}

/// Scans and retrieves information about a `UPnP` service.
///
/// # Errors
///
/// * If failed to scan for `UPnP` services
pub async fn scan_service(
    url: Option<&Uri>,
    service: &Service,
    path: Option<&str>,
) -> Result<UpnpService, ScanError> {
    let path = path.unwrap_or_default();

    log::debug!(
        "\n\
        {path}Scanning service:\n\t\
        {path}service_type={}\n\t\
        {path}service_id={}\n\t\
        ",
        service.service_type(),
        service.service_id(),
    );

    log::trace!(
        "service '{}' scpd={}",
        service.service_id(),
        if let Some(url) = url {
            format!("{:?}", service.scpd(url).await.ok())
        } else {
            "N/A".to_string()
        }
    );

    Ok(service.into())
}

/// Scans a `UPnP` device and its sub-devices, returning information about all discovered devices.
///
/// # Errors
///
/// * If failed to scan for `UPnP` devices
#[async_recursion]
pub async fn scan_device(
    device: Option<Device>,
    spec: &DeviceSpec,
    path: Option<&str>,
) -> Result<Vec<UpnpDevice>, ScanError> {
    let path = path.unwrap_or_default();

    log::debug!(
        "\n\
        {path}Scanning device: {}\n\t\
        {path}url={:?}\n\t\
        {path}manufacturer={}\n\t\
        {path}manufacturer_url={}\n\t\
        {path}model_name={}\n\t\
        {path}model_description={}\n\t\
        {path}model_number={}\n\t\
        {path}model_url={}\n\t\
        {path}serial_number={}\n\t\
        {path}udn={}\n\t\
        {path}upc={}\
        ",
        spec.friendly_name(),
        device.as_ref().map(rupnp::Device::url),
        spec.manufacturer(),
        spec.manufacturer_url().unwrap_or("N/A"),
        spec.model_name(),
        spec.model_description().unwrap_or("N/A"),
        spec.model_number().unwrap_or("N/A"),
        spec.model_url().unwrap_or("N/A"),
        spec.serial_number().unwrap_or("N/A"),
        spec.udn(),
        spec.upc().unwrap_or("N/A"),
    );

    let upnp_device: UpnpDevice = spec.into();
    let mut upnp_services = vec![];

    let services = spec.services();

    if services.is_empty() {
        log::debug!("no services for {}", spec.friendly_name());
    } else {
        let path = format!("{path}\t");
        for service in services {
            if let Some(device) = &device {
                cache::insert_service(device, service);
            }
            upnp_services.push(
                scan_service(
                    device.as_ref().map(rupnp::Device::url),
                    service,
                    Some(&path),
                )
                .await?,
            );
        }
    }

    let mut upnp_devices = vec![upnp_device.with_services(upnp_services)];

    let sub_devices = spec.devices();

    if sub_devices.is_empty() {
        log::debug!("no sub-devices for {}", spec.friendly_name());
    } else {
        let path = format!("{path}\t");
        for sub in sub_devices {
            // FIXME: should somehow insert sub-devices into the cache
            upnp_devices.extend_from_slice(&scan_device(None, sub, Some(&path)).await?);
        }
    }

    Ok(upnp_devices)
}

static UPNP_DEVICE_SCANNER: LazyLock<Arc<Mutex<UpnpDeviceScanner>>> =
    LazyLock::new(|| Arc::new(Mutex::new(UpnpDeviceScanner::new())));

static SCANNER: LazyLock<Box<dyn UpnpScanner>> = LazyLock::new(|| {
    #[cfg(feature = "simulator")]
    {
        Box::new(scanner::simulator::SimulatorScanner)
    }

    #[cfg(not(feature = "simulator"))]
    {
        Box::new(scanner::RupnpScanner)
    }
});

/// Scans the network for `UPnP` devices and caches them.
///
/// # Errors
///
/// * If failed to scan for `UPnP` devices
pub async fn scan_devices() -> Result<(), UpnpDeviceScannerError> {
    UPNP_DEVICE_SCANNER.lock().await.scan().await
}

/// Returns the list of cached `UPnP` devices from the last scan.
#[must_use]
pub async fn devices() -> Vec<UpnpDevice> {
    UPNP_DEVICE_SCANNER.lock().await.devices.clone()
}

/// Scanner for discovering `UPnP` devices on the network.
#[derive(Default)]
pub struct UpnpDeviceScanner {
    scanning: bool,
    /// List of discovered `UPnP` devices from the most recent scan.
    pub devices: Vec<UpnpDevice>,
}

/// Errors that can occur when scanning for `UPnP` devices.
#[allow(dead_code)]
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Error)]
pub enum UpnpDeviceScannerError {
    /// No audio outputs are available.
    #[error("No outputs available")]
    NoOutputs,
    /// Error from the underlying `UPnP` library.
    #[error(transparent)]
    Rupnp(#[from] rupnp::Error),
    /// Error scanning for `UPnP` devices or services.
    #[error(transparent)]
    Scan(#[from] ScanError),
}

impl UpnpDeviceScanner {
    /// Creates a new `UPnP` device scanner.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Scans the network for `UPnP` devices and populates the device list.
    ///
    /// This method discovers devices on the local network, caches them, and stores
    /// their information in the scanner's device list. If devices have already been
    /// scanned or a scan is in progress, this method returns immediately without
    /// performing another scan.
    ///
    /// # Errors
    ///
    /// * If failed to scan for `UPnP` devices
    pub async fn scan(&mut self) -> Result<(), UpnpDeviceScannerError> {
        if self.scanning || !self.devices.is_empty() {
            return Ok(());
        }

        self.scanning = true;

        let search_target = SearchTarget::RootDevice;
        let devices = SCANNER
            .discover(&search_target, Duration::from_secs(3))
            .await?;
        pin_utils::pin_mut!(devices);

        let mut upnp_devices = vec![];

        loop {
            match devices.try_next().await {
                Ok(Some(device)) => {
                    cache::insert_device(device.clone());
                    let spec: &DeviceSpec = &device;
                    upnp_devices
                        .extend_from_slice(&scan_device(Some(device.clone()), spec, None).await?);
                }
                Ok(None) => {
                    break;
                }
                Err(e) => {
                    log::error!("Received error device response: {e:?}");
                }
            }
        }

        if upnp_devices.is_empty() {
            log::debug!("No `UPnP` devices discovered");
        }

        self.devices = upnp_devices
            .into_iter()
            .unique_by(|x| x.udn.clone())
            .collect::<Vec<_>>();

        self.scanning = false;

        Ok(())
    }
}

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

    #[test_log::test]
    fn test_str_to_duration_valid_formats() {
        assert_eq!(str_to_duration("00:00:00"), 0);
        assert_eq!(str_to_duration("00:00:01"), 1);
        assert_eq!(str_to_duration("00:01:00"), 60);
        assert_eq!(str_to_duration("01:00:00"), 3600);
        assert_eq!(str_to_duration("00:03:31"), 211);
        assert_eq!(str_to_duration("01:30:45"), 5445);
        assert_eq!(str_to_duration("10:15:20"), 36_920);
    }

    #[test_log::test]
    fn test_duration_to_string_various_durations() {
        assert_eq!(duration_to_string(0), "00:00:00");
        assert_eq!(duration_to_string(1), "00:00:01");
        assert_eq!(duration_to_string(60), "00:01:00");
        assert_eq!(duration_to_string(3600), "01:00:00");
        assert_eq!(duration_to_string(211), "00:03:31");
        assert_eq!(duration_to_string(5445), "01:30:45");
        assert_eq!(duration_to_string(36_920), "10:15:20");
    }

    #[test_log::test]
    fn test_duration_roundtrip_conversion() {
        let test_cases = vec![
            "00:00:00", "00:00:30", "00:05:45", "01:23:45", "10:00:00", "23:59:59",
        ];

        for original in test_cases {
            let seconds = str_to_duration(original);
            let converted = duration_to_string(seconds);
            assert_eq!(
                original, converted,
                "Roundtrip conversion failed for {original}"
            );
        }
    }

    #[test_log::test]
    fn test_parse_track_metadata_complete() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sec="http://www.sec.co.kr/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">
            <item id="0" parentID="-1" restricted="false">
                <upnp:class>object.item.audioItem.musicTrack</upnp:class>
                <dc:title>Friday</dc:title>
                <dc:creator>Rebecca Black</dc:creator>
                <upnp:artist>Rebecca Black</upnp:artist>
                <upnp:album>Friday</upnp:album>
                <upnp:originalTrackNumber>1</upnp:originalTrackNumber>
                <res duration="00:03:31" protocolInfo="http-get:*:audio/flac:*">http://192.168.1.1:8001/track?trackId=123</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse metadata");
        assert_eq!(result.items.len(), 1);

        let item = &result.items[0];
        assert_eq!(
            item.upnp_class.as_deref(),
            Some("object.item.audioItem.musicTrack")
        );
        assert_eq!(item.dc_title.as_deref(), Some("Friday"));
        assert_eq!(item.dc_creator.as_deref(), Some("Rebecca Black"));
        assert_eq!(item.upnp_artist.as_deref(), Some("Rebecca Black"));
        assert_eq!(item.upnp_album.as_deref(), Some("Friday"));
        assert_eq!(item.upnp_original_track_number.as_deref(), Some("1"));
        assert_eq!(item.res.duration, Some(211));
        assert_eq!(
            item.res.protocol_info.as_deref(),
            Some("http-get:*:audio/flac:*")
        );
        assert_eq!(item.res.source, "http://192.168.1.1:8001/track?trackId=123");
    }

    #[test_log::test]
    fn test_parse_track_metadata_minimal() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
                <res>http://example.com/track.mp3</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse minimal metadata");
        assert_eq!(result.items.len(), 1);

        let item = &result.items[0];
        assert!(item.upnp_class.is_none());
        assert!(item.dc_title.is_none());
        assert!(item.dc_creator.is_none());
        assert!(item.upnp_artist.is_none());
        assert!(item.upnp_album.is_none());
        assert!(item.upnp_original_track_number.is_none());
        assert!(item.res.duration.is_none());
        assert!(item.res.protocol_info.is_none());
        assert_eq!(item.res.source, "http://example.com/track.mp3");
    }

    #[test_log::test]
    fn test_parse_track_metadata_multiple_items() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/">
            <item id="0" parentID="-1" restricted="false">
                <dc:title>Track 1</dc:title>
                <res>http://example.com/track1.mp3</res>
            </item>
            <item id="1" parentID="-1" restricted="false">
                <dc:title>Track 2</dc:title>
                <res>http://example.com/track2.mp3</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse multiple items");
        assert_eq!(result.items.len(), 2);
        assert_eq!(result.items[0].dc_title.as_deref(), Some("Track 1"));
        assert_eq!(result.items[1].dc_title.as_deref(), Some("Track 2"));
    }

    #[test_log::test]
    fn test_parse_track_metadata_missing_res_element() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml);
        assert!(
            result.is_err(),
            "Expected error when res element is missing"
        );
        match result {
            Err(ActionError::MissingProperty(_)) => {}
            _ => panic!("Expected MissingProperty error"),
        }
    }

    #[test_log::test]
    fn test_parse_track_metadata_empty_document() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"></DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse empty document");
        assert_eq!(result.items.len(), 0);
    }

    #[test_log::test]
    fn test_parse_track_metadata_with_xml_escaping() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/">
            <item id="0" parentID="-1" restricted="false">
                <dc:title>Track &amp; Title</dc:title>
                <res>http://example.com/track?id=1&amp;format=mp3</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse escaped XML");
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.items[0].dc_title.as_deref(), Some("Track & Title"));
        assert_eq!(
            result.items[0].res.source,
            "http://example.com/track?id=1&format=mp3"
        );
    }

    #[test_log::test]
    fn test_parse_track_metadata_res_element_without_text_content() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
                <res protocolInfo="http-get:*:audio/mp3:*"></res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml);
        assert!(
            result.is_err(),
            "Expected error when res element has no text content"
        );
        match result {
            Err(ActionError::MissingProperty(msg)) => {
                assert!(
                    msg.contains("res"),
                    "Error message should mention res: {msg}"
                );
            }
            _ => panic!("Expected MissingProperty error"),
        }
    }

    #[test_log::test]
    fn test_parse_track_metadata_case_insensitive_tag_names() {
        // UPnP specs don't guarantee case consistency, test that we handle different cases
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:dc="http://purl.org/dc/elements/1.1/">
            <ITEM id="0" parentID="-1" restricted="false">
                <upnp:CLASS>object.item.audioItem.musicTrack</upnp:CLASS>
                <dc:TITLE>Uppercase Tags</dc:TITLE>
                <RES>http://example.com/track.mp3</RES>
            </ITEM>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse uppercase tags");
        assert_eq!(result.items.len(), 1);
        assert_eq!(
            result.items[0].upnp_class.as_deref(),
            Some("object.item.audioItem.musicTrack")
        );
        assert_eq!(result.items[0].dc_title.as_deref(), Some("Uppercase Tags"));
    }

    #[test_log::test]
    fn test_parse_track_metadata_invalid_xml() {
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
                <res>http://example.com/track.mp3
            </item>"#; // Missing closing tags

        let result = parse_track_metadata(xml);
        assert!(result.is_err(), "Expected error when XML is invalid");
        assert!(
            matches!(result, Err(ActionError::Roxml(_))),
            "Expected Roxml error variant"
        );
    }

    #[test_log::test]
    fn test_parse_track_metadata_duration_parsing() {
        // Tests various duration formats in metadata res elements
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
                <res duration="01:30:45">http://example.com/long_track.mp3</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse metadata with duration");
        assert_eq!(result.items.len(), 1);
        // 1:30:45 = 1*3600 + 30*60 + 45 = 3600 + 1800 + 45 = 5445 seconds
        assert_eq!(result.items[0].res.duration, Some(5445));
    }

    #[test_log::test]
    fn test_parse_track_metadata_with_special_characters_in_url() {
        // Tests URL with query parameters and special characters (common in streaming APIs)
        let xml = r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
            <item id="0" parentID="-1" restricted="false">
                <res>http://192.168.1.100:8001/track?trackId=12911&amp;source=LIBRARY&amp;quality=HIGH</res>
            </item>
        </DIDL-Lite>"#;

        let result = parse_track_metadata(xml).expect("Failed to parse metadata with special URL");
        assert_eq!(result.items.len(), 1);
        assert_eq!(
            result.items[0].res.source,
            "http://192.168.1.100:8001/track?trackId=12911&source=LIBRARY&quality=HIGH"
        );
    }

    #[test_log::test]
    fn test_str_to_duration_boundary_values() {
        // Test boundary between time units
        assert_eq!(str_to_duration("00:00:59"), 59);
        assert_eq!(str_to_duration("00:59:59"), 3599);
        assert_eq!(str_to_duration("23:59:59"), 86399);
        // Test with leading zeros
        assert_eq!(str_to_duration("00:00:09"), 9);
        assert_eq!(str_to_duration("00:09:00"), 540);
        assert_eq!(str_to_duration("09:00:00"), 32400);
    }

    #[test_log::test]
    fn test_duration_to_string_boundary_values() {
        // Test boundary between time units
        assert_eq!(duration_to_string(59), "00:00:59");
        assert_eq!(duration_to_string(3599), "00:59:59");
        assert_eq!(duration_to_string(86399), "23:59:59");
        // Test large values beyond 24 hours
        assert_eq!(duration_to_string(90000), "25:00:00");
        assert_eq!(duration_to_string(360_000), "100:00:00");
    }

    mod cache_tests {
        use super::*;

        #[test_log::test]
        fn test_cache_device_not_found_by_udn() {
            let result = cache::get_device("uuid:nonexistent-device");
            assert!(result.is_err());
            match result {
                Err(ScanError::DeviceUdnNotFound { device_udn }) => {
                    assert_eq!(device_udn, "uuid:nonexistent-device");
                }
                _ => panic!("Expected DeviceUdnNotFound error"),
            }
        }

        #[test_log::test]
        fn test_cache_device_not_found_by_url() {
            let result = cache::get_device_from_url("http://192.168.1.100:1234/device");
            assert!(result.is_err());
            match result {
                Err(ScanError::DeviceUrlNotFound { device_url }) => {
                    assert_eq!(device_url, "http://192.168.1.100:1234/device");
                }
                _ => panic!("Expected DeviceUrlNotFound error"),
            }
        }

        #[test_log::test]
        fn test_cache_service_not_found() {
            let result = cache::get_service(
                "uuid:nonexistent-device",
                "urn:upnp-org:serviceId:AVTransport",
            );
            assert!(result.is_err());
            match result {
                Err(ScanError::DeviceUdnNotFound { device_udn }) => {
                    assert_eq!(device_udn, "uuid:nonexistent-device");
                }
                _ => panic!("Expected DeviceUdnNotFound error"),
            }
        }

        #[test_log::test]
        fn test_public_get_device_not_found() {
            let result = get_device("uuid:nonexistent");
            assert!(result.is_err());
        }

        #[test_log::test]
        fn test_public_get_service_not_found() {
            let result = get_service("uuid:nonexistent", "urn:upnp-org:serviceId:AVTransport");
            assert!(result.is_err());
        }

        #[test_log::test]
        fn test_public_get_device_and_service_not_found() {
            let result =
                get_device_and_service("uuid:nonexistent", "urn:upnp-org:serviceId:AVTransport");
            assert!(result.is_err());
        }

        #[test_log::test]
        fn test_public_get_device_from_url_not_found() {
            let result = get_device_from_url("http://192.168.1.100:1234/device");
            assert!(result.is_err());
        }

        #[test_log::test]
        fn test_public_get_device_and_service_from_url_not_found() {
            let result = get_device_and_service_from_url(
                "http://192.168.1.100:1234/device",
                "urn:upnp-org:serviceId:AVTransport",
            );
            assert!(result.is_err());
        }
    }

    mod upnp_device_scanner_tests {
        use super::*;

        #[test_log::test(switchy_async::test)]
        async fn test_scanner_returns_early_when_already_scanning() {
            let mut scanner = UpnpDeviceScanner {
                scanning: true,
                devices: vec![],
            };

            // Should return Ok immediately without actually scanning
            let result = scanner.scan().await;
            assert!(result.is_ok());
            // Devices should still be empty since scan was skipped
            assert!(scanner.devices.is_empty());
            // Scanning flag should remain true (it wasn't reset because scan was skipped)
            assert!(scanner.scanning);
        }

        #[test_log::test(switchy_async::test)]
        async fn test_scanner_returns_early_when_devices_already_found() {
            let existing_device = UpnpDevice {
                name: "Test Device".to_string(),
                udn: "uuid:test-123".to_string(),
                volume: None,
                services: vec![],
            };

            let mut scanner = UpnpDeviceScanner {
                scanning: false,
                devices: vec![existing_device.clone()],
            };

            // Should return Ok immediately without rescanning
            let result = scanner.scan().await;
            assert!(result.is_ok());
            // Devices should still contain the original device
            assert_eq!(scanner.devices.len(), 1);
            assert_eq!(scanner.devices[0].udn, "uuid:test-123");
            // Scanning flag should remain false (scan was skipped)
            assert!(!scanner.scanning);
        }

        #[test_log::test]
        fn test_scanner_new_creates_default_state() {
            let scanner = UpnpDeviceScanner::new();
            assert!(!scanner.scanning);
            assert!(scanner.devices.is_empty());
        }

        #[test_log::test(switchy_async::test)]
        async fn test_scanner_scan_completes_with_empty_device_list() {
            // Tests the scan path when no devices are found (simulator returns empty stream)
            let mut scanner = UpnpDeviceScanner::new();
            assert!(!scanner.scanning);
            assert!(scanner.devices.is_empty());

            let result = scanner.scan().await;
            assert!(result.is_ok());
            // After scan completes, scanning flag should be reset to false
            assert!(!scanner.scanning);
            // Devices list should still be empty (no devices discovered in simulator mode)
            assert!(scanner.devices.is_empty());
        }
    }
}