Debian Codegraph @

podcasts-data/src/models/source.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // source.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // SPDX-License-Identifier: GPL-3.0-or-later
19
20 use base64::engine::general_purpose;
21 use base64::prelude::*;
22 use diesel::SaveChangesDsl;
23 use http::StatusCode;
24 use http::header::{
25 AUTHORIZATION, ETAG, HeaderValue, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, LOCATION,
26 USER_AGENT as USER_AGENT_HEADER,
27 };
28 use rss::Channel;
29 use std::str::FromStr;
30 use url::Url;
31
32 use crate::USER_AGENT;
33 use crate::database::connection;
34 use crate::errors::*;
35 use crate::feed::{Feed, FeedBuilder};
36 use crate::make_id_wrapper;
37 use crate::models::{NewSource, Save};
38 use crate::schema::source;
39
40 make_id_wrapper!(SourceId);
41
42 #[derive(Queryable, Identifiable, AsChangeset, PartialEq, Selectable)]
43 #[diesel(table_name = source)]
44 #[diesel(treat_none_as_null = true)]
45 #[derive(Debug, Clone)]
46 /// Diesel Model of the source table.
47 pub struct Source {
48 id: SourceId,
49 uri: String,
50 last_modified: Option<String>,
51 http_etag: Option<String>,
52 }
53
54 impl Save<Source> for Source {
55 type Error = DataError;
56
57 /// Helper method to easily save/"sync" current state of self to the
58 /// Database.
59 fn save(&self) -> Result<Source, Self::Error> {
60 let db = connection();
61 let mut con = db.get()?;
62
63 self.save_changes::<Source>(&mut con).map_err(From::from)
64 }
65 }
66
67 impl Source {
68 /// Get the source `id` column.
69 pub fn id(&self) -> SourceId {
70 self.id
71 }
72
73 /// Represents the location(usually url) of the Feed xml file.
74 pub fn uri(&self) -> &str {
75 &self.uri
76 }
77
78 /// Set the `uri` field value.
79 pub fn set_uri(&mut self, uri: String) {
80 self.uri = uri;
81 }
82
83 /// Represents the Http Last-Modified Header field.
84 ///
85 /// See [RFC 7231](https://tools.ietf.org/html/rfc7231#section-7.2) for more.
86 pub fn last_modified(&self) -> Option<&str> {
87 self.last_modified.as_deref()
88 }
89
90 /// Set `last_modified` value.
91 pub fn set_last_modified(&mut self, value: Option<String>) {
92 // self.last_modified = value.map(|x| x.to_string());
93 self.last_modified = value;
94 }
95
96 /// Represents the Http Etag Header field.
97 ///
98 /// See [RFC 7231](https://tools.ietf.org/html/rfc7231#section-7.2) for more.
99 pub fn http_etag(&self) -> Option<&str> {
100 self.http_etag.as_deref()
101 }
102
103 /// Set `http_etag` value.
104 pub fn set_http_etag(&mut self, value: Option<&str>) {
105 self.http_etag = value.map(|x| x.to_string());
106 }
107
108 /// Extract Etag and LastModifier from res, and update self and the
109 /// corresponding db row.
110 fn update_etag(mut self, res: &reqwest::Response) -> Result<Self, DataError> {
111 let headers = res.headers();
112
113 let etag = headers.get(ETAG).and_then(|h| h.to_str().ok());
114 let lmod = headers
115 .get(LAST_MODIFIED)
116 .and_then(|h| h.to_str().ok())
117 .map(From::from);
118
119 if (self.http_etag() != etag) || (self.last_modified != lmod) {
120 self.set_http_etag(etag);
121 self.set_last_modified(lmod);
122 self = self.save()?;
123 }
124
125 Ok(self)
126 }
127
128 /// Clear the `HTTP` `Etag` and `Last-modified` headers.
129 /// This method does not sync the state of self in the database, call
130 /// .save() method explicitly
131 fn clear_etags(&mut self) {
132 debug!("Source etags before clear: {:#?}", &self);
133 self.http_etag = None;
134 self.last_modified = None;
135 }
136
137 fn make_err(self, context: &str, code: StatusCode) -> DataError {
138 DataError::HttpStatusGeneral {
139 url: self.uri,
140 status_code: code,
141 context: context.into(),
142 }
143 }
144
145 // TODO match on more stuff
146 // 301: Moved Permanently
147 // 304: Up to date Feed, checked with the Etag
148 // 307: Temporary redirect of the url
149 // 308: Permanent redirect of the url
150 // 401: Unathorized
151 // 403: Forbidden
152 // 408: Timeout
153 // 410: Feed deleted
154 // TODO: Rething this api,
155 fn match_status(mut self, res: reqwest::Response) -> Result<reqwest::Response, DataError> {
156 let code = res.status();
157
158 if code.is_success() {
159 // If request is successful save the etag
160 self = self.update_etag(&res)?
161 } else {
162 match code.as_u16() {
163 // Save etags if it returns NotModified
164 304 => self = self.update_etag(&res)?,
165 // Clear the Etag/lmod else
166 _ => {
167 self.clear_etags();
168 self = self.save()?;
169 }
170 };
171 };
172
173 match code.as_u16() {
174 304 => {
175 info!("304: Source, {} is up to date", self.uri());
176 return Err(DataError::FeedNotModified(self));
177 }
178 301 | 308 => {
179 info!("Feed was moved permanently.");
180 self = self.update_url(&res)?;
181 return Err(DataError::FeedRedirect(self));
182 }
183 302 | 307 => {
184 info!("302/307: Temporary Redirect.");
185 return Err(DataError::FeedRedirect(self));
186 }
187 401 => return Err(self.make_err("401: Unauthorized.", code)),
188 403 => return Err(self.make_err("403: Forbidden.", code)),
189 404 => return Err(self.make_err("404: Not found.", code)),
190 408 => return Err(self.make_err("408: Request Timeout.", code)),
191 410 => return Err(self.make_err("410: Feed was deleted..", code)),
192 _ => info!("HTTP StatusCode: {}", code),
193 };
194
195 Ok(res)
196 }
197
198 fn update_url(mut self, res: &reqwest::Response) -> Result<Self, DataError> {
199 let code = res.status();
200 let headers = res.headers();
201 info!("HTTP StatusCode: {}", code);
202 debug!("Headers {:#?}", headers);
203
204 if let Some(url) = headers.get(LOCATION) {
205 debug!("Previous Source: {:#?}", &self);
206
207 self.set_uri(url.to_str()?.into());
208 self.clear_etags();
209 self = self.save()?;
210
211 debug!("Updated Source: {:#?}", &self);
212 info!(
213 "Feed url of Source {}, was updated successfully.",
214 self.uri()
215 );
216 }
217
218 Ok(self)
219 }
220
221 /// Construct a new `Source` with the given `uri` and index it.
222 ///
223 /// This only indexes the `Source` struct, not the Podcast Feed.
224 pub fn from_url(uri: &str) -> Result<Source, DataError> {
225 let url = Url::parse(uri)?;
226
227 NewSource::new(&url).to_source()
228 }
229
230 /// `Feed` constructor.
231 ///
232 /// Fetches the latest xml Feed.
233 ///
234 /// Updates the validator Http Headers.
235 ///
236 /// Consumes `self` and Returns the corresponding `Feed` Object.
237 // Refactor into TryInto once it lands on stable.
238 pub async fn into_feed(self, client: &reqwest::Client) -> Result<Feed, DataError> {
239 let id = self.id();
240
241 let resp = self.get_response(client).await?;
242 let chan = response_to_channel(resp).await?;
243
244 FeedBuilder::default()
245 .channel(chan)
246 .source_id(id)
247 .build()
248 .map_err(|err| DataError::BuilderError(format!("{err}")))
249 }
250
251 async fn get_response(self, client: &reqwest::Client) -> Result<reqwest::Response, DataError> {
252 let mut source = self;
253 loop {
254 match source.request_constructor(client).await {
255 Ok(response) => return Ok(response),
256 Err(err) => match err {
257 DataError::FeedRedirect(s) => {
258 info!("Following redirect...");
259 source = s;
260 }
261 e => return Err(e),
262 },
263 }
264 }
265 }
266
267 async fn request_constructor(
268 self,
269 client: &reqwest::Client,
270 ) -> Result<reqwest::Response, DataError> {
271 let uri = Url::from_str(self.uri())?;
272 let mut req = client.get(uri);
273
274 if let Ok(url) = Url::parse(self.uri()) {
275 if let Some(password) = url.password() {
276 let mut auth = "Basic ".to_owned();
277 auth.push_str(&general_purpose::URL_SAFE.encode(
278 //url.username() converts @ symbols to %40 automatically. The "replace" undoes that.
279 format!("{}:{}", url.username().replace("%40", "@"), password),
280 ));
281 req = req.header(AUTHORIZATION, HeaderValue::from_str(&auth).unwrap());
282 }
283 }
284
285 // Set the UserAgent cause ppl still seem to check it for some reason...
286 req = req.header(USER_AGENT_HEADER, HeaderValue::from_static(USER_AGENT));
287
288 if let Some(etag) = self.http_etag() {
289 req = req.header(IF_NONE_MATCH, HeaderValue::from_str(etag).unwrap());
290 }
291
292 if let Some(lmod) = self.last_modified() {
293 req = req.header(IF_MODIFIED_SINCE, HeaderValue::from_str(lmod).unwrap());
294 }
295
296 let res = req.send().await?;
297 self.match_status(res)
298 }
299 }
300
301 async fn response_to_channel(res: reqwest::Response) -> Result<Channel, DataError> {
302 use bytes::buf::Buf;
303 let chunk = res.bytes().await?;
304
305 // Channel will do it's own decoding of strings
306 // based on what is specified in <?xml encoding="..."?>.
307 // So just pass it the raw byets.
308 Channel::read_from(chunk.reader()).map_err(From::from)
309 }
310
311 #[cfg(test)]
312 mod tests {
313 use super::*;
314 use anyhow::Result;
315
316 use crate::database::truncate_db;
317 use crate::dbqueries;
318 use crate::downloader::client_builder;
319 use crate::utils::get_feed;
320
321 #[test]
322 fn test_into_feed() -> Result<()> {
323 truncate_db()?;
324
325 let rt = tokio::runtime::Runtime::new()?;
326 let client = client_builder().build()?;
327
328 let url = "https://web.archive.org/web/20180120083840if_/https://feeds.feedburner.\
329 com/InterceptedWithJeremyScahill";
330 let source = Source::from_url(url)?;
331 let id = source.id();
332 let feed = source.into_feed(&client);
333 let feed = rt.block_on(feed)?;
334
335 let expected = get_feed("tests/feeds/2018-01-20-Intercepted.xml", id);
336 assert_eq!(expected, feed);
337 Ok(())
338 }
339
340 #[test]
341 fn test_into_non_utf8() -> Result<()> {
342 truncate_db()?;
343
344 let rt = tokio::runtime::Runtime::new()?;
345 let client = client_builder().build()?;
346
347 let url = "https://web.archive.org/web/20220205205130if_/https://dinamics.ccma.\
348 cat/public/podcast/catradio/xml/series-i-cinema.xml";
349 let source = Source::from_url(url)?;
350 let id = source.id();
351 let feed = source.into_feed(&client);
352 let feed = rt.block_on(feed)?;
353
354 let expected = get_feed("tests/feeds/2022-series-i-cinema.xml", id);
355 assert_eq!(expected, feed);
356
357 feed.index()?;
358 assert_eq!(dbqueries::get_podcasts()?.len(), 1);
359 assert_eq!(
360 dbqueries::get_podcasts()?[0].description(),
361 "Els clàssics, les novetats de la cartellera i les millors \
362 sèries, tot en un sol podcast."
363 );
364 Ok(())
365 }
366 }