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
/*
 * ForgeFlux StarChart - A federated software forge spider
 * Copyright © 2022 Aravinth Manivannan <realaravinth@batsense.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
use std::future::Future;
use std::sync::Arc;
use std::sync::RwLock;

use log::info;
use tokio::sync::oneshot::{error::TryRecvError, Receiver};
use url::Url;

use db_core::prelude::*;
use forge_core::prelude::*;
use gitea::Gitea;

use crate::ctx::Ctx;
use crate::db::BoxDB;
use crate::federate::ArcFederate;
use crate::ArcCtx;

impl Ctx {
    pub async fn crawl(&self, instance_url: &Url, db: &BoxDB, federate: &ArcFederate) {
        info!("[crawl][{instance_url}] Init crawling");
        let forge: Box<dyn SCForge> =
            Box::new(Gitea::new(instance_url.clone(), self.client.clone()));
        if !forge.is_forge().await {
            unimplemented!("Forge type unimplemented");
        }

        let mut page = 1;
        let url = forge.get_url();
        if !db.forge_exists(url).await.unwrap() {
            info!("[crawl][{url}] Creating forge");
            let msg = CreateForge {
                url: url.clone(),
                forge_type: forge.forge_type(),
                starchart_url: None,
            };

            db.create_forge_instance(&msg).await.unwrap();
        } else if !federate.forge_exists(url).await.unwrap() {
            let forge = db.get_forge(url).await.unwrap();
            let msg = CreateForge {
                url: url.clone(),
                forge_type: forge.forge_type,
                starchart_url: None,
            };
            federate.create_forge_instance(&msg).await.unwrap();
        }

        loop {
            info!("[crawl][{url}] Crawling. page: {page}");
            let res = forge
                .crawl(
                    self.settings.crawler.items_per_api_call,
                    page,
                    self.settings.crawler.wait_before_next_api_call,
                )
                .await;
            if res.repos.is_empty() {
                info!("[crawl][{url}] Finished crawling. pages: {}", page - 1);
                break;
            }

            for (username, u) in res.users.iter() {
                if !db
                    .user_exists(username, Some(forge.get_url()))
                    .await
                    .unwrap()
                {
                    info!("[crawl][{url}] Creating user: {username}");
                    let msg = u.as_ref().into();
                    db.add_user(&msg).await.unwrap();
                    federate.create_user(&msg).await.unwrap();
                }
                if !federate
                    .user_exists(username, forge.get_url())
                    .await
                    .unwrap()
                {
                    let msg = u.as_ref().into();
                    federate.create_user(&msg).await.unwrap();
                }
            }

            for r in res.repos.iter() {
                if !db
                    .repository_exists(&r.name, &r.owner.username, &r.url)
                    .await
                    .unwrap()
                {
                    info!("[crawl][{url}] Creating repository: {}", r.name);
                    let msg = r.into();
                    db.create_repository(&msg).await.unwrap();
                    federate.create_repository(&msg).await.unwrap();
                }
                if !federate
                    .repository_exists(&r.name, &r.owner.username, &r.url)
                    .await
                    .unwrap()
                {
                    let msg = r.into();
                    federate.create_repository(&msg).await.unwrap();
                }
            }

            page += 1;
        }
    }
}

pub struct Crawler {
    rx: RwLock<Option<Receiver<bool>>>,
    ctx: ArcCtx,
    db: BoxDB,
    federate: ArcFederate,
}

impl Crawler {
    pub fn new(rx: Receiver<bool>, ctx: ArcCtx, db: BoxDB, federate: ArcFederate) -> Arc<Self> {
        let rx = RwLock::new(Some(rx));
        Arc::new(Self {
            rx,
            ctx,
            db,
            federate,
        })
    }

    pub fn is_running(&self) -> bool {
        self.rx.read().unwrap().is_some()
    }

    fn shutdown(&self) -> bool {
        let res = if let Some(rx) = self.rx.write().unwrap().as_mut() {
            //            let rx = self.rx.as_mut().unwrap();
            match rx.try_recv() {
                // The channel is currently empty
                Ok(x) => {
                    info!("Received signal from tx: {}", x);
                    x
                }
                Err(TryRecvError::Empty) => false,
                Err(TryRecvError::Closed) => {
                    info!("Closed");
                    true
                }
            }
        } else {
            true
        };
        if res {
            let mut rx = self.rx.write().unwrap();
            *rx = None;
        }
        res
    }

    // static is justified since the crawler will be initialized when the program starts
    // and only shutdown when the program exits
    pub async fn start(c: Arc<Crawler>) -> impl Future {
        if c.shutdown() {
            info!("Stopping crawling job");
            return tokio::spawn(tokio::time::sleep(std::time::Duration::new(0, 0)));
        }

        let fut = async move {
            const LIMIT: u32 = 2;
            let mut page = 0;
            loop {
                info!("Running crawling job");
                let offset = page * LIMIT;
                if c.shutdown() {
                    break;
                }

                let forges = c.db.get_all_forges(false, offset, LIMIT).await.unwrap();
                if forges.is_empty() {
                    c.federate.tar().await.unwrap();
                    page = 0;
                    tokio::time::sleep(std::time::Duration::new(c.ctx.settings.crawler.ttl, 0))
                        .await;
                    if c.shutdown() {
                        info!("Stopping crawling job");
                        break;
                    }

                    continue;
                }
                for forge in forges.iter() {
                    if c.shutdown() {
                        info!("Stopping crawling job");
                        break;
                    }
                    c.ctx
                        .crawl(&Url::parse(&forge.url).unwrap(), &c.db, &c.federate)
                        .await;
                    page += 1;
                }

                if c.shutdown() {
                    info!("Stopping crawling job");
                    break;
                }
            }
        };

        tokio::spawn(fut)
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::sqlx_sqlite;

    use url::Url;

    pub const GITEA_HOST: &str = "http://localhost:8080";
    pub const GITEA_USERNAME: &str = "bot";

    #[actix_rt::test]
    async fn crawl_gitea() {
        let (db, ctx, federate, _tmp_dir) = sqlx_sqlite::get_ctx().await;
        let url = Url::parse(GITEA_HOST).unwrap();
        ctx.crawl(&url, &db, &federate).await;
        //        let hostname = get_hostname(&Url::parse(GITEA_HOST).unwrap());
        assert!(db.forge_exists(&url).await.unwrap());
        assert!(db.user_exists(GITEA_USERNAME, Some(&url)).await.unwrap());
        assert!(db.user_exists(GITEA_USERNAME, None).await.unwrap());
        for i in 0..100 {
            let repo = format!("repository_{i}");
            assert!(db
                .repository_exists(&repo, GITEA_USERNAME, &url)
                .await
                .unwrap())
        }
        assert!(db.forge_exists(&url).await.unwrap());
    }

    //    #[actix_rt::test]
    //    async fn crawlerd() {
    //        use super::*;
    //use tokio::sync::oneshot;
    //
    //        let (db, ctx, federate, _tmp_dir) = sqlx_sqlite::get_ctx().await;
    //    let (kill_crawler, rx) = oneshot::channel();
    //        let crawler = Crawler::new(rx, ctx.clone(), db, federate);
    //        let fut = tokio::spawn(Crawler::start(crawler.clone()));
    //        assert!(crawler.is_running());
    //
    //                    tokio::time::sleep(std::time::Duration::new(2, 0))
    //                        .await;
    //
    //
    //        kill_crawler.send(true).unwrap();
    //                    tokio::time::sleep(std::time::Duration::new(2, 0))
    //                        .await;
    //
    //
    //        fut.await.unwrap().await;
    //        assert!(!crawler.is_running());
    //    }
}