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
#![warn(clippy::all, missing_docs, rust_2018_idioms)]
mod server;
use std::borrow::Cow;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use cfg_if::cfg_if;
use futures_core::Stream;
use librespot_core as core;
use thiserror::Error;
use self::server::DiscoveryServer;
pub use crate::core::authentication::Credentials;
pub use crate::core::config::DeviceType;
pub struct Discovery {
server: DiscoveryServer,
#[cfg(not(feature = "with-dns-sd"))]
_svc: libmdns::Service,
#[cfg(feature = "with-dns-sd")]
_svc: dns_sd::DNSService,
}
pub struct Builder {
server_config: server::Config,
port: u16,
}
#[derive(Debug, Error)]
pub enum Error {
#[error("Setting up dns-sd failed: {0}")]
DnsSdError(#[from] io::Error),
#[error("Setting up the http server failed: {0}")]
HttpServerError(#[from] hyper::Error),
}
impl Builder {
pub fn new(device_id: impl Into<String>) -> Self {
Self {
server_config: server::Config {
name: "Librespot".into(),
device_type: DeviceType::default(),
device_id: device_id.into(),
},
port: 0,
}
}
pub fn name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.server_config.name = name.into();
self
}
pub fn device_type(mut self, device_type: DeviceType) -> Self {
self.server_config.device_type = device_type;
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
pub fn launch(self) -> Result<Discovery, Error> {
let mut port = self.port;
let name = self.server_config.name.clone().into_owned();
let server = DiscoveryServer::new(self.server_config, &mut port)?;
let svc;
cfg_if! {
if #[cfg(feature = "with-dns-sd")] {
svc = dns_sd::DNSService::register(
Some(name.as_ref()),
"_spotify-connect._tcp",
None,
None,
port,
&["VERSION=1.0", "CPath=/"],
)
.unwrap();
} else {
let responder = libmdns::Responder::spawn(&tokio::runtime::Handle::current())?;
svc = responder.register(
"_spotify-connect._tcp".to_owned(),
name,
port,
&["VERSION=1.0", "CPath=/"],
)
}
};
Ok(Discovery { server, _svc: svc })
}
}
impl Discovery {
pub fn builder(device_id: impl Into<String>) -> Builder {
Builder::new(device_id)
}
pub fn new(device_id: impl Into<String>) -> Result<Self, Error> {
Self::builder(device_id).launch()
}
}
impl Stream for Discovery {
type Item = Credentials;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.server).poll_next(cx)
}
}