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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! query for updates (or *one* update by ID, title, or alias)
//!
//! The contents of this module can be used to query a bodhi instance about
//! existing updates.
//!
//! The `UpdateIDQuery` returns exactly one Update, if and only if a Update
//! with this ID, alias, or title exists - otherwise, it will return an error. FIXME
//!
//! The `UpdateQuery` can be used to execute more complex queries, for example
//! filtering updates by release, status, security impact, reboot suggestion,
//! or for updates that are associated with a given set of packages.

use std::collections::HashMap;

use serde::Deserialize;

use crate::data::*;
use crate::service::{BodhiService, DEFAULT_PAGE, DEFAULT_ROWS};

/// Use this for querying bodhi for a specific update by its ID, title, or alias.
///
/// ```
/// let bodhi = bodhi::BodhiService::new(String::from(bodhi::FEDORA_BODHI_URL));
///
/// let update = bodhi::UpdateIDQuery::new(String::from("FEDORA-2019-3dd0cf468e"))
///     .query(&bodhi).unwrap();
/// ```
#[derive(Debug)]
pub struct UpdateIDQuery {
    id: String,
}

#[derive(Debug, Deserialize)]
struct UpdatePage {
    update: Update,
    can_edit: bool,
}

impl UpdateIDQuery {
    /// This method is the only way to create a new `UpdateIDQuery` instance.
    pub fn new(id: String) -> UpdateIDQuery {
        UpdateIDQuery { id }
    }

    /// This method will query the remote bodhi instance for the requested update by ID,
    /// title, or alias, and will either return an `Ok(Update)` matching the specified ID,
    /// title, or alias, or return an `Err(String)` if it doesn't exist,
    /// or if another error occurred.
    ///
    /// TODO: return `Result<Option<Update>, String>>` to distinguish "not found" from errors
    pub fn query(self, bodhi: &BodhiService) -> Result<Update, String> {
        let path = format!("/updates/{}", self.id);

        let mut response = bodhi.request(&path, None)?;
        let status = response.status();

        if status.is_success() {
            let update: UpdatePage = match response.json() {
                Ok(value) => value,
                Err(error) => {
                    return Err(format!("{:?}", error));
                }
            };

            Ok(update.update)
        } else {
            let error: BodhiError = match response.json() {
                Ok(value) => value,
                Err(error) => {
                    return Err(format!("Unexpected error message: {:?}", error));
                }
            };

            Err(format!("{:?}", error))
        }
    }
}

/// Use this for querying bodhi about a set of updates with the given properties,
/// which can be specified with the builder pattern. Note that some options can be
/// specified multiple times, and updates will be returned if any criteria match.
/// This is consistent with both the web interface and REST API behavior.
///
/// ```
/// let bodhi = bodhi::BodhiService::new(String::from(bodhi::FEDORA_BODHI_URL));
///
/// let updates = bodhi::UpdateQuery::new()
///     .users(String::from("decathorpe"))
///     .releases(String::from("F30"))
///     .status(bodhi::UpdateStatus::Testing)
///     .query(&bodhi).unwrap();
/// ```
#[derive(Debug, Default)]
pub struct UpdateQuery {
    active_releases: Option<bool>,
    aliases: Option<Vec<String>>,
    approved_before: Option<String>,
    approved_since: Option<String>,
    bugs: Option<Vec<String>>,
    builds: Option<Vec<String>>,
    content_type: Option<String>,
    critpath: Option<bool>,
    cves: Option<Vec<String>>,
    like: Option<String>,
    locked: Option<bool>,
    modified_before: Option<String>,
    modified_since: Option<String>,
    packages: Option<Vec<String>>,
    pushed: Option<bool>,
    pushed_before: Option<String>,
    pushed_since: Option<String>,
    releases: Option<Vec<String>>,
    request: Option<String>,
    search: Option<String>,
    severity: Option<String>,
    status: Option<String>,
    submitted_before: Option<String>,
    submitted_since: Option<String>,
    suggest: Option<String>,
    update_ids: Option<Vec<String>>,
    update_type: Option<String>,
    users: Option<Vec<String>>,
}

impl UpdateQuery {
    /// This method returns a new `UpdateQuery` with *no* filters set.
    pub fn new() -> UpdateQuery {
        UpdateQuery {
            active_releases: None,
            aliases: None,
            approved_before: None,
            approved_since: None,
            bugs: None,
            builds: None,
            content_type: None,
            critpath: None,
            cves: None,
            like: None,
            locked: None,
            modified_before: None,
            modified_since: None,
            packages: None,
            pushed: None,
            pushed_before: None,
            pushed_since: None,
            releases: None,
            request: None,
            search: None,
            severity: None,
            status: None,
            submitted_before: None,
            submitted_since: None,
            suggest: None,
            update_ids: None,
            update_type: None,
            users: None,
        }
    }

    /// Restrict the returned results to (not) active releases.
    pub fn active_releases(mut self, active_releases: bool) -> UpdateQuery {
        self.active_releases = Some(active_releases);
        self
    }

    /// Restrict results to updates matching the given alias(es).
    /// Can be specified multiple times.
    pub fn aliases(mut self, alias: String) -> UpdateQuery {
        match &mut self.aliases {
            Some(aliases) => aliases.push(alias),
            None => self.aliases = Some(vec![alias]),
        }

        self
    }

    /// Restrict the returned results to updates which were approved
    /// before the given date and time.
    pub fn approved_before(mut self, approved_before: String) -> UpdateQuery {
        self.approved_before = Some(approved_before);
        self
    }

    /// Restrict the returned results to updates which were approved
    /// since the given date and time.
    pub fn approved_since(mut self, approved_since: String) -> UpdateQuery {
        self.approved_since = Some(approved_since);
        self
    }

    /// Restrict results to updates associated with the given bug(s).
    /// Can be specified multiple times.
    pub fn bugs(mut self, bug: String) -> UpdateQuery {
        match &mut self.bugs {
            Some(bugs) => bugs.push(bug),
            None => self.bugs = Some(vec![bug]),
        }

        self
    }

    /// Restrict results to updates associated with the given build(s).
    /// Can be specified multiple times.
    pub fn builds(mut self, build: String) -> UpdateQuery {
        match &mut self.builds {
            Some(builds) => builds.push(build),
            None => self.builds = Some(vec![build]),
        }

        self
    }

    /// Restrict the returned results to the given content type.
    pub fn content_type(mut self, content_type: ContentType) -> UpdateQuery {
        self.content_type = Some(content_type.into());
        self
    }

    /// Restrict the returned results to updates (not) marked with critpath.
    pub fn critpath(mut self, critpath: bool) -> UpdateQuery {
        self.critpath = Some(critpath);
        self
    }

    /// Restrict results to updates associated with the given CVE(s).
    /// Can be specified multiple times.
    pub fn cves(mut self, cve: String) -> UpdateQuery {
        match &mut self.cves {
            Some(cves) => cves.push(cve),
            None => self.cves = Some(vec![cve]),
        }

        self
    }

    /// Restrict search to updates *like* the given argument (in the SQL sense).
    pub fn like(mut self, like: String) -> UpdateQuery {
        self.like = Some(like);
        self
    }

    /// Restrict the returned results to (not) locked updates.
    pub fn locked(mut self, locked: bool) -> UpdateQuery {
        self.locked = Some(locked);
        self
    }

    /// Restrict the returned results to updates which were modified
    /// before the given date and time.
    pub fn modified_before(mut self, modified_before: String) -> UpdateQuery {
        self.modified_before = Some(modified_before);
        self
    }

    /// Restrict the returned results to updates which were modified
    /// since the given date and time.
    pub fn modified_since(mut self, modified_since: String) -> UpdateQuery {
        self.modified_since = Some(modified_since);
        self
    }

    /// Restrict results to updates associated for the given package(s).
    /// Can be specified multiple times.
    pub fn packages(mut self, package: String) -> UpdateQuery {
        match &mut self.packages {
            Some(packages) => packages.push(package),
            None => self.packages = Some(vec![package]),
        }

        self
    }

    /// Restrict the returned results to (not) pushed updates.
    pub fn pushed(mut self, pushed: bool) -> UpdateQuery {
        self.pushed = Some(pushed);
        self
    }

    /// Restrict the returned results to updates which were pushed
    /// before the given date and time.
    pub fn pushed_before(mut self, pushed_before: String) -> UpdateQuery {
        self.pushed_before = Some(pushed_before);
        self
    }

    /// Restrict the returned results to updates which were pushed
    /// since the given date and time.
    pub fn pushed_since(mut self, pushed_since: String) -> UpdateQuery {
        self.pushed_since = Some(pushed_since);
        self
    }

    /// Restrict results to updates for the given release(s).
    /// Can be specified multiple times.
    pub fn releases(mut self, release: String) -> UpdateQuery {
        match &mut self.releases {
            Some(releases) => releases.push(release),
            None => self.releases = Some(vec![release]),
        }

        self
    }

    /// Restrict the returned results to updates with the given request.
    pub fn request(mut self, request: UpdateRequest) -> UpdateQuery {
        self.request = Some(request.into());
        self
    }

    /// Restrict search to updates containing the given argument.
    pub fn search(mut self, search: String) -> UpdateQuery {
        self.search = Some(search);
        self
    }

    /// Restrict the returned results to updates with the given severity.
    pub fn severity(mut self, severity: UpdateSeverity) -> UpdateQuery {
        self.severity = Some(severity.into());
        self
    }

    /// Restrict the returned results to updates with the given status.
    pub fn status(mut self, status: UpdateStatus) -> UpdateQuery {
        self.status = Some(status.into());
        self
    }

    /// Restrict the returned results to updates which were submitted
    /// before the given date and time.
    pub fn submitted_before(mut self, submitted_before: String) -> UpdateQuery {
        self.submitted_before = Some(submitted_before);
        self
    }

    /// Restrict the returned results to updates which were submitted
    /// since the given date and time.
    pub fn submitted_since(mut self, submitted_since: String) -> UpdateQuery {
        self.submitted_since = Some(submitted_since);
        self
    }

    /// Restrict the returned results to updates with the given "suggest" value.
    pub fn suggest(mut self, suggest: UpdateSuggestion) -> UpdateQuery {
        self.suggest = Some(suggest.into());
        self
    }

    /// Restrict results to updates matching the given update ID(s).
    /// Can be specified multiple times.
    pub fn update_ids(mut self, update_id: String) -> UpdateQuery {
        match &mut self.update_ids {
            Some(update_ids) => update_ids.push(update_id),
            None => self.update_ids = Some(vec![update_id]),
        }

        self
    }

    /// Restrict results to updates matching the given update type.
    pub fn update_type(mut self, update_type: UpdateType) -> UpdateQuery {
        self.update_type = Some(update_type.into());
        self
    }

    /// Restrict results to updates associated with the given user(s).
    /// Can be specified multiple times.
    pub fn users(mut self, user: String) -> UpdateQuery {
        match &mut self.users {
            Some(users) => users.push(user),
            None => self.users = Some(vec![user]),
        }

        self
    }

    /// Query the remote bodhi instance with the given parameters.
    pub fn query(self, bodhi: &BodhiService) -> Result<Vec<Update>, String> {
        let mut updates: Vec<Update> = Vec::new();
        let mut page = 1;

        loop {
            let mut query = UpdatePageQuery::new();
            query.page = page;

            query.active_releases = self.active_releases;
            query.aliases = self.aliases.clone();
            query.approved_before = self.approved_before.clone();
            query.approved_since = self.approved_since.clone();
            query.bugs = self.bugs.clone();
            query.builds = self.builds.clone();
            query.content_type = self.content_type.clone();
            query.critpath = self.critpath;
            query.cves = self.cves.clone();
            query.like = self.like.clone();
            query.locked = self.locked;
            query.modified_before = self.modified_before.clone();
            query.modified_since = self.modified_since.clone();
            query.packages = self.packages.clone();
            query.pushed = self.pushed;
            query.pushed_before = self.pushed_before.clone();
            query.pushed_since = self.pushed_since.clone();
            query.releases = self.releases.clone();
            query.request = self.request.clone();
            query.search = self.search.clone();
            query.severity = self.severity.clone();
            query.status = self.status.clone();
            query.submitted_before = self.submitted_before.clone();
            query.submitted_since = self.submitted_since.clone();
            query.suggest = self.suggest.clone();
            query.update_ids = self.update_ids.clone();
            query.update_type = self.update_type.clone();
            query.users = self.users.clone();

            let result = query.query(bodhi)?;
            updates.extend(result.updates);

            page += 1;

            if page > result.pages {
                break;
            }
        }

        Ok(updates)
    }
}

#[derive(Debug, Deserialize)]
struct UpdateListPage {
    updates: Vec<Update>,
    page: u32,
    pages: u32,
    rows_per_page: u32,
    total: u32,
}

#[derive(Debug)]
struct UpdatePageQuery {
    active_releases: Option<bool>,
    aliases: Option<Vec<String>>,
    approved_before: Option<String>,
    approved_since: Option<String>,
    bugs: Option<Vec<String>>,
    builds: Option<Vec<String>>,
    content_type: Option<String>,
    critpath: Option<bool>,
    cves: Option<Vec<String>>,
    like: Option<String>,
    locked: Option<bool>,
    modified_before: Option<String>,
    modified_since: Option<String>,
    packages: Option<Vec<String>>,
    pushed: Option<bool>,
    pushed_before: Option<String>,
    pushed_since: Option<String>,
    releases: Option<Vec<String>>,
    request: Option<String>,
    search: Option<String>,
    severity: Option<String>,
    status: Option<String>,
    submitted_before: Option<String>,
    submitted_since: Option<String>,
    suggest: Option<String>,
    update_ids: Option<Vec<String>>,
    update_type: Option<String>,
    users: Option<Vec<String>>,

    page: u32,
    rows_per_page: u32,
}

impl UpdatePageQuery {
    fn new() -> UpdatePageQuery {
        UpdatePageQuery {
            active_releases: None,
            aliases: None,
            approved_before: None,
            approved_since: None,
            bugs: None,
            builds: None,
            content_type: None,
            critpath: None,
            cves: None,
            like: None,
            locked: None,
            modified_before: None,
            modified_since: None,
            packages: None,
            pushed: None,
            pushed_before: None,
            pushed_since: None,
            releases: None,
            request: None,
            search: None,
            severity: None,
            status: None,
            submitted_before: None,
            submitted_since: None,
            suggest: None,
            update_ids: None,
            update_type: None,
            users: None,
            page: DEFAULT_PAGE,
            rows_per_page: DEFAULT_ROWS,
        }
    }

    fn query(self, bodhi: &BodhiService) -> Result<UpdateListPage, String> {
        let path = String::from("/updates/");

        let mut args: HashMap<&str, String> = HashMap::new();

        if let Some(active_releases) = self.active_releases {
            args.insert("active_releases", active_releases.to_string());
        };

        if let Some(aliases) = self.aliases {
            args.insert("alias", aliases.join(","));
        };

        if let Some(approved_before) = self.approved_before {
            args.insert("approved_before", approved_before);
        };

        if let Some(approved_since) = self.approved_since {
            args.insert("approved_since", approved_since);
        };

        if let Some(bugs) = self.bugs {
            args.insert("bugs", bugs.join(","));
        };

        if let Some(builds) = self.builds {
            args.insert("builds", builds.join(","));
        };

        if let Some(content_type) = self.content_type {
            args.insert("content_type", content_type);
        };

        if let Some(critpath) = self.critpath {
            args.insert("critpath", critpath.to_string());
        };

        if let Some(cves) = self.cves {
            args.insert("cves", cves.join(","));
        };

        if let Some(like) = self.like {
            args.insert("like", like);
        };

        if let Some(locked) = self.locked {
            args.insert("locked", locked.to_string());
        };

        if let Some(modified_before) = self.modified_before {
            args.insert("modified_before", modified_before);
        };

        if let Some(modified_since) = self.modified_since {
            args.insert("modified_since", modified_since);
        };

        if let Some(packages) = self.packages {
            args.insert("packages", packages.join(","));
        };

        if let Some(pushed) = self.pushed {
            args.insert("pushed", pushed.to_string());
        };

        if let Some(pushed_before) = self.pushed_before {
            args.insert("pushed_before", pushed_before);
        };

        if let Some(pushed_since) = self.pushed_since {
            args.insert("pushed_since", pushed_since);
        };

        if let Some(releases) = self.releases {
            args.insert("releases", releases.join(","));
        };

        if let Some(request) = self.request {
            args.insert("request", request);
        };

        if let Some(search) = self.search {
            args.insert("search", search);
        };

        if let Some(severity) = self.severity {
            args.insert("severity", severity);
        };

        if let Some(status) = self.status {
            args.insert("status", status);
        };

        if let Some(submitted_before) = self.submitted_before {
            args.insert("submitted_before", submitted_before);
        };

        if let Some(submitted_since) = self.submitted_since {
            args.insert("submitted_since", submitted_since);
        };

        if let Some(suggest) = self.suggest {
            args.insert("suggest", suggest);
        };

        if let Some(update_ids) = self.update_ids {
            args.insert("updateid", update_ids.join(","));
        };

        if let Some(update_type) = self.update_type {
            args.insert("type", update_type);
        };

        if let Some(users) = self.users {
            args.insert("user", users.join(","));
        };

        args.insert("page", format!("{}", self.page));
        args.insert("rows_per_page", format!("{}", self.rows_per_page));

        let mut response = bodhi.request(&path, Some(args))?;
        let status = response.status();

        if status.is_success() {
            let updates: UpdateListPage = match response.json() {
                Ok(value) => value,
                Err(error) => {
                    return Err(format!("{:?}", error));
                }
            };

            Ok(updates)
        } else {
            let error: BodhiError = match response.json() {
                Ok(value) => value,
                Err(error) => {
                    return Err(format!("Unexpected error message: {:?}", error));
                }
            };

            Err(format!("{:?}", error))
        }
    }
}