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
|
use serde::Deserialize;
use std::path::{PathBuf, Path};
use std::env;
use std::io;
use std::time::Duration;
use std::sync::Arc;
use std::fmt;
use rand::RngExt;
use log::{info, debug, warn, trace, error};
use tokio::signal::unix::{signal, SignalKind};
use tokio::task::JoinSet;
#[derive(Deserialize, Debug)]
struct PollRes {
content: Option<PollResContent>
}
#[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "UPPERCASE")]
enum Status {
Open,
Close,
#[serde(other)]
Unknown,
}
enum Transition {
WentOpen { recovered: bool },
WentClose,
Nop { prev: Status, curr: Status },
}
#[derive(Deserialize, Default)]
struct Hooks {
went_open: Option<String>,
went_close: Option<String>
}
impl Hooks {
fn script(&self, t: &Transition) -> Option<&str> {
match t {
Transition::WentOpen { .. } => self.went_open.as_deref(),
Transition::WentClose => self.went_close.as_deref(),
_ => None,
}
}
}
impl Status {
fn transition_from(self, prev: Status) -> Transition {
use Status::*;
use Transition::*;
match (prev, self) {
(Close, Open) => WentOpen { recovered: false },
(Unknown, Open) => WentOpen { recovered: true },
(Open, Close) => WentClose,
// no useful information given to user
(_, _) => Nop { prev, curr: self },
}
}
}
#[derive(Deserialize, Debug)]
struct PollResContent {
#[serde(rename = "liveTitle")]
live_title: Option<String>,
status: Status
}
#[derive(Deserialize)]
struct Channel {
id: String,
alias: Option<String>,
}
impl fmt::Display for Channel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.alias {
Some(a) => write!(f, "{}", a),
None => write!(f, "{}", self.id)
}
}
}
impl Channel {
async fn fetch(&self, client: &reqwest::Client) -> Result<PollRes, reqwest::Error> {
let id = &self.id;
let url = format!("https://api.chzzk.naver.com/polling/v2/channels/{id}/live-status");
client.get(&url)
.send()
.await?
.error_for_status()?
.json()
.await
}
pub async fn event_loop(&self, client: &reqwest::Client, timeout: u64, hooks: &Hooks) {
// Receive notifications for already opened broadcasts when first run
let mut prev = Status::Close;
let mut errs = 0;
loop {
(prev, errs) = self.tick(client, prev, errs, &hooks).await;
let phase = jittered(timeout, errs);
debug!("{self}: sleep for {phase:?}");
tokio::time::sleep(phase).await;
}
}
async fn tick(
&self,
client: &reqwest::Client, prev: Status, errs: u32, hooks: &Hooks
) -> (Status, u32) {
match self.fetch(client).await {
Ok(res) => {
trace!("{self}: {res:?}");
let content = match res.content {
Some(c) => c,
None => return (prev, errs)
};
self.event(prev, &content, hooks);
(content.status, 0)
}
Err(e) => {
let errs = errs.saturating_add(1);
warn!("{self}: fetch failed (x{}): {e:#}", errs);
(prev, errs)
}
}
}
fn event(&self, prev: Status, content: &PollResContent, hooks: &Hooks) {
let tr = content.status.transition_from(prev);
let title = content.live_title.as_deref().unwrap_or("");
match tr {
Transition::WentOpen { recovered } => {
if recovered {
warn!("{self}: open from unknown state: {title}");
}
info!("{self}: WentOpen: {title}");
},
Transition::WentClose => {
info!("{self}: WentClose: {title}");
},
Transition::Nop { prev, curr } => {
trace!("{self}: Nop: {prev:?} => {curr:?}");
}
}
if let Some(sc) = hooks.script(&tr) {
let mut cmd = tokio::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg(sc)
.env("CHZZKD_ALIAS", self.to_string())
.env("CHZZKD_LIVE_TITLE", title)
.env("CHZZKD_ID", &self.id);
if let Transition::WentOpen { recovered } = tr {
cmd.env("CHZZKD_RECOVERED", if recovered { "1" } else { "0" });
}
// Here tokio runtime simply forks/execs and reaps it at
// poll loop later. i.e. if the script runs in an infinite
// loop, it will just run forever in the forked process,
// and chzzkd cannot detect it.
match cmd.spawn() {
Ok(_child) => {}
Err(e) => warn!("{self}: hook spawn failed: {e}"),
}
}
}
}
#[derive(Deserialize)]
struct Config {
#[serde(default = "default_timeout")]
timeout: u64,
#[serde(default)]
hooks: Hooks,
channel: Vec<Channel>,
}
fn default_timeout() -> u64 {
10
}
fn jittered(timeout: u64, errs: u32) -> Duration {
let backoff = 1u64 << errs.min(3); // 1x 2x 4x 8x
let secs = (timeout * backoff) as f64 * rand::rng().random_range(0.9..1.1);
Duration::from_secs_f64(secs)
}
async fn watch(cfg: Arc<Config>, idx: usize, client: reqwest::Client) {
let ch = &cfg.channel[idx];
ch.event_loop(&client, cfg.timeout, &cfg.hooks).await;
}
/// Resolves config file path. Precedence:
/// 1. argv[1]
/// 2. $XDG_CONFIG_HOME/chzzkd/config.toml
/// 3. $HOME/.config/chzzkd/config.toml
/// 4. /etc/chzzkd/config.toml
fn resolve_cfg_path() -> Result<PathBuf, io::Error> {
if let Some(arg) = env::args_os().nth(1) {
let p = PathBuf::from(arg);
return if p.is_file() {
Ok(p)
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("{}: no such config file", p.display()),
))
};
}
let xdg = env::var_os("XDG_CONFIG_HOME")
.filter(|s| !s.is_empty())
.map(|d| PathBuf::from(d).join("chzzkd/config.toml"));
let home = env::var_os("HOME")
.filter(|s| !s.is_empty())
.map(|h| PathBuf::from(h).join(".config/chzzkd/config.toml"));
xdg.into_iter()
.chain(home)
.chain(std::iter::once(PathBuf::from("/etc/chzzkd/config.toml")))
.find(|p| p.is_file())
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config file found"))
}
fn load_cfg(path: &Path) -> anyhow::Result<Arc<Config>> {
let s = std::fs::read_to_string(path)?;
Ok(Arc::new(toml::from_str::<Config>(&s)?))
}
fn spawn_all(cfg: &Arc<Config>, client: &reqwest::Client) -> JoinSet<()> {
let mut set = JoinSet::new();
for i in 0..cfg.channel.len() {
set.spawn(watch(cfg.clone(), i, client.clone()));
}
set
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::init();
let mut hup = signal(SignalKind::hangup())?;
let client = reqwest::Client::builder()
.user_agent("Mozilla/5.0")
.timeout(Duration::from_secs(5))
.build()?;
let cfg_path = resolve_cfg_path()?;
info!("Found config {:?}, using it", cfg_path);
let mut cfg = load_cfg(&cfg_path)?;
let mut tasks = spawn_all(&cfg, &client);
loop {
tokio::select! {
_ = hup.recv() => {
match load_cfg(&cfg_path) {
Ok(new_cfg) => {
info!("Received SIGHUP: reloading {} channels", new_cfg.channel.len());
tasks.shutdown().await;
cfg = new_cfg;
tasks = spawn_all(&cfg, &client);
}
Err(e) => {
warn!("Received SIGHUP: reload failed, keeping running config: {e:#}");
}
}
}
Some(res) = tasks.join_next() => {
match res {
Ok(()) => warn!("watcher exited unexpectedly"),
Err(e) if e.is_cancelled() => {}
Err(e) => error!("watcher panicked: {e}"),
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_config() -> Config {
Config {
timeout: 10,
hooks: Hooks {
went_open: Some("echo $CHZZKD_ALIAS: $CHZZKD_LIVE_TITLE".into()),
..Default::default()
},
channel: vec![
Channel {
id: "c847a58a1599988f6154446c75366523".into(),
alias: Some("dopa".into())
},
Channel {
id: "a7e175625fdea5a7d98428302b7aa57f".into(),
alias: Some("chamcham".into())
},
Channel {
id: "6e06f5e1907f17eff543abd06cb62891".into(),
alias: Some("nokduro".into())
},
Channel {
id: "9381e7d6816e6d915a44a13c0195b202".into(),
alias: Some("lck".into())
},
Channel {
id: "0b33823ac81de48d5b78a38cdbc0ab94".into(),
alias: Some("wolf".into())
},
Channel {
id: "42597020c1a79fb151bd9b9beaa9779b".into(),
alias: Some("paka".into())
},
Channel {
id: "26ae7850ad5b6b09ca864d482dc7fa50".into(),
alias: Some("qb".into())
},
Channel {
id: "c100f81959d1c17044be0541eed56f5b".into(),
alias: Some("megajw".into())
},
Channel {
id: "b5ed5db484d04faf4d150aedd362f34b".into(),
alias: Some("gg".into())
},
Channel {
id: "8b3e8e3a13201cff0836c69cfab62f45".into(),
alias: Some("flame".into())
},
Channel {
id: "6cac96d5c9b7a9fd28903aa32fc61749".into(),
alias: Some("hd".into())
},
Channel {
id: "bc2dbff369307b5c446224cce192c8b1".into(),
alias: Some("goarosa".into())
},
Channel {
id: "732f6f16d20991243ec3f2d7afed8821".into(),
alias: Some("0du".into())
},
Channel {
id: "96e44e40a448971244bfd9dd8c832505".into(),
alias: Some("gn".into())
},
],
}
}
#[test]
fn toml_parses() {
let cfg: Config = toml::from_str(r#"
[[channel]]
id = "abc"
alias = "x"
[[channel]]
id = "def"
"#).unwrap();
assert_eq!(cfg.timeout, default_timeout());
assert!(cfg.hooks.went_open.is_none());
assert_eq!(cfg.channel.len(), 2);
}
#[tokio::test]
#[ignore] // do API request
async fn live_tick() {
let client = reqwest::Client::builder()
.user_agent("Mozilla/5.0")
.build().unwrap();
let cfg = sample_config();
for ch in &cfg.channel {
let (status, errs) = ch.tick(&client, Status::Close, 0, &cfg.hooks).await;
assert_eq!(errs, 0, "{ch}: fetch failed");
assert_ne!(status, Status::Unknown, "{ch}: unknown status");
}
}
}
|