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
/*
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

use crate::page::InfoResponse;
use crate::{Bot, Page, Result};
use mwapi_responses::prelude::*;
use std::collections::HashMap;
use tokio::sync::mpsc;

type Receiver = mpsc::Receiver<Result<Page>>;

/// A structure to manage query parameters, but keeps continuation separate
#[derive(Default)]
struct Params {
    main: HashMap<String, String>,
    continue_: HashMap<String, String>,
}

impl Params {
    /// Merge the main and continuation parameters into one map
    fn merged(&self) -> HashMap<&String, &String> {
        let mut map = HashMap::new();
        map.extend(&self.main);
        map.extend(&self.continue_);
        map
    }
}

/// Recursively get pages that are in given category. Note that it is fully
/// possible to get pages multiple times if they're present in multiple
/// categories.
///
/// To prevent infinite loops, the generator keeps track of categories seen
/// and will not recurse through it multiple times.
pub fn categorymembers_recursive(bot: &Bot, title: &str) -> Receiver {
    let (tx, rx) = mpsc::channel(50);
    let title = title.to_string();
    let bot = bot.clone();
    tokio::spawn(async move {
        // Categories we've already seen
        let mut seen = vec![];
        // Categories that are pending
        let mut pending = vec![title];
        while let Some(category) = pending.pop() {
            // Mark as having seen it to stop loops
            seen.push(category.to_string());
            let mut gen = categorymembers(&bot, &category);
            while let Some(page) = gen.recv().await {
                if let Ok(page) = &page {
                    if page.is_category()
                        && !seen.contains(&page.title().to_string())
                        && !pending.contains(&page.title().to_string())
                    {
                        pending.push(page.title().to_string());
                    }
                }
                if tx.send(page).await.is_err() {
                    // Receiver hung up, just abort
                    return;
                }
            }
        }
    });
    rx
}

/// Get pages that are in the given category
pub fn categorymembers(bot: &Bot, title: &str) -> Receiver {
    generator(
        bot,
        HashMap::from([
            ("generator".to_string(), "categorymembers".to_string()),
            ("gcmtitle".to_string(), title.to_string()),
            ("gcmlimit".to_string(), "max".to_string()),
        ]),
    )
}

/// Get pages that transclude the given template
pub fn embeddedin(bot: &Bot, title: &str) -> Receiver {
    generator(
        bot,
        HashMap::from([
            ("generator".to_string(), "embeddedin".to_string()),
            ("geititle".to_string(), title.to_string()),
            ("geilimit".to_string(), "max".to_string()),
        ]),
    )
}

pub enum FilterRedirect {
    All,
    Nonredirects,
    Redirects,
}

impl FilterRedirect {
    fn as_str(&self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Nonredirects => "nonredirects",
            Self::Redirects => "redirects",
        }
    }
}

impl Default for FilterRedirect {
    fn default() -> Self {
        Self::All
    }
}

/// Get all pages in a given namespace
pub fn allpages(
    bot: &Bot,
    namespace: u32,
    filter_redirect: FilterRedirect,
) -> Receiver {
    generator(
        bot,
        HashMap::from([
            ("generator".to_string(), "allpages".to_string()),
            (
                "gapfilterredir".to_string(),
                filter_redirect.as_str().to_owned(),
            ),
            ("gapnamespace".to_string(), namespace.to_string()),
            ("gaplimit".to_string(), "max".to_string()),
        ]),
    )
}

/// Get pages that transclude the given template
fn generator(bot: &Bot, params: HashMap<String, String>) -> Receiver {
    let (tx, rx) = mpsc::channel(50);
    let bot = bot.clone();
    tokio::spawn(async move {
        let mut params = Params {
            main: params,
            ..Default::default()
        };
        loop {
            let resp: InfoResponse =
                match bot.api.query_response(params.merged()).await {
                    Ok(resp) => resp,
                    Err(err) => {
                        match tx.send(Err(err)).await {
                            Ok(_) => break,
                            // Receiver hung up, just abort
                            Err(_) => return,
                        }
                    }
                };
            params.continue_ = resp.continue_.clone();
            for item in resp.into_items() {
                let page = bot.page(&item.title).map(|page| {
                    // unwrap: We just created the page, it's impossible for
                    // another thread to be trying to set metadata
                    page.info.set(item).unwrap();
                    page
                });
                if tx.send(page).await.is_err() {
                    // Receiver hung up, just abort
                    return;
                }
            }
            if params.continue_.is_empty() {
                // All done
                break;
            }
        }
    });
    rx
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::testwp;

    #[tokio::test]
    async fn test_categorymembers() {
        let bot = testwp().await;
        let mut members = categorymembers(&bot, "Category:!Requests");
        while let Some(page) = members.recv().await {
            let page = page.unwrap();
            // This page is the last one, so it should require at least one continuation
            if page.title() == "Category:Unsuccessful requests for permissions"
            {
                assert!(true);
                return;
            }
        }

        panic!("Unable to find the page");
    }

    #[tokio::test]
    async fn test_categorymembers_recursive() {
        let bot = testwp().await;
        let mut members = categorymembers_recursive(&bot, "Category:Mwbot-rs");
        let mut found = false;
        while let Some(page) = members.recv().await {
            if page.unwrap().title() == "Mwbot-rs/Categorized depth 1" {
                found = true;
            }
        }
        // We are also testing that this generator runs to completion and does
        // not get trapped in an infinte loop
        assert!(found, "Found depth 1 page");
    }

    #[tokio::test]
    async fn test_embeddedin() {
        let bot = testwp().await;
        let mut embeddedin = embeddedin(&bot, "Template:1x");
        let mut count = 0;
        while let Some(page) = embeddedin.recv().await {
            page.unwrap();
            count += 1;
            if count == 5 {
                break;
            }
        }
        assert_eq!(count, 5);
    }

    #[tokio::test]
    async fn test_allpages() {
        let bot = testwp().await;
        let mut pages = allpages(&bot, 0, FilterRedirect::Nonredirects);
        let mut count = 0;
        while let Some(page) = pages.recv().await {
            page.unwrap();
            count += 1;
            if count == 5 {
                break;
            }
        }
        assert_eq!(count, 5);
    }
}