pleezer 0.5.0

Headless Deezer Connect player
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
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
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
//! Remote control protocol implementation for Deezer Connect.
//!
//! This module implements the client side of the Deezer Connect protocol,
//! enabling remote control functionality between devices. It handles:
//! * Device discovery and connection
//! * Authentication and session management
//! * Command processing
//! * Queue synchronization and manipulation (shuffle, repeat)
//! * Playback reporting
//! * Event notifications
//!
//! # Protocol Flow
//!
//! 1. Connection Establishment
//!    * Client connects to Deezer websocket
//!    * Authenticates with user token
//!    * Subscribes to required channels
//!
//! 2. Device Discovery
//!    * Client announces availability
//!    * Controllers send discovery requests
//!    * Client responds with connection offers
//!
//! 3. Control Session
//!    * Controller initiates connection
//!    * Client accepts and establishes session
//!    * Commands flow between devices
//!    * Queue and playback state synchronized (including shuffle)
//!
//! # Connection States
//!
//! A client progresses through several states:
//! * Disconnected - Initial state
//! * Available - Ready for discovery
//! * Connecting - Accepting controller
//! * Connected - Active control session
//! * Taken - Connection locked (if interruptions disabled)
//!
//! # Message Types
//!
//! The protocol uses several message types:
//! * Discovery - Device detection
//! * Command - Playback control
//! * Queue - Content management
//! * Stream - Playback reporting
//! * Status - Command acknowledgement
//!
//! # Example
//!
//! ```rust
//! use pleezer::remote::Client;
//!
//! let mut client = Client::new(&config, player)?;
//!
//! // Start client and handle control messages
//! client.start().await?;
//! ```

use std::{collections::HashSet, ops::ControlFlow, pin::Pin, process::Command, time::Duration};

use futures_util::{stream::SplitSink, SinkExt, StreamExt};
use log::Level;
use lru_time_cache::LruCache;
use semver;
use tokio_tungstenite::{
    tungstenite::{
        client::ClientRequestBuilder, protocol::frame::Frame, Message as WebsocketMessage,
    },
    MaybeTlsStream, WebSocketStream,
};
use uuid::Uuid;

use crate::{
    arl::Arl,
    config::{Config, Credentials},
    error::{Error, ErrorKind, Result},
    events::Event,
    gateway::Gateway,
    player::Player,
    protocol::connect::{
        queue::{self, ContainerType, MixType},
        stream, Body, Channel, Contents, DeviceId, DeviceType, Headers, Ident, Message, Percentage,
        QueueItem, RepeatMode, Status, UserId,
    },
    proxy,
    tokens::UserToken,
    track::{Track, TrackId},
};

/// A client on the Deezer Connect protocol.
pub struct Client {
    /// Unique identifier for this device
    device_id: DeviceId,

    /// Human-readable device name shown in discovery
    device_name: String,

    /// Device type identifier (mobile, desktop, etc)
    device_type: DeviceType,

    /// User authentication credentials
    credentials: Credentials,

    /// Gateway API client
    gateway: Gateway,

    /// Current user authentication token
    user_token: Option<UserToken>,

    /// Channel for token lifetime updates
    time_to_live_tx: tokio::sync::mpsc::Sender<Duration>,

    /// Receiver for token lifetime updates
    time_to_live_rx: tokio::sync::mpsc::Receiver<Duration>,

    /// Protocol version string
    version: String,

    /// Websocket message sender
    websocket_tx:
        Option<SplitSink<WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>, WebsocketMessage>>,

    /// Active channel subscriptions
    subscriptions: HashSet<Ident>,

    /// Current connection state
    connection_state: ConnectionState,

    /// Timer for receiving controller heartbeats
    watchdog_rx: Pin<Box<tokio::time::Sleep>>,

    /// Timer for sending heartbeats
    watchdog_tx: Pin<Box<tokio::time::Sleep>>,

    /// Current discovery state
    discovery_state: DiscoveryState,

    /// Cache of pending connection offers
    connection_offers: LruCache<String, DeviceId>,

    /// Channel for receiving player and control events
    event_rx: tokio::sync::mpsc::UnboundedReceiver<Event>,

    /// Channel for sending player and control events
    event_tx: tokio::sync::mpsc::UnboundedSender<Event>,

    /// Volume level to set on connection and maintain until client sets below maximum.
    /// Helps work around clients that don't properly set volume levels.
    initial_volume: InitialVolume,

    /// Whether to allow connection interruptions
    interruptions: bool,

    /// Optional hook script for events
    hook: Option<String>,

    /// Audio playback manager
    player: Player,

    /// Timer for playback progress reports
    reporting_timer: Pin<Box<tokio::time::Sleep>>,

    /// Current playback queue
    ///
    /// Maintains both track list and shuffle state.
    queue: Option<queue::List>,

    /// Position to set when queue arrives
    ///
    /// Used to handle position changes that arrive before queue.
    deferred_position: Option<usize>,

    /// Whether to monitor all websocket traffic
    eavesdrop: bool,
}

/// Device discovery state.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum DiscoveryState {
    /// Available for discovery
    Available,

    /// Accepting connection from controller
    Connecting {
        /// Controller device ID
        controller: DeviceId,

        /// ID of ready message
        ready_message_id: String,
    },

    /// Not available for discovery
    Taken,
}

/// Connection state with controller.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ConnectionState {
    /// No active connection
    Disconnected,

    /// Connected to controller
    Connected {
        /// Controller device ID
        controller: DeviceId,

        /// Unique session identifier
        session_id: Uuid,
    },
}

/// Direction for queue shuffling operations.
///
/// Controls whether to:
/// * `Shuffle` - Randomize track order
/// * `Unshuffle` - Restore original track order
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum ShuffleAction {
    /// Randomize track order
    Shuffle,
    /// Restore original track order
    Unshuffle,
}

/// Volume initialization state.
///
/// Controls how initial volume is applied:
/// * Active - Set volume and remain active until client sets below maximum
/// * Inactive - Initial volume has been superseded by client control
/// * Disabled - No initial volume configured
#[derive(Copy, Clone, Debug, PartialEq)]
enum InitialVolume {
    /// Initial volume is active and will be applied
    Active(Percentage),
    /// Initial volume is stored but inactive
    Inactive(Percentage),
    /// No initial volume configured
    Disabled,
}

/// Calculates a future time instant by adding seconds to now.
///
/// # Arguments
///
/// * `seconds` - Duration to add to current time
///
/// # Returns
///
/// * Some(Instant) - Future time if addition succeeds
/// * None - If addition would overflow
#[must_use]
fn from_now(seconds: Duration) -> Option<tokio::time::Instant> {
    tokio::time::Instant::now().checked_add(seconds)
}

/// A client on the Deezer Connect protocol.
///
/// Handles:
/// * Device discovery and connections
/// * Command processing
/// * Queue management
/// * Playback state synchronization
/// * Volume management and normalization
/// * Event notifications
impl Client {
    /// Time before network operations timeout.
    const NETWORK_TIMEOUT: Duration = Duration::from_secs(2);

    /// Buffer before token refresh to prevent expiration during requests.
    const TOKEN_EXPIRATION_THRESHOLD: Duration = Duration::from_secs(60);

    /// How often to report playback progress to controller.
    const REPORTING_INTERVAL: Duration = Duration::from_secs(3);

    /// Maximum time to wait for controller heartbeat.
    const WATCHDOG_RX_TIMEOUT: Duration = Duration::from_secs(10);

    /// Maximum time between sending heartbeats.
    const WATCHDOG_TX_TIMEOUT: Duration = Duration::from_secs(5);

    /// Maximum allowed websocket message size in bytes.
    const MESSAGE_SIZE_MAX: usize = 8192;

    /// Creates a new client instance.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration including device and authentication settings
    /// * `player` - Audio playback manager instance
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Application version in config is not valid `SemVer`
    /// * Gateway client creation fails
    pub fn new(config: &Config, player: Player) -> Result<Self> {
        // Construct version in the form of `Mmmppp` where:
        // - `M` is the major version
        // - `mm` is the minor version
        // - `ppp` is the patch version
        let semver = semver::Version::parse(&config.app_version)?;
        let major = semver.major;
        let minor = semver.minor;
        let patch = semver.patch;

        // Trim leading zeroes.
        let version = if major > 0 {
            format!("{major}{minor:0>2}{patch:0>3}")
        } else if minor > 0 {
            format!("{minor}{patch:0>3}")
        } else {
            format!("{patch}")
        };
        trace!("remote version: {version}");

        // Controllers send discovery requests every two seconds.
        let time_to_live = Duration::from_secs(5);
        let connection_offers = LruCache::with_expiry_duration(time_to_live);

        // Timers are set in the message handlers. They should be moved into
        // a state variant once `select!` supports `if let` statements:
        // https://github.com/tokio-rs/tokio/issues/4173
        let reporting_timer = tokio::time::sleep(Duration::ZERO);
        let watchdog_rx = tokio::time::sleep(Duration::ZERO);
        let watchdog_tx = tokio::time::sleep(Duration::ZERO);

        let (time_to_live_tx, time_to_live_rx) = tokio::sync::mpsc::channel(1);
        let (event_tx, event_rx) = tokio::sync::mpsc::unbounded_channel::<Event>();

        let initial_volume = match config.initial_volume {
            Some(volume) => InitialVolume::Active(volume),
            None => InitialVolume::Disabled,
        };

        Ok(Self {
            device_id: config.device_id.into(),
            device_name: config.device_name.clone(),
            device_type: config.device_type,

            credentials: config.credentials.clone(),
            gateway: Gateway::new(config)?,

            user_token: None,
            time_to_live_tx,
            time_to_live_rx,

            version,
            websocket_tx: None,

            subscriptions: HashSet::new(),

            connection_state: ConnectionState::Disconnected,
            watchdog_rx: Box::pin(watchdog_rx),
            watchdog_tx: Box::pin(watchdog_tx),

            event_rx,
            event_tx,

            player,
            reporting_timer: Box::pin(reporting_timer),

            discovery_state: DiscoveryState::Available,
            connection_offers,

            initial_volume,
            interruptions: config.interruptions,
            hook: config.hook.clone(),

            queue: None,
            deferred_position: None,

            eavesdrop: config.eavesdrop,
        })
    }

    /// Attempts to login using email and password credentials.
    ///
    /// # Arguments
    ///
    /// * `email` - User's email address
    /// * `password` - User's password
    ///
    /// # Returns
    ///
    /// An ARL token for future authentication.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Login credentials are invalid
    /// * Network request fails
    /// * Gateway response is invalid
    async fn login(&mut self, email: &str, password: &str) -> Result<Arl> {
        let arl = self.gateway.login(email, password).await?;

        // Use `arl:?` to print as `Debug`, which is redacted.
        trace!("arl: {arl:?}");

        Ok(arl)
    }

    /// Retrieves a valid user token from the gateway.
    ///
    /// Repeatedly attempts to get a token that expires after the threshold.
    /// Returns both the token and its time-to-live for expiration tracking.
    ///
    /// # Returns
    ///
    /// Tuple containing:
    /// * `UserToken` - Valid authentication token
    /// * Duration - Time until token expires
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Gateway request fails
    /// * Token cannot be retrieved
    async fn user_token(&mut self) -> Result<(UserToken, Duration)> {
        // Loop until a user token is supplied that expires after the
        // threshold. If rate limiting is necessary, then that should be done
        // by the token token_provider.
        loop {
            let token = self.gateway.user_token().await?;

            let time_to_live = token
                .time_to_live()
                .checked_sub(Self::TOKEN_EXPIRATION_THRESHOLD);

            match time_to_live {
                Some(duration) => {
                    // This takes a few milliseconds and would normally
                    // truncate (round down). Return `ceil` is more human
                    // readable.
                    debug!(
                        "user data time to live: {:.0}s",
                        duration.as_secs_f32().ceil(),
                    );

                    break Ok((token, duration));
                }
                None => {
                    // Flush user tokens that expire within the threshold.
                    self.gateway.flush_user_token();
                }
            }
        }
    }

    /// Configures player settings from user preferences.
    ///
    /// Updates:
    /// * Audio quality
    /// * Volume normalization
    /// * License token
    /// * Media URL
    fn set_player_settings(&mut self) {
        let audio_quality = self.gateway.audio_quality();
        info!("user casting quality: {audio_quality}");
        self.player.set_audio_quality(audio_quality);

        let gain_target_db = self.gateway.target_gain();
        self.player.set_gain_target_db(gain_target_db);

        if let Some(license_token) = self.gateway.license_token() {
            self.player.set_license_token(license_token);
        }

        self.player.set_media_url(self.gateway.media_url());
    }

    /// Starts the client and handles control messages.
    ///
    /// Establishes websocket connection, authenticates, and begins processing:
    /// * Controller discovery
    /// * Command messages
    /// * Playback state updates
    /// * Connection maintenance
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Authentication fails
    /// * Websocket connection fails
    /// * Message handling fails critically
    pub async fn start(&mut self) -> Result<()> {
        if let Credentials::Login { email, password } = &self.credentials.clone() {
            info!("logging in with email and password");
            // We can drop the result because the ARL is stored as a cookie.
            let _arl = self.login(email, password).await?;
        } else {
            info!("using ARL from secrets file");
        }

        let (user_token, time_to_live) = self.user_token().await?;
        debug!("user id: {}", user_token.user_id);

        // Set timer for user token expiration. Wake a short while before
        // actual expiration. This prevents API request errors when the
        // expiration is checked with only a few seconds on the clock.
        let expiry = tokio::time::sleep(time_to_live);
        tokio::pin!(expiry);

        let uri = format!(
            "wss://live.deezer.com/ws/{}?version={}",
            user_token, self.version
        );
        let mut request = ClientRequestBuilder::new(uri.parse::<http::Uri>()?);

        self.user_token = Some(user_token);

        // Decorate the websocket request with the same cookies as the gateway.
        if let Some(cookies) = self.gateway.cookies() {
            if let Ok(cookie_str) = cookies.to_str() {
                request = request.with_header("Cookie", cookie_str);
            } else {
                warn!("unable to set cookie header on websocket");
            }
        }

        let (ws_stream, _) = if let Some(proxy) = proxy::Http::from_env() {
            info!("using proxy: {proxy}");
            let tcp_stream = proxy.connect_async(&uri).await?;
            tokio_tungstenite::client_async_tls(request, tcp_stream).await?
        } else {
            tokio_tungstenite::connect_async(request).await?
        };

        let (websocket_tx, mut websocket_rx) = ws_stream.split();
        self.websocket_tx = Some(websocket_tx);

        self.subscribe(Ident::Stream).await?;
        self.subscribe(Ident::RemoteDiscover).await?;

        // Register playback event handler.
        self.player.register(self.event_tx.clone());

        if self.eavesdrop {
            warn!("not discoverable: eavesdropping on websocket");
        } else {
            info!("ready for discovery");
        }

        let loop_result = loop {
            tokio::select! {
                biased;

                () = &mut self.watchdog_tx, if self.is_connected() => {
                    if let Err(e) = self.send_ping().await {
                        error!("error sending ping: {e}");
                    }
                }

                () = &mut self.watchdog_rx, if self.is_connected() => {
                    error!("controller is not responding");
                    let _drop = self.disconnect().await;
                }

                () = &mut expiry => {
                    break Err(Error::deadline_exceeded("user token expired"));
                }
                Some(time_to_live) = self.time_to_live_rx.recv() => {
                    if let Some(deadline) = tokio::time::Instant::now().checked_add(time_to_live) {
                        expiry.as_mut().reset(deadline);
                    }
                }

                () = &mut self.reporting_timer, if self.is_connected() && self.player.is_playing() => {
                    if let Err(e) = self.report_playback_progress().await {
                        error!("error reporting playback progress: {e}");
                    }
                }

                Some(message) = websocket_rx.next() => {
                    match message {
                        Ok(message) => {
                            // Do not parse exceedingly large messages to
                            // prevent out of memory conditions.
                            let message_size = message.len();
                            if message_size > Self::MESSAGE_SIZE_MAX {
                                error!("ignoring oversized message with {message_size} bytes");
                                continue;
                            }

                            match self.handle_message(&message).await {
                                ControlFlow::Continue(()) => continue,

                                ControlFlow::Break(e) => {
                                    if e.kind == ErrorKind::DeadlineExceeded {
                                        info!("stopping client: {}", e.to_string());
                                        self.gateway.flush_user_token();
                                        break Ok(());
                                    }

                                    break Err(Error::internal(format!("error handling message: {e}")));
                                }
                            }
                        }
                        Err(e) => error!("error receiving message: {e}"),
                    }
                }

                Err(e) = self.player.run(), if self.player.is_started() => break Err(e),

                Some(event) = self.event_rx.recv() => {
                    self.handle_event(event).await;
                }
            }
        };

        self.stop().await;

        loop_result
    }

    /// Processes received events.
    ///
    /// Handles:
    /// * Play - Track started
    /// * Pause - Playback paused
    /// * `TrackChanged` - New track active
    /// * Connected - Controller connected
    /// * Disconnected - Controller disconnected
    ///
    /// Executes hook script if configured.
    ///
    /// # Arguments
    ///
    /// * `event` - Event to process
    async fn handle_event(&mut self, event: Event) {
        let mut command = self.hook.as_ref().map(Command::new);
        let track_id = self.player.track().map(Track::id);

        debug!("handling event: {event:?}");

        match event {
            Event::Play => {
                if let Some(track_id) = track_id {
                    // Report playback progress without waiting for the next
                    // reporting interval, so the UI refreshes immediately.
                    let _ = self.report_playback_progress().await;

                    // Report the playback stream.
                    if let Err(e) = self.report_playback(track_id).await {
                        error!("error streaming {track_id}: {e}");
                    }

                    if self.is_flow() {
                        // Extend the queue if the player is near the end.
                        if self
                            .queue
                            .as_ref()
                            .map_or(0, |queue| queue.tracks.len())
                            .saturating_sub(self.player.position())
                            <= 2
                        {
                            if let Err(e) = self.extend_queue().await {
                                error!("error extending queue: {e}");
                            }
                        }
                    }

                    if let Some(command) = command.as_mut() {
                        command
                            .env("EVENT", "playing")
                            .env("TRACK_ID", shell_escape(&track_id.to_string()));
                    }
                }
            }

            Event::Pause => {
                if let Some(command) = command.as_mut() {
                    command.env("EVENT", "paused");
                }
            }

            Event::TrackChanged => {
                if let Some(track) = self.player.track() {
                    if let Some(command) = command.as_mut() {
                        command
                            .env("EVENT", "track_changed")
                            .env("TRACK_ID", shell_escape(&track.id().to_string()))
                            .env("TITLE", shell_escape(track.title()))
                            .env("ARTIST", shell_escape(track.artist()))
                            .env("ALBUM_TITLE", shell_escape(track.album_title()))
                            .env("ALBUM_COVER", shell_escape(track.album_cover()))
                            .env(
                                "DURATION",
                                shell_escape(&track.duration().as_secs().to_string()),
                            );
                    }
                }
            }

            Event::Connected => {
                if let Some(command) = command.as_mut() {
                    command
                        .env("EVENT", "connected")
                        .env("USER_ID", shell_escape(&self.user_id().to_string()))
                        .env(
                            "USER_NAME",
                            shell_escape(self.gateway.user_name().unwrap_or_default()),
                        );
                }
            }

            Event::Disconnected => {
                if let Some(command) = command.as_mut() {
                    command.env("EVENT", "disconnected");
                }
            }
        }

        if let Some(command) = command.as_mut() {
            if let Err(e) = command.spawn() {
                error!("failed to spawn hook script: {e}");
            }
        }
    }

    /// Checks whether the current queue is a Flow (personalized radio) queue.
    ///
    /// Examines the queue context to determine if it represents a personalized radio stream.
    ///
    /// # Returns
    ///
    /// * `true` - Current queue is a Flow queue
    /// * `false` - Current queue is not Flow or no queue exists
    fn is_flow(&self) -> bool {
        self.queue.as_ref().is_some_and(|queue| {
            queue
                .contexts
                .first()
                .unwrap_or_default()
                .container
                .mix
                .typ
                .enum_value_or_default()
                == MixType::MIX_TYPE_USER
        })
    }

    /// Resets the receive watchdog timer.
    ///
    /// Called when messages are received from the controller to prevent connection timeout.
    fn reset_watchdog_rx(&mut self) {
        if let Some(deadline) = from_now(Self::WATCHDOG_RX_TIMEOUT) {
            self.watchdog_rx.as_mut().reset(deadline);
        }
    }

    /// Resets the transmit watchdog timer.
    ///
    /// Called when messages are sent to the controller to maintain heartbeat timing.
    fn reset_watchdog_tx(&mut self) {
        if let Some(deadline) = from_now(Self::WATCHDOG_TX_TIMEOUT) {
            self.watchdog_tx.as_mut().reset(deadline);
        }
    }

    /// Resets the playback reporting timer.
    ///
    /// Schedules the next progress report according to the reporting interval.
    fn reset_reporting_timer(&mut self) {
        if let Some(deadline) = from_now(Self::REPORTING_INTERVAL) {
            self.reporting_timer.as_mut().reset(deadline);
        }
    }

    /// Stops the client and cleans up resources.
    ///
    /// * Disconnects from controller if connected
    /// * Processes remaining events
    /// * Unsubscribes from channels
    pub async fn stop(&mut self) {
        if self.is_connected() {
            if let Err(e) = self.disconnect().await {
                error!("error disconnecting: {e}");
            }
        }

        // Close the event receiver and handle any remaining events.
        self.event_rx.close();
        while let Some(event) = self.event_rx.recv().await {
            self.handle_event(event).await;
        }

        // Cancel any remaining subscriptions not handled by `disconnect`.
        let subscriptions = self.subscriptions.clone();
        for ident in subscriptions {
            if self.unsubscribe(ident).await.is_ok() {
                self.subscriptions.remove(&ident);
            }
        }
    }

    /// Creates a message targeted at a specific device.
    ///
    /// # Arguments
    ///
    /// * `destination` - Target device ID
    /// * `channel` - Message channel
    /// * `body` - Message content
    ///
    /// # Returns
    ///
    /// Formatted message ready for sending.
    fn message(&self, destination: DeviceId, channel: Channel, body: Body) -> Message {
        let contents = Contents {
            ident: channel.ident,
            headers: Headers {
                from: self.device_id.clone(),
                destination: Some(destination),
            },
            body,
        };

        Message::Send { channel, contents }
    }

    /// Creates a command message for a device.
    ///
    /// Convenience wrapper around `message()` for command channel.
    ///
    /// # Arguments
    ///
    /// * `destination` - Target device ID
    /// * `body` - Command content
    fn command(&self, destination: DeviceId, body: Body) -> Message {
        let remote_command = self.channel(Ident::RemoteCommand);
        self.message(destination, remote_command, body)
    }

    /// Creates a discovery message for a device.
    ///
    /// Convenience wrapper around `message()` for discovery channel.
    ///
    /// # Arguments
    ///
    /// * `destination` - Target device ID
    /// * `body` - Discovery content
    fn discover(&self, destination: DeviceId, body: Body) -> Message {
        let remote_discover = self.channel(Ident::RemoteDiscover);
        self.message(destination, remote_discover, body)
    }

    /// Reports track playback to Deezer.
    ///
    /// # Arguments
    ///
    /// * `track_id` - ID of track being played
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active connection
    /// * Message send fails
    async fn report_playback(&mut self, track_id: TrackId) -> Result<()> {
        if let ConnectionState::Connected { session_id, .. } = &self.connection_state {
            let message = Message::StreamSend {
                channel: self.channel(Ident::Stream),
                contents: stream::Contents {
                    action: stream::Action::Play,
                    ident: stream::Ident::Limitation,
                    value: stream::Value {
                        user: self.user_id(),
                        uuid: *session_id,
                        track_id,
                    },
                },
            };

            self.send_message(message).await
        } else {
            Err(Error::failed_precondition(
                "playback reporting should have an active connection".to_string(),
            ))
        }
    }

    /// Disconnects from the current controller.
    ///
    /// Sends a close message to the controller and resets connection state.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller connection exists
    /// * Message send fails
    async fn disconnect(&mut self) -> Result<()> {
        if let Some(controller) = self.controller() {
            let close = Body::Close {
                message_id: crate::Uuid::fast_v4().to_string(),
            };

            let command = self.command(controller.clone(), close);
            self.send_message(command).await?;

            self.reset_states();
            return Ok(());
        }

        Err(Error::failed_precondition(
            "disconnect should have an active connection".to_string(),
        ))
    }

    /// Handles device discovery request from a controller.
    ///
    /// Creates and caches a connection offer, then sends it to the
    /// requesting controller.
    ///
    /// # Arguments
    ///
    /// * `from` - ID of requesting controller
    ///
    /// # Errors
    ///
    /// Returns error if message send fails.
    async fn handle_discovery_request(&mut self, from: DeviceId) -> Result<()> {
        // Controllers keep sending discovery requests about every two seconds
        // until it accepts some offer. `connection_offers` implements a LRU
        // cache to evict stale offers.
        let message_id = crate::Uuid::fast_v4().to_string();
        self.connection_offers
            .insert(message_id.clone(), from.clone());

        let offer = Body::ConnectionOffer {
            message_id,
            from: self.device_id.clone(),
            device_name: self.device_name.clone(),
            device_type: self.device_type,
        };

        let discover = self.discover(from, offer);
        self.send_message(discover).await
    }

    /// Handles connection request from a controller.
    ///
    /// Validates connection offer and establishes control session if:
    /// * Offer is valid and matches requesting controller
    /// * Client is available for connections
    /// * Required channel subscriptions succeed
    ///
    /// # Arguments
    ///
    /// * `from` - ID of connecting controller
    /// * `offer_id` - ID of previous connection offer
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Offer validation fails
    /// * Client is not available
    /// * Channel subscription fails
    /// * Message send fails
    async fn handle_connect(&mut self, from: DeviceId, offer_id: Option<String>) -> Result<()> {
        let controller = offer_id
            .and_then(|offer_id| self.connection_offers.remove(&offer_id))
            .ok_or_else(|| Error::failed_precondition("connection offer should be active"))?;

        if controller != from {
            return Err(Error::failed_precondition(format!(
                "connection offer for {controller} should be for {from}"
            )));
        }

        if self.discovery_state == DiscoveryState::Taken {
            debug!("not allowing interruptions from {from}");

            // This is a known and valid condition. Return `Ok` so the
            // control flow may continue.
            return Ok(());
        }

        // Subscribe to both channels. If one fails, try to roll back.
        self.subscribe(Ident::RemoteQueue).await?;
        if let Err(e) = self.subscribe(Ident::RemoteCommand).await {
            let _drop = self.unsubscribe(Ident::RemoteQueue).await;
            return Err(e);
        }

        let message_id = crate::Uuid::fast_v4().to_string();
        let ready = Body::Ready {
            message_id: message_id.clone(),
        };

        let command = self.command(from.clone(), ready);
        self.send_message(command).await?;

        self.discovery_state = DiscoveryState::Connecting {
            controller: from,
            ready_message_id: message_id,
        };

        Ok(())
    }

    /// Checks if client has active controller connection.
    ///
    /// # Returns
    ///
    /// * true - Connected to controller
    /// * false - Not connected
    #[must_use]
    fn is_connected(&self) -> bool {
        if let ConnectionState::Connected { .. } = &self.connection_state {
            return true;
        }

        false
    }

    /// Returns ID of currently connected controller if any.
    ///
    /// # Returns
    ///
    /// * Some(DeviceId) - ID of connected controller
    /// * None - No controller connected
    fn controller(&self) -> Option<DeviceId> {
        if let ConnectionState::Connected { controller, .. } = &self.connection_state {
            return Some(controller.clone());
        }

        if let DiscoveryState::Connecting { controller, .. } = &self.discovery_state {
            return Some(controller.clone());
        }

        None
    }

    /// Handles status message from controller.
    ///
    /// Processes command status and updates connection state.
    /// During connection handshake, establishes full connection and:
    /// * Updates connection state
    /// * Sets discovery state
    /// * Loads user settings
    /// * Starts playback device
    /// * Applies initial volume if configured
    ///
    /// # Arguments
    ///
    /// * `from` - Controller device ID
    /// * `command_id` - ID of command being acknowledged
    /// * `status` - Command status
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Status indicates command failure
    /// * Connection state transition invalid
    /// * Message send fails
    /// * Volume setting fails
    async fn handle_status(
        &mut self,
        from: DeviceId,
        command_id: &str,
        status: Status,
    ) -> Result<()> {
        if status != Status::OK {
            return Err(Error::failed_precondition(format!(
                "controller failed to process {command_id}"
            )));
        }

        if let DiscoveryState::Connecting {
            controller,
            ready_message_id,
        } = self.discovery_state.clone()
        {
            if from == controller && command_id == ready_message_id {
                if let ConnectionState::Connected { controller, .. } = &self.connection_state {
                    // Evict the active connection.
                    let close = Body::Close {
                        message_id: crate::Uuid::fast_v4().to_string(),
                    };

                    let command = self.command(controller.clone(), close);
                    self.send_message(command).await?;
                }

                if self.interruptions {
                    self.discovery_state = DiscoveryState::Available;
                } else {
                    self.discovery_state = DiscoveryState::Taken;
                }

                // The unique session ID is used when reporting playback.
                self.connection_state = ConnectionState::Connected {
                    controller: from,
                    session_id: crate::Uuid::fast_v4().into(),
                };

                info!("connected to {controller}");
                if let Err(e) = self.event_tx.send(Event::Connected) {
                    error!("failed to send connected event: {e}");
                }

                // Refreshed the user token on every reconnection in order to reload the user
                // configuration, like normalization and audio quality.
                let (user_token, time_to_live) =
                    tokio::time::timeout(Self::NETWORK_TIMEOUT, self.user_token()).await??;
                self.user_token = Some(user_token);

                // Inform the select loop about the new time to live.
                if let Err(e) = self.time_to_live_tx.send(time_to_live).await {
                    error!("failed to send user token time to live: {e}");
                }

                self.set_player_settings();
                self.player.start()?;

                if let InitialVolume::Active(initial_volume) = self.initial_volume {
                    debug!("initial volume: {initial_volume}");
                    self.player.set_volume(initial_volume)?;
                }

                return Ok(());
            }

            return Err(Error::failed_precondition(
                "should match controller and ready message".to_string(),
            ));
        }

        // Ignore other status messages.
        Ok(())
    }

    /// Handles close request from controller.
    ///
    /// Cleans up connection state and subscriptions.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * Unsubscribe fails
    async fn handle_close(&mut self) -> Result<()> {
        if self.controller().is_some() {
            self.unsubscribe(Ident::RemoteQueue).await?;
            self.unsubscribe(Ident::RemoteCommand).await?;

            self.reset_states();
            return Ok(());
        }

        Err(Error::failed_precondition(
            "close should have an active connection".to_string(),
        ))
    }

    /// Resets connection and discovery states.
    ///
    /// Called when a connection terminates to:
    /// * Clear controller association
    /// * Reset connection state
    /// * Reset discovery state
    /// * Restore initial volume activation
    /// * Flush cached tokens
    /// * Emit disconnect event
    fn reset_states(&mut self) {
        if let Some(controller) = self.controller() {
            info!("disconnected from {controller}");

            if let Err(e) = self.event_tx.send(Event::Disconnected) {
                error!("failed to send disconnected event: {e}");
            }
        }

        // Ensure the player releases the output device.
        self.player.stop();

        // Restore the initial volume for the next connection.
        if let InitialVolume::Inactive(initial_volume) = self.initial_volume {
            self.initial_volume = InitialVolume::Active(initial_volume);
        }

        // Force the user token to be reloaded on the next connection.
        self.gateway.flush_user_token();

        // Reset the connection and discovery states.
        self.connection_state = ConnectionState::Disconnected;
        self.discovery_state = DiscoveryState::Available;
    }

    /// Handles queue publication from controller.
    ///
    /// Updates local queue and configures player:
    /// * Stores queue metadata
    /// * Resolves track information
    /// * Updates player queue
    /// * Handles deferred position
    /// * Extends Flow queues
    ///
    /// # Arguments
    ///
    /// * `list` - Published queue content
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Queue resolution fails
    /// * Flow extension fails
    async fn handle_publish_queue(&mut self, list: queue::List) -> Result<()> {
        let container_type = list
            .contexts
            .first()
            .unwrap_or_default()
            .container
            .typ
            .enum_value_or_default();

        let shuffled = if list.shuffled { "(shuffled)" } else { "" };
        info!("setting queue to {} {shuffled}", list.id);

        // Await with timeout in order to prevent blocking the select loop.
        let queue = match container_type {
            ContainerType::CONTAINER_TYPE_LIVE => {
                error!("live radio is not supported yet");
                Vec::new()
            }
            ContainerType::CONTAINER_TYPE_PODCAST => {
                error!("podcasts are not supported yet");
                Vec::new()
            }
            _ => {
                tokio::time::timeout(Self::NETWORK_TIMEOUT, self.gateway.list_to_queue(&list))
                    .await??
            }
        };

        let tracks: Vec<_> = queue.into_iter().map(Track::from).collect();

        self.queue = Some(list);
        self.player.set_queue(tracks);

        if let Some(position) = self.deferred_position.take() {
            self.set_position(position);
        }

        if self.is_flow() {
            self.extend_queue().await?;
        }

        Ok(())
    }

    /// Sends ping message to controller.
    ///
    /// Part of connection keepalive mechanism.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * Message send fails
    async fn send_ping(&mut self) -> Result<()> {
        if let Some(controller) = self.controller() {
            let ping = Body::Ping {
                message_id: crate::Uuid::fast_v4().to_string(),
            };

            let command = self.command(controller.clone(), ping);
            return self.send_message(command).await;
        }

        Err(Error::failed_precondition(
            "ping should have an active connection".to_string(),
        ))
    }

    /// Extends Flow queue and notifies controller.
    ///
    /// Fetches more personalized recommendations when:
    /// * Current queue is Flow
    /// * Near end of current tracks
    ///
    /// Updates both local state and remote controller by:
    /// 1. Fetching new tracks
    /// 2. Updating local queue and player
    /// 3. Publishing updated queue to controller
    /// 4. Requesting controller UI refresh
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active queue exists
    /// * Track fetch fails
    /// * Controller communication fails
    async fn extend_queue(&mut self) -> Result<()> {
        let user_id = self.user_id();

        if let Some(list) = self.queue.as_mut() {
            let new_queue =
                tokio::time::timeout(Self::NETWORK_TIMEOUT, self.gateway.user_radio(user_id))
                    .await??;

            let new_tracks: Vec<_> = new_queue.into_iter().map(Track::from).collect();

            let new_list: Vec<_> = new_tracks
                .iter()
                .map(|track| queue::Track {
                    id: track.id().to_string(),
                    ..Default::default()
                })
                .collect();

            debug!("extending queue with {} tracks", new_tracks.len());

            list.tracks.extend(new_list);
            self.player.extend_queue(new_tracks);
            self.refresh_queue().await
        } else {
            Err(Error::failed_precondition(
                "cannot extend queue: queue is missing",
            ))
        }
    }

    /// Publishes updated queue to controller and requests UI refresh.
    ///
    /// Called after queue modifications to:
    /// 1. Send updated queue state to controller
    /// 2. Request controller to refresh its UI
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller connection exists
    /// * Queue publication fails
    /// * Refresh request fails
    ///
    /// # Notes
    ///
    /// This is typically called after operations that modify the queue like:
    /// * Extending Flow recommendations
    /// * Updating shuffle order
    /// * Changing repeat mode
    async fn refresh_queue(&mut self) -> Result<()> {
        if let Some(controller) = self.controller() {
            // First publish the new queue to the controller.
            if let Some(queue) = self.queue.as_mut() {
                queue.id = crate::Uuid::fast_v4().to_string();
            }
            self.publish_queue().await?;

            // Then signal the controller to refresh its UI.
            let contents = Body::RefreshQueue {
                message_id: crate::Uuid::fast_v4().to_string(),
            };

            let channel = self.channel(Ident::RemoteQueue);
            let refresh_queue = self.message(controller.clone(), channel, contents);
            self.send_message(refresh_queue).await
        } else {
            Err(Error::failed_precondition(
                "refresh should have an active connection".to_string(),
            ))
        }
    }

    /// Handles a refresh queue request from the controller.
    ///
    /// Simply republishes our current queue state in response to
    /// the controller's request for a refresh.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active queue exists
    /// * No active controller connection
    /// * Message send fails
    /// * Progress report fails
    async fn handle_refresh_queue(&mut self) -> Result<()> {
        if let Some(queue) = self.queue.as_mut() {
            queue.id = crate::Uuid::fast_v4().to_string();
            self.publish_queue().await?;
            self.report_playback_progress().await
        } else {
            Err(Error::failed_precondition(
                "queue refresh should have a published queue".to_string(),
            ))
        }
    }

    /// Publishes current queue state to the remote controller.
    ///
    /// Sends a `PublishQueue` message containing:
    /// * New message ID
    /// * Current queue state
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller connection
    /// * No queue exists to publish
    /// * Message send fails
    async fn publish_queue(&mut self) -> Result<()> {
        if let Some(controller) = self.controller() {
            if let Some(queue) = self.queue.as_ref() {
                let contents = Body::PublishQueue {
                    message_id: crate::Uuid::fast_v4().to_string(),
                    queue: queue.clone(),
                };

                let channel = self.channel(Ident::RemoteQueue);
                let publish_queue = self.message(controller.clone(), channel, contents);
                self.send_message(publish_queue).await
            } else {
                Err(Error::failed_precondition(
                    "queue refresh should have a published queue".to_string(),
                ))
            }
        } else {
            Err(Error::failed_precondition(
                "queue refresh should have an active connection".to_string(),
            ))
        }
    }

    /// Sends acknowledgement for a command.
    ///
    /// # Arguments
    ///
    /// * `acknowledgement_id` - ID of command to acknowledge
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * Message send fails
    async fn send_acknowledgement(&mut self, acknowledgement_id: &str) -> Result<()> {
        if let Some(controller) = self.controller() {
            let acknowledgement = Body::Acknowledgement {
                message_id: crate::Uuid::fast_v4().to_string(),
                acknowledgement_id: acknowledgement_id.to_string(),
            };

            let command = self.command(controller, acknowledgement);
            return self.send_message(command).await;
        }

        Err(Error::failed_precondition(
            "acknowledgement should have an active connection".to_string(),
        ))
    }

    /// Handles skip command from controller.
    ///
    /// Updates player state according to skip parameters:
    /// * Queue position
    /// * Playback progress
    /// * Playback state
    /// * Shuffle mode
    /// * Repeat mode
    /// * Volume
    ///
    /// # Arguments
    ///
    /// * `message_id` - Command ID for acknowledgement
    /// * `queue_id` - Target queue identifier
    /// * `item` - Target track and position
    /// * `progress` - Playback progress
    /// * `should_play` - Whether to start playback
    /// * `set_shuffle` - New shuffle mode
    /// * `set_repeat_mode` - New repeat mode
    /// * `set_volume` - New volume level
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * Player state update fails
    /// * Message send fails
    #[expect(clippy::too_many_arguments)]
    async fn handle_skip(
        &mut self,
        message_id: &str,
        queue_id: Option<&str>,
        item: Option<QueueItem>,
        progress: Option<Percentage>,
        should_play: Option<bool>,
        set_shuffle: Option<bool>,
        set_repeat_mode: Option<RepeatMode>,
        set_volume: Option<Percentage>,
    ) -> Result<()> {
        // Check for controller, not if we are connected: the first `Skip`
        // message is received during the handshake, before the connection is
        // ready.
        if self.controller().is_some() {
            self.send_acknowledgement(message_id).await?;

            self.set_player_state(
                queue_id,
                item,
                progress,
                should_play,
                set_shuffle,
                set_repeat_mode,
                set_volume,
            )
            .await?;

            // The status response to the first skip, that is received during the initial handshake
            // ahead of the queue publication, should be "1" (Error).
            let status = if self.player.track().is_some() {
                Status::OK
            } else {
                Status::Error
            };

            self.send_status(message_id, status).await?;

            Ok(())
        } else {
            Err(Error::failed_precondition(
                "skip should have an active connection".to_string(),
            ))
        }
    }

    fn set_position(&mut self, position: usize) {
        let mut position = position;
        if let Some(queue) = self.queue.as_ref() {
            if queue.shuffled {
                position = queue.tracks_order[position] as usize;
            }
        }

        self.player.set_position(position);
    }

    /// Updates player state based on controller commands.
    ///
    /// Applies changes to:
    /// * Queue position
    /// * Playback progress
    /// * Playback state
    /// * Shuffle mode and track order
    /// * Repeat mode
    /// * Volume level (respecting initial volume until client takes control)
    ///
    /// # Arguments
    ///
    /// * `queue_id` - Target queue identifier
    /// * `item` - Target track and position
    /// * `progress` - Playback progress
    /// * `should_play` - Whether to start playback
    /// * `set_shuffle` - New shuffle mode
    /// * `set_repeat_mode` - New repeat mode
    /// * `set_volume` - New volume level
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * Progress setting fails
    /// * Progress reporting fails
    #[expect(clippy::too_many_arguments)]
    pub async fn set_player_state(
        &mut self,
        queue_id: Option<&str>,
        item: Option<QueueItem>,
        progress: Option<Percentage>,
        should_play: Option<bool>,
        set_shuffle: Option<bool>,
        set_repeat_mode: Option<RepeatMode>,
        set_volume: Option<Percentage>,
    ) -> Result<()> {
        if let Some(item) = item {
            let position = item.position;

            // Sometimes Deezer sends a skip message ahead of a queue publication.
            // In this case, we defer setting the position until the queue is published.
            if self
                .queue
                .as_ref()
                .is_some_and(|local| queue_id.is_some_and(|remote| local.id == remote))
            {
                self.set_position(position);
            } else {
                self.deferred_position = Some(position);
            }
        }

        if let Some(progress) = progress {
            self.player.set_progress(progress)?;
        }

        if let Some(shuffle) = set_shuffle {
            if self
                .queue
                .as_ref()
                .is_some_and(|queue| queue.shuffled != shuffle)
            {
                if shuffle {
                    self.shuffle_queue(ShuffleAction::Shuffle);
                } else {
                    self.shuffle_queue(ShuffleAction::Unshuffle);
                }

                if let Some(queue) = self.queue.as_mut() {
                    let reordered_queue: Vec<_> = queue
                        .tracks
                        .iter()
                        .filter_map(|track| track.id.parse().ok())
                        .collect();
                    self.player.reorder_queue(&reordered_queue);
                    self.refresh_queue().await?;
                }
            }
        }

        if let Some(repeat_mode) = set_repeat_mode {
            self.player.set_repeat_mode(repeat_mode);
        }

        if let Some(mut volume) = set_volume {
            if let InitialVolume::Active(initial_volume) = self.initial_volume {
                if volume < Percentage::ONE_HUNDRED {
                    // If the volume is set to a value less than 1.0, we stop using the initial
                    // volume.
                    self.initial_volume = InitialVolume::Inactive(initial_volume);
                } else {
                    volume = initial_volume;
                }
            }

            if let Err(e) = self.player.set_volume(volume) {
                error!("error setting volume: {e}");
            }
        }

        if let Some(should_play) = should_play {
            if let Err(e) = self.player.set_playing(should_play) {
                error!("error setting playback state: {e}");
            }
        }

        // TODO: move to caller so we also report on failure
        self.report_playback_progress().await
    }

    /// Shuffles or unshuffles the current queue.
    ///
    /// # Arguments
    ///
    /// * `action` - Whether to shuffle or unshuffle the queue
    ///
    /// When shuffling:
    /// * Randomizes track order
    /// * Stores original order for unshuffling
    /// * Updates shuffle state
    ///
    /// When unshuffling:
    /// * Restores original track order
    /// * Clears stored order
    /// * Updates shuffle state
    ///
    /// No effect if no queue exists.
    #[expect(clippy::cast_possible_truncation)]
    fn shuffle_queue(&mut self, action: ShuffleAction) {
        if let Some(queue) = self.queue.as_mut() {
            match action {
                ShuffleAction::Shuffle => {
                    info!("shuffling queue");

                    let len = queue.tracks.len();
                    let mut order: Vec<usize> = (0..len).collect();
                    fastrand::shuffle(&mut order);

                    let mut tracks = Vec::with_capacity(len);
                    for i in &order {
                        tracks.push(queue.tracks[*i].clone());
                    }

                    queue.tracks = tracks;
                    queue.tracks_order = order.iter().map(|position| *position as u32).collect();
                    queue.shuffled = true;
                }

                ShuffleAction::Unshuffle => {
                    info!("unshuffling queue");

                    let len = queue.tracks.len();
                    let mut tracks = Vec::with_capacity(len);
                    for i in 0..len {
                        if let Some(position) = queue
                            .tracks_order
                            .iter()
                            .position(|position| *position == i as u32)
                        {
                            tracks.push(queue.tracks[position].clone());
                        }
                    }

                    queue.tracks = tracks;
                    queue.tracks_order.clear();
                    queue.tracks_order.shrink_to_fit();
                    queue.shuffled = false;
                }
            }
        }
    }

    /// Sends command status to controller.
    ///
    /// # Arguments
    ///
    /// * `command_id` - ID of command being acknowledged
    /// * `status` - Command completion status
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * Message send fails
    async fn send_status(&mut self, command_id: &str, status: Status) -> Result<()> {
        if let Some(controller) = self.controller() {
            let status = Body::Status {
                message_id: crate::Uuid::fast_v4().to_string(),
                command_id: command_id.to_string(),
                status,
            };

            let command = self.command(controller.clone(), status);
            return self.send_message(command).await;
        }

        Err(Error::failed_precondition(
            "status should have an active connection".to_string(),
        ))
    }

    /// Reports current playback state to controller.
    ///
    /// Sends current:
    /// * Track information
    /// * Playback progress
    /// * Buffer status
    /// * Volume level
    /// * Playback state
    /// * Shuffle/repeat modes
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No active controller
    /// * No active queue
    /// * No current track
    /// * Message send fails
    #[expect(clippy::cast_possible_truncation)]
    async fn report_playback_progress(&mut self) -> Result<()> {
        // Reset the timer regardless of success or failure, to prevent getting
        // stuck in a reporting state.
        self.reset_reporting_timer();

        // TODO : replace `if let Some(x) = y` with `let x = y.ok_or(z)?`
        if let Some(controller) = self.controller() {
            if let Some(track) = self.player.track() {
                let queue = self
                    .queue
                    .as_ref()
                    .ok_or(Error::internal("no active queue"))?;

                let player_position = self.player.position();
                let mut position = player_position;
                if queue.shuffled {
                    position = queue
                        .tracks_order
                        .iter()
                        .position(|i| *i == player_position as u32)
                        .unwrap_or_default();
                }

                let item = QueueItem {
                    queue_id: queue.id.to_string(),
                    track_id: track.id(),
                    position,
                };

                let progress = Body::PlaybackProgress {
                    message_id: crate::Uuid::fast_v4().to_string(),
                    track: item,
                    quality: track.quality(),
                    duration: track.duration(),
                    buffered: track.buffered(),
                    progress: self.player.progress(),
                    volume: self.player.volume(),
                    is_playing: self.player.is_playing(),
                    is_shuffle: queue.shuffled,
                    repeat_mode: self.player.repeat_mode(),
                };

                let command = self.command(controller.clone(), progress);
                self.send_message(command).await?;
            }

            Ok(())
        } else {
            Err(Error::failed_precondition(
                "playback progress should have an active connection".to_string(),
            ))
        }
    }

    /// Handles incoming websocket messages.
    ///
    /// Processes:
    /// * Text messages (JSON protocol messages)
    /// * Ping frames (RFC 6455 compliance)
    /// * Close frames (connection termination)
    ///
    /// # Arguments
    ///
    /// * `message` - Incoming websocket message
    ///
    /// # Returns
    ///
    /// * Continue - Message handled successfully
    /// * Break(Error) - Fatal error occurred
    async fn handle_message(&mut self, message: &WebsocketMessage) -> ControlFlow<Error, ()> {
        match message {
            WebsocketMessage::Text(message) => {
                match serde_json::from_str::<Message>(message) {
                    Ok(message) => {
                        match message.clone() {
                            Message::Receive { contents, .. } => {
                                let from = contents.headers.from;

                                // Ignore echoes of own messages.
                                if from == self.device_id {
                                    return ControlFlow::Continue(());
                                }

                                let for_another = contents
                                    .headers
                                    .destination
                                    .is_some_and(|destination| destination != self.device_id);

                                // Only log messages intended for this device or eavesdropping.
                                if !for_another || self.eavesdrop {
                                    if log_enabled!(Level::Trace) {
                                        trace!("{message:#?}");
                                    } else {
                                        debug!("{message}");
                                    }
                                }

                                // Ignore messages not intended for this device.
                                if for_another || self.eavesdrop {
                                    return ControlFlow::Continue(());
                                }

                                if self
                                    .controller()
                                    .is_some_and(|controller| controller == from)
                                {
                                    self.reset_watchdog_rx();
                                }

                                if let Err(e) = self.dispatch(from, contents.body).await {
                                    error!("error handling message: {e}");
                                }
                            }

                            Message::StreamReceive { .. } => {
                                if self.eavesdrop {
                                    if log_enabled!(Level::Trace) {
                                        trace!("{message:#?}");
                                    } else {
                                        debug!("{message}");
                                    }
                                }
                                return ControlFlow::Continue(());
                            }

                            _ => {
                                trace!("ignoring unexpected message: {message:#?}");
                            }
                        }
                    }

                    Err(e) => {
                        error!("error parsing message: {e}");
                        debug!("{message:#?}");
                    }
                }
            }

            // Deezer Connect sends pings as text message payloads, but so far
            // not as websocket frames. Aim for RFC 6455 compliance anyway.
            WebsocketMessage::Ping(payload) => {
                debug!("ping -> pong");
                let pong = Frame::pong(payload.clone());
                if let Err(e) = self.send_frame(WebsocketMessage::Frame(pong)).await {
                    error!("{e}");
                }
            }

            WebsocketMessage::Close(payload) => {
                return ControlFlow::Break(Error::aborted(format!(
                    "connection closed by server: {payload:?}"
                )))
            }

            _ => {
                trace!("ignoring unimplemented frame: {message:#?}");
            }
        }

        ControlFlow::Continue(())
    }

    /// Dispatches protocol messages to appropriate handlers.
    ///
    /// Routes messages based on body type:
    /// * Acknowledgement - Command completion
    /// * Close - Connection termination
    /// * Connect - Connection establishment
    /// * Discovery - Device discovery
    /// * Ping - Connection keepalive
    /// * Queue - Content management
    /// * Skip - Playback control
    /// * Status - Command status
    /// * Stop - Playback control
    ///
    /// # Arguments
    ///
    /// * `from` - Source device ID
    /// * `body` - Message content
    ///
    /// # Errors
    ///
    /// Returns error if message handler fails
    async fn dispatch(&mut self, from: DeviceId, body: Body) -> Result<()> {
        match body {
            // TODO - Think about maintaining a queue of message IDs to be
            // acknowledged, evictingt them one by one.
            Body::Acknowledgement { .. } => Ok(()),

            Body::Close { .. } => self.handle_close().await,

            Body::Connect { from, offer_id, .. } => self.handle_connect(from, offer_id).await,

            Body::DiscoveryRequest { from, .. } => self.handle_discovery_request(from).await,

            // Pings don't use dedicated WebSocket frames, but are sent as
            // normal data. An acknowledgement serves as pong.
            Body::Ping { message_id } => self.send_acknowledgement(&message_id).await,

            Body::PublishQueue { queue, .. } => self.handle_publish_queue(queue).await,

            Body::RefreshQueue { .. } => self.handle_refresh_queue().await,

            Body::Skip {
                message_id,
                queue_id,
                track,
                progress,
                should_play,
                set_shuffle,
                set_repeat_mode,
                set_volume,
            } => {
                self.handle_skip(
                    &message_id,
                    queue_id.as_deref(),
                    track,
                    progress,
                    should_play,
                    set_shuffle,
                    set_repeat_mode,
                    set_volume,
                )
                .await
            }

            Body::Status {
                command_id, status, ..
            } => self.handle_status(from, &command_id, status).await,

            Body::Stop { .. } => self.player.pause(),

            Body::ConnectionOffer { .. } | Body::PlaybackProgress { .. } | Body::Ready { .. } => {
                trace!("ignoring message intended for a controller");
                Ok(())
            }
        }
    }

    /// Sends a websocket frame.
    ///
    /// # Arguments
    ///
    /// * `frame` - Frame to send
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * No websocket connection
    /// * Send operation fails
    async fn send_frame(&mut self, frame: WebsocketMessage) -> Result<()> {
        match &mut self.websocket_tx {
            Some(tx) => tx.send(frame).await.map_err(Into::into),
            None => Err(Error::unavailable(
                "websocket stream unavailable".to_string(),
            )),
        }
    }

    /// Sends a protocol message.
    ///
    /// Serializes message to JSON and sends as text frame.
    /// Resets watchdog timer on success.
    ///
    /// # Arguments
    ///
    /// * `message` - Protocol message to send
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// * JSON serialization fails
    /// * Frame send fails
    async fn send_message(&mut self, message: Message) -> Result<()> {
        // Reset the timer regardless of success or failure, to prevent getting
        // stuck in a reporting state.
        self.reset_watchdog_tx();

        if log_enabled!(Level::Trace) {
            trace!("{message:#?}");
        } else {
            debug!("{message}");
        }

        let json = serde_json::to_string(&message)?;
        let frame = WebsocketMessage::Text(json);
        self.send_frame(frame).await
    }

    /// Subscribes to a protocol channel.
    ///
    /// Only subscribes if not already subscribed.
    ///
    /// # Arguments
    ///
    /// * `ident` - Channel identifier
    ///
    /// # Errors
    ///
    /// Returns error if subscription message fails
    async fn subscribe(&mut self, ident: Ident) -> Result<()> {
        if !self.subscriptions.contains(&ident) {
            let channel = self.channel(ident);

            let subscribe = Message::Subscribe { channel };
            self.send_message(subscribe).await?;

            self.subscriptions.insert(ident);
        }

        Ok(())
    }

    /// Unsubscribes from a protocol channel.
    ///
    /// Only unsubscribes if currently subscribed.
    ///
    /// # Arguments
    ///
    /// * `ident` - Channel identifier
    ///
    /// # Errors
    ///
    /// Returns error if unsubscribe message fails
    async fn unsubscribe(&mut self, ident: Ident) -> Result<()> {
        if self.subscriptions.contains(&ident) {
            let channel = self.channel(ident);

            let unsubscribe = Message::Unsubscribe { channel };
            self.send_message(unsubscribe).await?;

            self.subscriptions.remove(&ident);
        }

        Ok(())
    }

    /// Returns current user ID.
    ///
    /// Returns unspecified ID if no user token available.
    #[must_use]
    fn user_id(&self) -> UserId {
        self.user_token
            .as_ref()
            .map_or(UserId::Unspecified, |token| token.user_id)
    }

    /// Creates channel descriptor for given identifier.
    ///
    /// Sets source and destination based on:
    /// * Channel type
    /// * Current user ID
    ///
    /// # Arguments
    ///
    /// * `ident` - Channel identifier
    ///
    /// # Returns
    ///
    /// Channel descriptor for protocol messages
    #[must_use]
    fn channel(&self, ident: Ident) -> Channel {
        let user_id = self.user_id();
        let from = if let Ident::UserFeed(_) = ident {
            UserId::Unspecified
        } else {
            user_id
        };

        Channel {
            from,
            to: user_id,
            ident,
        }
    }
}

/// Escapes a string for use in shell commands.
///
/// Wraps shell-escape crate's functionality for string escaping.
///
/// # Arguments
///
/// * `s` - String to escape
///
/// # Returns
///
/// Shell-safe escaped string
fn shell_escape(s: &str) -> String {
    shell_escape::escape(s.into()).to_string()
}