notbot 0.6.13

Matrix chatbot, primarily used around the Warsaw Hackerspace channels and spaces
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
//! Queries Frogejo for latest, and oldest open issues pull request, and post notifications about new events.
//!
//! # Configuration
//!
//! [`ForgejoConfig`]
//!
//! ```toml
//! [module."notbot::forgejo".instances.example]
//! instance_url = "https://code.example.org"
//! token_name = "notbot-test"
//! token_secret = "…"
//! organizations = [ "orga" ]
//! feed_rooms = [
//!     "#bottest:example.net",
//!     "#infra:example.org",
//! ]
//! events = [
//!     "create_pull_request",
//!     "merge_pull_request",
//!     "pull_request_ready_for_review",
//!     "approve_pull_request",
//!     "reject_pull_request",
//!     "create_issue",
//!     "close_issue",
//!     "reopen_pull_request",
//! ]
//!
//! [module."notbot::forgejo".rooms]
//! "default" = "example"
//!
//! [module."notbot::forgejo"]
//! feed_interval = 5
//! ```
//!
//! # Usage
//!
//! Keywords:
//! * `pr-new`, `prnew`, `pr`, `p` - [`forgejo_query`] - show latest open pull requests
//! * `pr-old`, `prold` - [`forgejo_query`] - show oldest open pull requests
//! * `issue-new`, `issuenew`, `issue`, `i` - [`forgejo_query`] - show latest issues
//! * `issue-old`, `issueold` - [`forgejo_query`] - show oldest open issues
//!
//! Like with many other so-called binaries in life, turns out that the PR/issue one is
//! false as well.
//!
//! Passive feed updates: [`forgejo_feeds`]
//! Provides updates about configured events to configured rooms.

use crate::prelude::*;

use std::fmt::Debug;

use tokio::time::{Duration, interval};

use forgejo_api::structs::ActivityOpType;
use forgejo_api::{Auth, Forgejo};

use askama::Template;

/// Configuration of a forgejo instance.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct ForgejoInstance {
    /// Base instance URL.
    pub instance_url: String,
    /// Configured token name.
    pub token_name: String,
    /// Generated token secret.
    pub token_secret: String,
    /// Organization to observe changes in.
    pub organization: String,
    /// Room to post updates to.
    pub feed_rooms: Vec<String>,
    /// Event types to post about
    #[serde(default = "forgejo_events_default")]
    pub events: Vec<ActivityOpType>,
}

/// Default event types to post notifications for
#[must_use]
pub fn forgejo_events_default() -> Vec<ActivityOpType> {
    use ActivityOpType::{
        ApprovePullRequest, CloseIssue, ClosePullRequest, CreateIssue, CreatePullRequest,
        CreateRepo, MergePullRequest, PullRequestReadyForReview, RejectPullRequest, ReopenIssue,
        ReopenPullRequest,
    };
    vec![
        CreatePullRequest,
        MergePullRequest,
        PullRequestReadyForReview,
        ApprovePullRequest,
        RejectPullRequest,
        ReopenPullRequest,
        ClosePullRequest,
        CreateIssue,
        CloseIssue,
        ReopenIssue,
        CreateRepo,
    ]
}

/// General module configuration
#[derive(Clone, Debug, Deserialize)]
pub struct ForgejoConfig {
    /// Instance to act upon in a given room. Special key "default" signifies the default instance if none is configured for a given room.
    pub rooms: HashMap<String, String>,
    /// How often the feeds should be checked, in minutes.
    #[serde(default = "feed_interval")]
    pub feed_interval: u64,
    /// How many issues/PRs should be returned on active queries
    #[serde(default = "objects_count")]
    pub objects_count: u16,
    /// Map of Forgejo instances to query and observe
    pub instances: HashMap<String, ForgejoInstance>,
    /// Keywords for displaying list of latest open pull requests.
    #[serde(default = "keywords_pr_new")]
    pub keywords_pr_new: Vec<String>,
    /// Keywords for displaying list of oldest open pull requests.
    #[serde(default = "keywords_pr_old")]
    pub keywords_pr_old: Vec<String>,
    /// Keywords for displaying list of latest open issues.
    #[serde(default = "keywords_issue_new")]
    pub keywords_issue_new: Vec<String>,
    /// Keywords for displaying list of oldest open issues.
    #[serde(default = "keywords_issue_old")]
    pub keywords_issue_old: Vec<String>,
}

/// Default value for feed checking interval: 5 minutes
#[must_use]
pub const fn feed_interval() -> u64 {
    5
}

/// Default value for returned objects count: 3
#[must_use]
pub const fn objects_count() -> u16 {
    3
}

/// Default keywords for displaying list of latest open pull requests: pr-new, prnew, pr, p
#[must_use]
pub fn keywords_pr_new() -> Vec<String> {
    vec!["pr-new".s(), "prnew".s(), "prs".s(), "pr".s()]
}

/// Default keywords for displaying list of oldest open pull requests: pr-old, prold
#[must_use]
pub fn keywords_pr_old() -> Vec<String> {
    vec!["pr-old".s(), "prold".s()]
}

/// Default keywords for displaying list of latest open issues: issue-new, issuenew, issue, i
#[must_use]
pub fn keywords_issue_new() -> Vec<String> {
    vec![
        "issue-new".s(),
        "issues-new".s(),
        "issuenew".s(),
        "issue".s(),
        "issues".s(),
    ]
}

/// Default keywords for displaying list of oldest open issues: issue-old, issueold
#[must_use]
pub fn keywords_issue_old() -> Vec<String> {
    vec!["issue-old".s(), "issues-old".s(), "issueold".s()]
}

pub(crate) fn starter(_: &Client, config: &Config) -> anyhow::Result<Vec<ModuleInfo>> {
    info!("registering modules");
    let forgejo_config: ForgejoConfig = config.typed_module_config(module_path!())?;

    let mut keywords = vec![];
    keywords.extend(forgejo_config.keywords_pr_new.clone());
    keywords.extend(forgejo_config.keywords_pr_old.clone());

    keywords.extend(forgejo_config.keywords_issue_new.clone());
    keywords.extend(forgejo_config.keywords_issue_old.clone());

    Ok(vec![ModuleInfo::new(
        "forgejo-query",
        "display list of open issues or pull requests, oldest or newest",
        vec![],
        TriggerType::Keyword(keywords),
        None,
        forgejo_config,
        forgejo_query,
    )])
}

#[derive(thiserror::Error, Debug)]
enum EarlyFailCheck {
    #[error("no instances configured")]
    NoInstancesConfigured,
    #[error("argument provided was not found")]
    ProvidedNotFound,
    #[error("no argument provided and >1 instance configured")]
    NotProvidedMany,
}

async fn early_fail(
    event: ConsumerEvent,
    config: &ForgejoConfig,
) -> anyhow::Result<(String, Forgejo)> {
    use EarlyFailCheck::{NoInstancesConfigured, NotProvidedMany, ProvidedNotFound};

    let instance = if config.instances.keys().len() == 0 {
        event
            .room
            .send(RoomMessageEventContent::text_plain(
                "No instances configured",
            ))
            .await?;
        return Err(NoInstancesConfigured.into());
    } else if event.args.is_none() {
        if config.instances.keys().len() == 1 {
            config
                .instances
                .values()
                .last()
                .ok_or_else(|| anyhow!("wtf? empty instances list"))?
                .to_owned()
        } else {
            event
                .room
                .send(RoomMessageEventContent::text_plain(
                    "No arguments provided and more than one instance configured",
                ))
                .await?;
            return Err(NotProvidedMany.into());
        }
    } else if config.instances.contains_key(
        &event
            .args
            .clone()
            .ok_or_else(|| anyhow!("wtf? empty args should've been cought earlier"))?,
    ) {
        config
            .instances
            .get(
                &event
                    .args
                    .ok_or_else(|| anyhow!("wtf? empty args should've been cought earlier"))?,
            )
            .ok_or_else(|| anyhow!("wtf? empty instances should've been cought earlier"))?
            .to_owned()
    } else {
        event
            .room
            .send(RoomMessageEventContent::text_plain(
                "Argument provided but instance not found",
            ))
            .await?;
        return Err(ProvidedNotFound.into());
    };

    let auth = Auth::Token(&instance.token_secret);
    let forgejo = Forgejo::new(auth, instance.instance_url.parse()?)?;

    Ok((instance.organization, forgejo))
}

/// Display list of open issues or pull requests
///
/// # Errors
/// Will return `Err` or malformed Forgejo API responses
pub async fn forgejo_query(event: ConsumerEvent, config: ForgejoConfig) -> anyhow::Result<()> {
    use forgejo_api::structs::{
        Issue, IssueListIssuesQuery, IssueListIssuesQueryState, IssueListIssuesQueryType,
        OrgListReposQuery,
    };
    let (organization, forgejo) = early_fail(event.clone(), &config).await?;
    let repo_query = OrgListReposQuery {
        page: Some(1),
        limit: Some(0),
    };

    let query_type = if config.keywords_issue_new.contains(&event.keyword)
        || config.keywords_issue_old.contains(&event.keyword)
    {
        IssueListIssuesQueryType::Issues
    } else {
        IssueListIssuesQueryType::Pulls
    };

    let issue_query = IssueListIssuesQuery {
        state: Some(IssueListIssuesQueryState::Open),
        labels: None,
        q: None,
        r#type: Some(query_type),
        milestones: None,
        since: None,
        before: None,
        created_by: None,
        assigned_by: None,
        mentioned_by: None,
        page: None,
        limit: None,
    };

    let mut items: Vec<Issue> = vec![];

    let (_, repos) = forgejo.org_list_repos(&organization, repo_query).await?;

    for repo in repos {
        if repo.has_issues.is_some_and(|i| i) {
            let (_, repo_issues) = forgejo
                .issue_list_issues(
                    &organization,
                    &repo
                        .name
                        .ok_or_else(|| anyhow!("wtf? empty repository name response from API"))?,
                    issue_query.clone(),
                )
                .await?;
            items.extend(repo_issues);
        }
    }

    items.sort_by_key(|i| i.updated_at.unwrap_or(time::OffsetDateTime::UNIX_EPOCH));
    let shortlist: Vec<Issue> = if config.keywords_issue_old.contains(&event.keyword)
        || config.keywords_pr_old.contains(&event.keyword)
    {
        items
            .iter()
            .take(config.objects_count.into())
            .map(std::borrow::ToOwned::to_owned)
            .collect()
    } else {
        items
            .iter()
            .rev()
            .take(config.objects_count.into())
            .map(std::borrow::ToOwned::to_owned)
            .collect()
    };

    let render_items = RenderItems { items: shortlist };
    let message = RoomMessageEventContent::text_html(
        render_items.as_plain().render()?,
        render_items.as_formatted().render()?,
    );

    event.room.send(message).await?;

    Ok(())
}

#[derive(Template)]
#[template(
    path = "matrix/forgejo-formatted.html",
    blocks = ["formatted", "plain"],
)]
struct RenderItems {
    items: Vec<forgejo_api::structs::Issue>,
}

pub(crate) fn workers(mx: &Client, config: &Config) -> anyhow::Result<Vec<WorkerInfo>> {
    info!("registering workers");
    let forgejo_config: ForgejoConfig = config.typed_module_config(module_path!())?;
    Ok(vec![WorkerInfo::new(
        "forgejo",
        "observes forgejo organization feeds for configured events",
        "forgejo",
        mx.clone(),
        forgejo_config,
        forgejo_feeds,
    )])
}

/// Worker spawning forgejo feeds processor in configured intervals.
///
/// # Errors
/// Will return `Err` if:
/// * module is misconfigured
/// * configuration behaves weirdly at runtime
/// *
pub async fn forgejo_feeds(mx: Client, module_config: ForgejoConfig) -> anyhow::Result<()> {
    let mut interval = interval(Duration::from_secs(60 * module_config.feed_interval));
    // (instance name, org)
    let mut first_loop: HashMap<String, bool> = HashMap::default();
    // (name, instance)
    let mut instances: HashMap<String, Forgejo> = HashMap::default();
    // (instance name, org)
    let mut activities: HashMap<(String, String), Vec<forgejo_api::structs::Activity>> =
        HashMap::default();

    for (name, config) in module_config.instances.clone() {
        let auth = Auth::Token(&config.token_secret);
        let forgejo = match Forgejo::new(auth, config.instance_url.parse()?) {
            Ok(f) => f,
            Err(e) => {
                error!("invalid forgejo configuration: {e}");
                continue;
            }
        };
        instances.insert(name.clone(), forgejo);
        first_loop.insert(name.clone(), true);
    }

    loop {
        interval.tick().await;

        for (name, forgejo) in &instances {
            trace!("processing feeds for instance: {name}");

            let config = module_config
                .instances
                .get(name)
                .ok_or_else(|| anyhow!("wtf? weird misconfiguration?"))?;
            let mut potentially_pushed_activities = vec![];

            let org = &config.organization;

            let query = forgejo_api::structs::OrgListActivityFeedsQuery {
                date: None,
                page: None,
                limit: None,
            };
            let (_, returned_activities) = match forgejo.org_list_activity_feeds(org, query).await {
                Ok(v) => v,
                Err(e) => {
                    error!("error fetching org {org} activity feed: {e}");
                    continue;
                }
            };

            let known_act_ids: Vec<i64>;
            let mut new_known_activities = vec![];

            if let Some(known_act) = activities.get(&(name.to_owned(), org.to_owned())) {
                // can .unwrap(): activites get added to known list only if id.is_some()
                known_act_ids = known_act.iter().map(|a| a.id.unwrap_or_default()).collect();
            } else {
                activities.insert((name.to_owned(), org.to_owned()), vec![]);
                known_act_ids = vec![];
            };

            for activity in returned_activities {
                if let Some(a_id) = activity.id {
                    new_known_activities.push(activity.clone());
                    if !known_act_ids.contains(&a_id)
                        && activity
                            .op_type
                            .is_some_and(|op| config.events.contains(&op))
                    {
                        potentially_pushed_activities.push(activity);
                    }
                }
            }

            activities.insert((name.to_owned(), org.to_owned()), new_known_activities);

            if first_loop
                .get(name)
                .ok_or_else(|| anyhow!("wtf? iterating over previously unknown instance?"))?
                .to_owned()
            {
                first_loop.insert(name.to_owned(), false);

                continue;
            }

            if potentially_pushed_activities.is_empty() {
                continue;
            }

            let render_feed = activity_fmt::RenderFeed {
                items: potentially_pushed_activities,
            };

            let plain = render_feed.as_plain().render()?;
            let html = render_feed.as_formatted().render()?;

            for room_name in &config.feed_rooms {
                let Ok(room) = maybe_get_room(&mx, room_name).await else {
                    continue;
                };

                if let Err(e) = room
                    .send(RoomMessageEventContent::text_html(
                        plain.clone(),
                        html.clone(),
                    ))
                    .await
                {
                    error!("failed to send message: {e}");
                }
            }
        }
    }
}

pub mod activity_fmt {
    //! Formating forgejo feed activities, separated into its own module.
    use crate::tools::ToStringExt;
    use askama::Template;
    use forgejo_api::structs::{Activity, ActivityOpType};
    use reqwest::Url;
    use serde_derive::Deserialize;
    use unicode_ellipsis::truncate_str;

    /// Object for rendering a Matrix message from filtered forgejo feed results.
    #[derive(Template)]
    #[template(
        path = "matrix/forgejo-observer.html",
        blocks = ["formatted", "plain"],
    )]
    pub struct RenderFeed {
        /// List of activities to render
        pub items: Vec<Activity>,
    }

    /// Turns act.content into formatted response part. Applicable for PRs and Issues only
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn act_content_part_html(repo_url: &Url, item: &str, content: String) -> Option<String> {
        let mut parts = content.splitn(3, '|');
        let item_nr = parts.next()?;
        let item_title = parts
            .next()
            .map_or_else(|| "".s(), |title| format!(" {}", truncate_str(title, 60)));
        let item_emoji = parts
            .next()
            .map_or_else(|| "".s(), |emoji| format!(" {emoji}"));

        let item_url = format!("{repo_url}/{item}/{item_nr}");
        Some(format!(
            r#"<a href="{item_url}">#{item_nr}{item_title}{item_emoji}</a>"#,
        ))
    }

    /// Turns act.content into plain response part. Applicable for PRs and Issues only
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn act_content_part_plain(repo_url: &Url, item: &str, content: String) -> Option<String> {
        let mut parts = content.splitn(3, '|');
        let item_nr = parts.next()?;
        let item_title = parts
            .next()
            .map_or_else(|| "".s(), |title| format!(" {}", truncate_str(title, 60)));
        let item_emoji = parts
            .next()
            .map_or_else(|| "".s(), |emoji| format!(" {emoji}"));

        let item_url = format!("{repo_url}/{item}/{item_nr}");
        Some(format!(r"{item_url}{item_title}{item_emoji}",))
    }

    fn content_commits(s: &str) -> anyhow::Result<ContentCommits> {
        let data: ContentCommits = match serde_json::from_str(s) {
            Ok(d) => d,
            Err(e) => anyhow::bail!("err while parsing commit details from activity: {e}"),
        };

        Ok(data)
    }

    /// Generated from the json that's *sometimes* present in `content` field in [`Activity`]
    #[allow(missing_docs)]
    #[derive(Default, Debug, Clone, Deserialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct ContentCommits {
        pub commits: Vec<Commit>,
        pub head_commit: Commit,
        #[serde(rename = "CompareURL")]
        pub compare_url: String,
        pub len: i64,
    }

    #[allow(missing_docs)]
    #[derive(Default, Debug, Clone, Deserialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct Commit {
        pub sha1: String,
        pub message: String,
        pub author_email: String,
        pub author_name: String,
        pub committer_email: String,
        pub committer_name: String,
        pub timestamp: String,
    }
}