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
/*
 * 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/.
 */

//! Twitter feed
//!
//! This module includes the [`Twitter`] struct that is a source that is able to parse a twitter feed via twitter API

use super::{error::SourceError, Fetch};
use crate::{
	entry::Entry,
	sink::message::{Media, Message},
};

use async_trait::async_trait;
use egg_mode::{
	auth::bearer_token,
	entities::MediaType,
	tweet::{user_timeline, Timeline},
	KeyPair, Token,
};

/// A source that fetches from a Twitter feed using the Twitter API
pub struct Twitter {
	// the only point of this option is to enable taking timeline by value. It can be never observed to be None unless the thread panicked
	timeline: Option<Timeline>,
	handle: String,
	auth: Auth,
}

enum Auth {
	NotAuthenticated { api_key: String, api_secret: String },
	Authenticated(Token),
}

#[allow(missing_docs)] // error message is self-documenting
#[derive(thiserror::Error, Debug)]
pub enum TwitterError {
	#[error("Authentication failed")]
	Auth(#[source] egg_mode::error::Error),

	#[error(transparent)]
	Other(#[from] egg_mode::error::Error),
}

impl Twitter {
	/// Creates a new [`Twitter`] source
	#[must_use]
	pub fn new(handle: String, api_key: String, api_secret: String) -> Self {
		Self {
			timeline: None,
			handle,
			auth: Auth::NotAuthenticated {
				api_key,
				api_secret,
			},
		}
	}
}

#[async_trait]
impl Fetch for Twitter {
	/// Fetches all tweets from the feed
	async fn fetch(&mut self) -> Result<Vec<Entry>, SourceError> {
		self.fetch_impl().await.map_err(Into::into)
	}
}

impl Twitter {
	async fn fetch_impl(&mut self) -> Result<Vec<Entry>, TwitterError> {
		tracing::debug!("Getting tweets");

		let token = match &self.auth {
			Auth::NotAuthenticated {
				api_key,
				api_secret,
			} => {
				let token = bearer_token(&KeyPair::new(api_key.clone(), api_secret.clone()))
					.await
					.map_err(TwitterError::Auth)?;

				self.auth = Auth::Authenticated(token);
				let Auth::Authenticated(auth) = &self.auth else {
					unreachable!("it has just been put there, this couldn't happen");
				};

				auth
			}
			Auth::Authenticated(token) => token,
		};

		let (timeline, tweets) = match &self.timeline {
			None => {
				user_timeline(self.handle.clone(), true, true, token)
					.start()
					.await?
			}
			Some(_) => {
				self.timeline
					.take()
					.expect("shouldn't be None, just matched Some")
					.newer(None)
					.await?
			}
		};

		self.timeline = Some(timeline);

		tracing::debug!("Got {num} tweets", num = tweets.len());

		let messages = tweets
			.iter()
			.map(|tweet| {
				Entry {
					id: Some(tweet.id.to_string().into()),
					reply_to: tweet.in_reply_to_status_id.map(|i| i.to_string().into()),
					msg: Message {
						body: Some(tweet.text.clone()),
						link: Some(
							format!(
								"https://twitter.com/{handle}/status/{id}",
								handle = self.handle,
								id = tweet.id
							)
							.as_str()
							.try_into()
							.expect("The URL is hand crafted and should always be valid"),
						),
						media: tweet.entities.media.as_ref().and_then(|x| {
							x.iter()
								.map(|x| match x.media_type {
									MediaType::Photo => {
										Some(Media::Photo(x.media_url.as_str().try_into().expect("The tweet URL provided by the Tweeter API should always be a valid URL")))
									}
									MediaType::Video => {
										Some(Media::Video(x.media_url.as_str().try_into().expect("The tweet URL provided by the Tweeter API should always be a valid URL")))
									}
									MediaType::Gif => None,
								})
								.collect::<Option<Vec<Media>>>()
						}),
						..Default::default()
					},
					..Default::default()
				}
			})
			.collect::<Vec<_>>();

		let unread_num = messages.len();
		if unread_num > 0 {
			tracing::debug!("Got {unread_num} unread filtered tweets");
		} else {
			tracing::debug!("All tweets have already been read, none remaining to send");
		}

		Ok(messages)
	}
}

impl std::fmt::Debug for Twitter {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Twitter")
			.field("handle", &self.handle)
			.finish_non_exhaustive()
	}
}