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
use std::{
    fs::File, io::Read, pin::Pin, rc::Rc, sync::Arc, task::Poll, time::Duration,
};

use anyhow::Result;
use async_trait::async_trait;
use derive_builder::Builder;
use futures::{FutureExt, StreamExt};
use lazy_static::lazy_static;
use regex::Regex;
use reqwest::{
    header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, USER_AGENT},
    Client,
};
use serde::Deserialize;
use tokio::{
    task::{self, JoinHandle},
    time::{interval, Interval},
};
use tokio_stream::Stream;

use crate::{
    bar::PanelDrawInfo,
    common::{draw_common, PanelCommon},
    remove_array_from_config, remove_bool_from_config,
    remove_string_from_config, remove_uint_from_config, PanelConfig,
};

lazy_static! {
    static ref REGEX: Regex =
        Regex::new(r#"<(?<url>\S*)>; rel="next""#).unwrap();
}

/// Displays the number of github notifications you have.
#[derive(Builder)]
#[builder_struct_attr(allow(missing_docs))]
#[builder_impl_attr(allow(missing_docs))]
pub struct Github {
    name: &'static str,
    #[builder(default = "Duration::from_secs(60)")]
    interval: Duration,
    token: String,
    #[builder(default = "Vec::new()")]
    filter: Vec<String>,
    #[builder(default)]
    include: bool,
    #[builder(default = "true")]
    show_zero: bool,
    format: &'static str,
    common: PanelCommon,
}

impl Github {
    fn draw(
        &self,
        cr: &Rc<cairo::Context>,
        height: i32,
        count: usize,
    ) -> Result<PanelDrawInfo> {
        let mut text = if !self.show_zero && count == 0 {
            String::new()
        } else {
            self.format.replace("%count%", count.to_string().as_str())
        };

        if count == 50 {
            text.push('+');
        }

        draw_common(
            cr,
            text.as_str(),
            &self.common.attrs[0],
            self.common.dependence,
            self.common.images.clone(),
            height,
        )
    }
}

#[async_trait(?Send)]
impl PanelConfig for Github {
    /// Configuration options:
    ///
    /// - `interval`: how long to wait between requests. The panel will never
    ///   poll more often than this, but it may poll less often according to the
    ///   `X-Poll-Interval` header of the reponse. See
    ///   <https://docs.github.com/en/rest/activity/notifications?apiVersion=2022-11-28#about-github-notifications>
    ///   for more information.
    /// - `token`: A file path containing your GitHub token. Visit <https://github.com/settings/tokens/new>
    ///   to generate a token. The `notifications` scope is required.
    /// - `filter`: An array of strings corresponding to notification reasons.
    ///   See <https://docs.github.com/en/rest/activity/notifications?apiVersion=2022-11-28#about-notification-reasons>
    ///   for details.
    /// - `include`: Whether to include or exclude the reasons in `filter`. If
    ///   `include` is true, only notifications with one of the reasons in
    ///   `filter` will be counted. Otherwise, only notifications with reasons
    ///   not in `filter` will be counted.
    /// - `show_zero`: Whether or not the panel is shown when you have zero
    ///   notifications.
    ///
    /// See [`PanelCommon::parse`].
    fn parse(
        name: &'static str,
        table: &mut std::collections::HashMap<String, config::Value>,
        _global: &config::Config,
    ) -> anyhow::Result<Self> {
        let mut builder = GithubBuilder::default();

        builder.name(name);

        if let Some(interval) = remove_uint_from_config("interval", table) {
            builder.interval(Duration::from_secs(interval.max(1) * 60));
        }

        if let Some(path) = remove_string_from_config("token", table) {
            let mut token = String::new();
            File::open(path)?.read_to_string(&mut token)?;

            builder.token(token);
        }

        if let Some(filter) = remove_array_from_config("filter", table) {
            builder.filter(
                filter
                    .iter()
                    .filter_map(|v| v.clone().into_string().ok())
                    .collect(),
            );
        }

        if let Some(include) = remove_bool_from_config("include", table) {
            builder.include(include);
        }

        if let Some(show_zero) = remove_bool_from_config("show_zero", table) {
            builder.show_zero(show_zero);
        }

        let (common, formats) =
            PanelCommon::parse(table, &[""], &["%count%"], &[""], &[])?;

        builder.common(common);
        builder.format(formats.into_iter().next().unwrap().leak());

        Ok(builder.build()?)
    }

    fn props(&self) -> (&'static str, bool) {
        (self.name, self.common.visible)
    }

    async fn run(
        mut self: Box<Self>,
        cr: std::rc::Rc<cairo::Context>,
        global_attrs: crate::attrs::Attrs,
        height: i32,
    ) -> anyhow::Result<(
        crate::PanelStream,
        Option<
            crate::ipc::ChannelEndpoint<
                crate::bar::Event,
                crate::bar::EventResponse,
            >,
        >,
    )> {
        for attr in &mut self.common.attrs {
            attr.apply_to(&global_attrs);
        }

        let stream = GithubStream::new(
            self.token.as_str(),
            self.interval,
            self.filter.clone(),
            self.include,
        )?
        .map(move |r| self.draw(&cr, height, r?));

        Ok((Box::pin(stream), None))
    }
}

struct GithubStream {
    handle: Option<JoinHandle<Result<usize>>>,
    interval: Arc<futures::lock::Mutex<Interval>>,
    filter: Vec<String>,
    include: bool,
    client: Client,
}

impl GithubStream {
    pub fn new(
        token: &str,
        duration: Duration,
        filter: Vec<String>,
        include: bool,
    ) -> Result<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(
            ACCEPT,
            HeaderValue::from_static("application/vnd.github+json"),
        );
        headers.insert(
            "X-Github-Api-Version",
            HeaderValue::from_static("2022-11-28"),
        );
        headers.insert(USER_AGENT, HeaderValue::from_static("lazybar"));
        let mut secret =
            HeaderValue::from_str(format!("Bearer {}", token.trim()).as_str())?;
        secret.set_sensitive(true);
        headers.insert(AUTHORIZATION, secret);
        let client = Client::builder().default_headers(headers).build()?;
        let interval = Arc::new(futures::lock::Mutex::new(interval(duration)));
        Ok(Self {
            handle: None,
            interval,
            filter,
            include,
            client,
        })
    }
}

impl Stream for GithubStream {
    type Item = Result<usize>;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        if let Some(ref mut handle) = &mut self.handle {
            let val = handle.poll_unpin(cx).map(Result::ok);

            if val.is_ready() {
                self.handle = None;
            }

            val
        } else {
            let interval = self.interval.clone();
            let filter = self.filter.clone();
            let include = self.include;
            let client = self.client.clone();
            self.handle = Some(task::spawn(get_notifications(
                interval, filter, include, client,
            )));

            Poll::Pending
        }
    }
}

async fn get_notifications(
    interval: Arc<futures::lock::Mutex<Interval>>,
    filter: Vec<String>,
    include: bool,
    client: Client,
) -> Result<usize> {
    interval.lock().await.tick().await;

    let request = client.get("https://api.github.com/notifications").build()?;

    let response = client.execute(request).await?;

    let headers = response.headers().clone();
    let wait = headers
        .get("X-Poll-Interval")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse().ok())
        .unwrap_or(60);

    interval.lock().await.reset_after(Duration::from_secs(wait));

    let body = response.json::<Vec<Thread>>().await?;

    let count = body
        .into_iter()
        .filter(|t| !(include ^ filter.contains(&t.reason)))
        .count();

    Ok(count)
}

#[derive(Deserialize, Debug)]
#[non_exhaustive]
struct Thread {
    reason: String,
}