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
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

pub mod file;
pub mod http;
pub mod twitter;

use self::{file::File, http::Http, twitter::Twitter};
use crate::{entry::Entry, error::source::Error as SourceError};

/// Always contains a vec with sources of the same type
#[derive(Debug)]
pub struct Source(Vec<Kind>);

#[derive(Debug)]
pub enum Kind {
	File(File),
	Http(Http),
	Twitter(Twitter),
}

impl Source {
	/// Create a new sources vec that contains one or several pure sources of the same type
	///
	/// # Errors
	/// * if the source list is empty
	/// * if the several sources that were provided are of different `WithStaredReadFilterInner` variants
	pub fn new(sources: Vec<Kind>) -> Result<Self, SourceError> {
		match sources.len() {
			0 => return Err(SourceError::EmptySourceList),
			1 => (),
			// assert that all source types are of the same enum variant
			_ => {
				for variants in sources.windows(2) {
					use std::mem::discriminant as disc;

					if disc(&variants[0]) != disc(&variants[1]) {
						return Err(SourceError::SourceListHasDifferentVariants);
					}
				}
			}
		}

		Ok(Self(sources))
	}

	/// Get all entries from the sources
	///
	/// # Errors
	/// if there was an error fetching from a source
	pub async fn get(&mut self) -> Result<Vec<Entry>, SourceError> {
		let mut entries = Vec::new();

		for s in &mut self.0 {
			entries.extend(match s {
				Kind::Http(x) => vec![x.get().await?],
				Kind::Twitter(x) => x.get().await?,
				Kind::File(x) => vec![x.get().await?],
			});
		}

		Ok(entries)
	}
}

impl TryFrom<Vec<Kind>> for Source {
	type Error = SourceError;

	fn try_from(value: Vec<Kind>) -> Result<Self, Self::Error> {
		Self::new(value)
	}
}

impl std::ops::Deref for Source {
	type Target = [Kind];

	fn deref(&self) -> &Self::Target {
		self.0.as_slice()
	}
}