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
use futures::{future, stream, Future, Stream};
use log::trace;
use reqwest::{header, r#async, StatusCode, Url};
use serde::de::DeserializeOwned;

use super::Error;
use crate::types::*;

/// Asynchronous client for the crates.io API.
#[derive(Clone)]
pub struct Client {
    client: r#async::Client,
    base_url: Url,
}

impl Client {
    /// Instantiate a new client.
    ///
    /// This will fail if the underlying http client could not be created.
    pub fn new() -> Self {
        Self {
            client: r#async::Client::new(),
            base_url: Url::parse("https://crates.io/api/v1/").unwrap(),
        }
    }

    pub fn with_user_agent(user_agent: &str) -> Self {
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::USER_AGENT,
            header::HeaderValue::from_str(user_agent).unwrap(),
        );
        Self {
            client: r#async::Client::builder()
                .default_headers(headers)
                .build()
                .unwrap(),
            base_url: Url::parse("https://crates.io/api/v1/").unwrap(),
        }
    }

    fn get<T: DeserializeOwned>(&self, url: &Url) -> impl Future<Item = T, Error = Error> {
        trace!("GET {}", url);

        self.client
            .get(url.clone())
            .send()
            .map_err(Error::from)
            .and_then(|res| {
                if res.status() == StatusCode::NOT_FOUND {
                    return Err(Error::NotFound);
                }
                let res = res.error_for_status()?;
                Ok(res)
            })
            .and_then(|mut res| res.json().map_err(Error::from))
    }

    /// Retrieve a summary containing crates.io wide information.
    pub fn summary(&self) -> impl Future<Item = Summary, Error = Error> {
        let url = self.base_url.join("summary").unwrap();
        self.get(&url)
    }

    /// Retrieve information of a crate.
    ///
    /// If you require detailed information, consider using [full_crate]().
    pub fn get_crate(&self, name: &str) -> impl Future<Item = CrateResponse, Error = Error> {
        let url = self.base_url.join("crates/").unwrap().join(name).unwrap();
        self.get(&url)
    }

    /// Retrieve download stats for a crate.
    pub fn crate_downloads(&self, name: &str) -> impl Future<Item = Downloads, Error = Error> {
        let url = self
            .base_url
            .join(&format!("crates/{}/downloads", name))
            .unwrap();
        self.get(&url)
    }

    /// Retrieve the owners of a crate.
    pub fn crate_owners(&self, name: &str) -> impl Future<Item = Vec<User>, Error = Error> {
        let url = self
            .base_url
            .join(&format!("crates/{}/owners", name))
            .unwrap();
        self.get::<Owners>(&url).map(|data| data.users)
    }

    /// Load all reverse dependencies of a crate.
    ///
    /// Note: Since the reverse dependency endpoint requires pagination, this
    /// will result in multiple requests if the crate has more than 100 reverse
    /// dependencies.
    pub fn crate_reverse_dependencies(&self, name: &str)
        -> impl Future<Item = ReverseDependencies, Error = Error> {

        fn fetch_page(c: Client, name: String, mut tidy_rdeps: ReverseDependencies, page: u64)
            -> impl Future<Item = ReverseDependencies, Error = Error> + Send {

            let url = c.base_url.join(&format!(
                "crates/{0}/reverse_dependencies?per_page=100&page={1}", name, page
            )).unwrap();

            c.get::<ReverseDependenciesAsReceived>(&url).and_then(move |rdeps|
                -> Box<dyn Future<Item = ReverseDependencies, Error = Error> + Send> {

                tidy_rdeps.from_received(&rdeps);

                if !rdeps.dependencies.is_empty() {
                    tidy_rdeps.meta = rdeps.meta;
                    Box::new(fetch_page(c, name, tidy_rdeps, page + 1))
                } else {
                    Box::new(::futures::future::ok(tidy_rdeps))
                }
            })
        }

        fetch_page(self.clone(), name.to_string(), ReverseDependencies {
            dependencies: Vec::new(), meta:Meta{total:0} }, 1)
    }

    /// Retrieve the authors for a crate version.
    pub fn crate_authors(
        &self,
        name: &str,
        version: &str,
    ) -> impl Future<Item = Authors, Error = Error> {
        let url = self
            .base_url
            .join(&format!("crates/{}/{}/authors", name, version))
            .unwrap();
        self.get::<AuthorsResponse>(&url).map(|res| Authors {
            names: res.meta.names,
            users: res.users,
        })
    }

    /// Retrieve the dependencies of a crate version.
    pub fn crate_dependencies(
        &self,
        name: &str,
        version: &str,
    ) -> impl Future<Item = Vec<Dependency>, Error = Error> {
        let url = self
            .base_url
            .join(&format!("crates/{}/{}/dependencies", name, version))
            .unwrap();
        self.get::<Dependencies>(&url).map(|res| res.dependencies)
    }

    fn full_version(&self, version: Version) -> impl Future<Item = FullVersion, Error = Error> {
        let authors = self.crate_authors(&version.crate_name, &version.num);
        let deps = self.crate_dependencies(&version.crate_name, &version.num);

        authors.join(deps).map(|(authors, deps)| FullVersion {
            created_at: version.created_at,
            updated_at: version.updated_at,
            dl_path: version.dl_path,
            downloads: version.downloads,
            features: version.features,
            id: version.id,
            num: version.num,
            yanked: version.yanked,
            license: version.license,
            links: version.links,
            readme_path: version.readme_path,

            author_names: authors.names,
            authors: authors.users,
            dependencies: deps,
        })
    }

    /// Retrieve all available information for a crate, including download
    /// stats,  owners and reverse dependencies.
    ///
    /// The `all_versions` argument controls the retrieval of detailed version
    /// information.
    /// If false, only the data for the latest version will be fetched, if true,
    /// detailed information for all versions will be available.
    /// Note: Each version requires two extra requests.
    pub fn full_crate(
        &self,
        name: &str,
        all_versions: bool,
    ) -> impl Future<Item = FullCrate, Error = Error> {
        let c = self.clone();
        let crate_and_versions = self.get_crate(name).and_then(
            move |info| -> Box<
                Future<Item = (CrateResponse, Vec<FullVersion>), Error = Error> + Send,
            > {
                if !all_versions {
                    Box::new(
                        c.full_version(info.versions[0].clone())
                            .map(|v| (info, vec![v])),
                    )
                } else {
                    Box::new(
                        ::futures::future::join_all(
                            info.versions
                                .clone()
                                .into_iter()
                                .map(|v| c.full_version(v))
                                .collect::<Vec<_>>(),
                        )
                        .map(|versions| (info, versions)),
                    )
                }
            },
        );

        let dls = self.crate_downloads(name);
        let owners = self.crate_owners(name);
        let reverse_dependencies = self.crate_reverse_dependencies(name);

        crate_and_versions
            .join4(dls, owners, reverse_dependencies)
            .map(|((resp, versions), dls, owners, reverse_dependencies)| {
                let data = resp.crate_data;
                FullCrate {
                    id: data.id,
                    name: data.name,
                    description: data.description,
                    license: resp.versions[0].license.clone(),
                    documentation: data.documentation,
                    homepage: data.homepage,
                    repository: data.repository,
                    total_downloads: data.downloads,
                    max_version: data.max_version,
                    created_at: data.created_at,
                    updated_at: data.updated_at,

                    categories: resp.categories,
                    keywords: resp.keywords,
                    downloads: dls,
                    owners,
                    reverse_dependencies,
                    versions,
                }
            })
    }

    /// Retrieve a page of crates, optionally constrained by a query.
    ///
    /// If you want to get all results without worrying about paging,
    /// use [all_crates]().
    ///
    /// ```
    pub fn crates(&self, spec: ListOptions) -> impl Future<Item = CratesResponse, Error = Error> {
        let mut url = self.base_url.join("crates").unwrap();
        {
            let mut q = url.query_pairs_mut();
            q.append_pair("page", &spec.page.to_string());
            q.append_pair("per_page", &spec.per_page.to_string());
            q.append_pair("sort", spec.sort.to_str());
            if let Some(query) = spec.query {
                q.append_pair("q", &query);
            }
        }
        self.get(&url)
    }

    /// Retrieve all crates, optionally constrained by a query.
    ///
    /// Note: This method fetches all pages of the result.
    /// This can result in a lot queries (100 results per query).
    pub fn all_crates(&self, query: Option<String>) -> impl Stream<Item = Crate, Error = Error> {
        let opts = ListOptions {
            query,
            sort: Sort::Alphabetical,
            per_page: 100,
            page: 1,
        };

        let c = self.clone();
        self.crates(opts.clone())
            .and_then(move |res| {
                let pages = (res.meta.total as f64 / 100.0).ceil() as u64;
                let streams_futures = (1..pages)
                    .map(|page| {
                        let opts = ListOptions {
                            page,
                            ..opts.clone()
                        };
                        c.crates(opts)
                            .and_then(|res| future::ok(stream::iter_ok(res.crates)))
                    })
                    .collect::<Vec<_>>();
                let stream = stream::futures_ordered(streams_futures).flatten();
                future::ok(stream)
            })
            .flatten_stream()
    }

    /// Retrieve all crates with all available extra information.
    ///
    /// Note: This method fetches not only all crates, but does multiple requests for each crate
    /// to retrieve extra information.
    ///
    /// This can result in A LOT of queries.
    pub fn all_crates_full(
        &self,
        query: Option<String>,
        all_versions: bool,
    ) -> impl Stream<Item = FullCrate, Error = Error> {
        let c = self.clone();
        self.all_crates(query)
            .and_then(move |cr| c.full_crate(&cr.name, all_versions))
    }
}

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

    #[test]
    fn test_client() {
        let mut rt = ::tokio::runtime::Runtime::new().unwrap();

        let client = Client::new();

        let summary = rt.block_on(client.summary()).unwrap();
        assert!(summary.most_downloaded.len() > 0);

        for item in &summary.most_downloaded[0..3] {
            let _ = rt.block_on(client.full_crate(&item.name, false)).unwrap();
        }

        let crates = rt
            .block_on(client.all_crates(None).take(3).collect())
            .unwrap();
        println!("{:?}", crates);
    }
}