Debian Codegraph @

podcasts-data/src/feed.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // feed.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 //! Index Feeds.
21
22 use crate::dbqueries;
23 use crate::errors::DataError;
24 use crate::models::{EpisodeId, NewEpisode, NewEpisodeMinimal, NewShow, Show, SourceId};
25 use crate::models::{Index, IndexState, Update};
26
27 /// Wrapper struct that hold a `Source` id and the `rss::Channel`
28 /// that corresponds to the `Source.uri` field.
29 #[derive(Debug, Clone, Builder, PartialEq)]
30 #[builder(derive(Debug))]
31 #[builder(setter(into))]
32 pub struct Feed {
33 /// The `rss::Channel` parsed from the `Source` uri.
34 channel: rss::Channel,
35 /// The `Source` id where the xml `rss::Channel` came from.
36 source_id: SourceId,
37 }
38
39 impl Feed {
40 /// Index the contents of the RSS `Feed` into the database.
41 pub fn index(self) -> Result<(), DataError> {
42 let show = self.parse_podcast().to_podcast()?;
43 self.index_channel_items(show)
44 }
45
46 fn parse_podcast(&self) -> NewShow {
47 NewShow::new(&self.channel, self.source_id)
48 }
49
50 fn index_channel_items(self, pd: Show) -> Result<(), DataError> {
51 let stream = self.channel.into_items().into_iter();
52 // Parse the episodes
53 let episodes = stream.filter_map(move |item| {
54 let ret = NewEpisodeMinimal::new(&item, pd.id())
55 .and_then(move |ep| determine_ep_state(ep, &item));
56 if ret.is_ok() {
57 Some(ret)
58 } else {
59 error!("importing ep: {:?}", ret);
60 None
61 }
62 });
63 // Filter errors, Index updatable episodes, return insertables.
64 let insertable_episodes = filter_episodes(episodes);
65 batch_insert_episodes(&insertable_episodes);
66 Ok(())
67 }
68 }
69
70 fn determine_ep_state(
71 ep: NewEpisodeMinimal,
72 item: &rss::Item,
73 ) -> Result<IndexState<NewEpisode, EpisodeId>, DataError> {
74 // Check if feed exists
75 let exists = dbqueries::episode_exists(ep.guid(), ep.title(), ep.show_id())?;
76
77 if !exists {
78 Ok(IndexState::Index(ep.into_new_episode(item)))
79 } else {
80 let old = dbqueries::get_episode_minimal(ep.guid(), ep.title(), ep.show_id())?;
81 let id = old.id();
82
83 if ep != old {
84 Ok(IndexState::Update((ep.into_new_episode(item), id)))
85 } else {
86 Ok(IndexState::NotChanged)
87 }
88 }
89 }
90
91 fn filter_episodes<S>(stream: S) -> Vec<NewEpisode>
92 where
93 S: Iterator<Item = Result<IndexState<NewEpisode, EpisodeId>, DataError>>,
94 {
95 let result: Vec<NewEpisode> = stream
96 .filter_map(Result::ok)
97 .filter_map(|state| {
98 match state {
99 IndexState::NotChanged => None,
100 // Update individual rows, and filter them
101 IndexState::Update((ref ep, id)) => {
102 if let Err(err) = ep.update(id) {
103 error!("{}", err);
104 error!("Failed to index episode: {:?}.", ep.title())
105 }
106 None
107 }
108 IndexState::Index(s) => Some(s),
109 }
110 })
111 // only Index is left, collect them for batch index
112 .collect();
113
114 // filter out duplicates with same guid or title, they are assumed to be the same episode
115 let mut set = std::collections::HashSet::new();
116 result
117 .into_iter()
118 .filter(|ep| {
119 let id = ep.guid().unwrap_or(ep.title()).to_string();
120 set.insert(id)
121 })
122 .collect()
123 }
124
125 fn batch_insert_episodes(episodes: &[NewEpisode]) {
126 if episodes.is_empty() {
127 return;
128 };
129
130 info!("Indexing {} episodes.", episodes.len());
131 if let Err(err) = dbqueries::index_new_episodes(episodes) {
132 error!("Failed batch indexing: {}", err);
133 info!("Falling back to individual indexing.");
134 } else {
135 for ep in episodes {
136 if let Err(err) = ep.index() {
137 error!("Error: {}.", err);
138 error!("Failed to index episode: {:?}.", ep.title());
139 }
140 }
141 }
142 }
143
144 #[cfg(test)]
145 mod tests {
146 use anyhow::Result;
147 use rss::Channel;
148
149 use crate::EpisodeModel;
150 use crate::Source;
151 use crate::database::truncate_db;
152 use crate::dbqueries;
153 use crate::utils::get_feed;
154
155 use std::fs;
156 use std::io::BufReader;
157
158 use super::*;
159
160 // (path, url) tuples.
161 const URLS: &[(&str, &str)] = {
162 &[
163 (
164 "tests/feeds/2018-01-20-Intercepted.xml",
165 "https://web.archive.org/web/20180120083840if_/https://feeds.feedburner.\
166 com/InterceptedWithJeremyScahill",
167 ),
168 (
169 "tests/feeds/2018-01-20-LinuxUnplugged.xml",
170 "https://web.archive.org/web/20180120110314if_/https://feeds.feedburner.\
171 com/linuxunplugged",
172 ),
173 (
174 "tests/feeds/2018-01-20-TheTipOff.xml",
175 "https://web.archive.org/web/20180120110727if_/https://rss.acast.com/thetipoff",
176 ),
177 (
178 "tests/feeds/2018-01-20-StealTheStars.xml",
179 "https://web.archive.org/web/20180120104957if_/https://rss.art19.\
180 com/steal-the-stars",
181 ),
182 (
183 "tests/feeds/2018-01-20-GreaterThanCode.xml",
184 "https://web.archive.org/web/20180120104741if_/https://www.greaterthancode.\
185 com/feed/podcast",
186 ),
187 (
188 "tests/feeds/2022-series-i-cinema.xml",
189 "https://web.archive.org/web/20220205205130_/https://dinamics.ccma.\
190 cat/public/podcast/catradio/xml/series-i-cinema.xml",
191 ),
192 ]
193 };
194 /// randomly chosen
195 const TEST_SOURCE_ID: SourceId = SourceId(42);
196
197 #[test]
198 fn test_complete_index() -> Result<()> {
199 truncate_db()?;
200
201 let feeds: Vec<_> = URLS
202 .iter()
203 .map(|&(path, url)| {
204 // Create and insert a Source into db
205 let s = Source::from_url(url).unwrap();
206 get_feed(path, s.id())
207 })
208 .collect();
209
210 // Index the channels
211 for feed in feeds {
212 feed.index()?
213 }
214
215 // Assert the index rows equal the controlled results
216 assert_eq!(dbqueries::get_sources()?.len(), 6);
217 assert_eq!(dbqueries::get_podcasts()?.len(), 6);
218 assert_eq!(dbqueries::get_episodes()?.len(), 404);
219 Ok(())
220 }
221
222 #[test]
223 fn test_feed_parse_podcast() -> Result<()> {
224 truncate_db()?;
225
226 let path = "tests/feeds/2018-01-20-Intercepted.xml";
227 let feed = get_feed(path, TEST_SOURCE_ID);
228
229 let file = fs::File::open(path)?;
230 let channel = Channel::read_from(BufReader::new(file))?;
231
232 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
233 assert_eq!(feed.parse_podcast(), pd);
234 Ok(())
235 }
236
237 #[test]
238 fn test_feed_index_channel_items() -> Result<()> {
239 truncate_db()?;
240
241 let path = "tests/feeds/2018-01-20-Intercepted.xml";
242 let feed = get_feed(path, TEST_SOURCE_ID);
243 let pd = feed.parse_podcast().to_podcast()?;
244
245 feed.index_channel_items(pd)?;
246 assert_eq!(dbqueries::get_podcasts()?.len(), 1);
247 assert_eq!(dbqueries::get_episodes()?.len(), 43);
248 Ok(())
249 }
250
251 #[test]
252 fn test_feed_non_utf8() -> Result<()> {
253 truncate_db()?;
254
255 let path = "tests/feeds/2022-series-i-cinema.xml";
256 let feed = get_feed(path, TEST_SOURCE_ID);
257
258 let file = fs::File::open(path)?;
259 let channel = Channel::read_from(BufReader::new(file))?;
260
261 let description = feed.channel.description();
262 assert_eq!(
263 description,
264 "Els clàssics, les novetats de la cartellera i les millors sèries, tot en un sol podcast."
265 );
266 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
267 assert_eq!(feed.parse_podcast(), pd);
268 Ok(())
269 }
270
271 // https://gitlab.gnome.org/World/podcasts/-/issues/239
272 #[test]
273 fn test_feed_same_title_different_guid() -> Result<()> {
274 truncate_db()?;
275
276 let path = "tests/feeds/de-grote.xml";
277 let feed = get_feed(path, TEST_SOURCE_ID);
278 let pd = feed.parse_podcast().to_podcast()?;
279
280 feed.index_channel_items(pd)?;
281 assert_eq!(dbqueries::get_podcasts()?.len(), 1);
282 assert_eq!(dbqueries::get_episodes()?.len(), 12);
283 Ok(())
284 }
285
286 // https://gitlab.gnome.org/World/podcasts/-/issues/239
287 #[test]
288 fn test_feed_same_title_no_guid() -> Result<()> {
289 truncate_db()?;
290
291 let path = "tests/feeds/de-grote-no-guid.xml";
292 let feed = get_feed(path, TEST_SOURCE_ID);
293 let pd = feed.parse_podcast().to_podcast()?;
294
295 feed.index_channel_items(pd)?;
296
297 let eps = dbqueries::get_episodes()?;
298
299 assert_eq!(1, dbqueries::get_podcasts()?.len());
300 assert_eq!(2, eps.len());
301
302 // latest episode (latest item in feed), previous items with same title are ignored
303 let ep1 = eps.get(0).unwrap();
304 assert_eq!(
305 Some(
306 "https://chtbl.com/track/11G3D/progressive-audio.vrt.be/public/output/aud-7478134e-7c0e-44d4-8d65-32aa87dc6a3a-PODCAST_1/aud-7478134e-7c0e-44d4-8d65-32aa87dc6a3a-PODCAST_1.mp3"
307 ),
308 ep1.uri()
309 );
310
311 // teaser (first item in feed)
312 let ep2 = eps.get(1).unwrap();
313 assert_eq!(
314 Some(
315 "https://chtbl.com/track/11G3D/progressive-audio.vrt.be/public/output/aud-6b925160-4400-4d50-bb54-0085b84643cd-PODCAST_1/aud-6b925160-4400-4d50-bb54-0085b84643cd-PODCAST_1.mp3"
316 ),
317 ep2.uri()
318 );
319
320 Ok(())
321 }
322
323 // https://gitlab.gnome.org/World/podcasts/-/issues/204
324 #[test]
325 fn test_reruns() -> Result<()> {
326 truncate_db()?;
327
328 let path = "tests/feeds/2020-12-29-replyall.xml";
329 let feed = get_feed(path, TEST_SOURCE_ID);
330 let pd = feed.parse_podcast().to_podcast()?;
331 feed.index_channel_items(pd)?;
332 let show_id = dbqueries::get_podcasts()?.get(0).unwrap().id();
333
334 let eps = dbqueries::get_episodes()?;
335 let rerun_eps: Vec<_> = eps
336 .into_iter()
337 .filter(|e| e.title() == "#86 Man of the People")
338 .collect();
339
340 assert_eq!(rerun_eps.len(), 2);
341 // rerun
342 let ep1 = rerun_eps.get(0).unwrap();
343 assert_eq!("#86 Man of the People", ep1.title());
344 assert_eq!(Some("c16006fa-e2c3-11e9-be80-bf4954f39568"), ep1.guid());
345 assert_eq!(
346 Some("https://traffic.megaphone.fm/GLT8202680871.mp3?updated=1607019082"),
347 ep1.uri()
348 );
349 assert_eq!(
350 &dbqueries::get_episode(
351 Some("c16006fa-e2c3-11e9-be80-bf4954f39568"),
352 "#86 Man of the People",
353 show_id
354 )?,
355 ep1
356 );
357
358 // original run
359 let ep2 = rerun_eps.get(1).unwrap();
360 assert_eq!("#86 Man of the People", ep2.title());
361 assert_eq!(Some("3e7f1804-affc-11e6-892a-bb965a8b4a3f"), ep2.guid());
362 assert_eq!(
363 Some("https://traffic.megaphone.fm/GLT1103232835.mp3?updated=1486920888"),
364 ep2.uri()
365 );
366 assert_eq!(
367 &dbqueries::get_episode(
368 Some("3e7f1804-affc-11e6-892a-bb965a8b4a3f"),
369 "#86 Man of the People",
370 show_id
371 )?,
372 ep2
373 );
374
375 Ok(())
376 }
377
378 #[test]
379 // has same title and &amp; sign in title
380 fn test_same_title_streetfight() -> Result<()> {
381 truncate_db()?;
382
383 let path = "tests/feeds/2024-03-15-streetfightradio.xml";
384 let feed = get_feed(path, TEST_SOURCE_ID);
385 let pd = feed.parse_podcast().to_podcast()?;
386 feed.index_channel_items(pd)?;
387 let show_id = dbqueries::get_podcasts()?.get(0).unwrap().id();
388
389 let eps = dbqueries::get_episodes()?;
390 let same_title_eps: Vec<_> = eps
391 .clone()
392 .into_iter()
393 .filter(|e| e.title() == "Return Of The Macks")
394 .collect();
395
396 assert_eq!(2, same_title_eps.len());
397 let ep1 = same_title_eps.get(0).unwrap();
398 assert_eq!("Return Of The Macks", ep1.title());
399 assert_eq!(Some("tag:soundcloud,2010:tracks/501720369"), ep1.guid());
400 assert_eq!(
401 Some(
402 "https://feeds.soundcloud.com/stream/501720369-streetfightwcrs-return-of-the-macks-1.mp3"
403 ),
404 ep1.uri()
405 );
406 assert_eq!(
407 &dbqueries::get_episode(
408 Some("tag:soundcloud,2010:tracks/501720369"),
409 "Return Of The Macks",
410 show_id
411 )?,
412 ep1
413 );
414
415 let ep2 = same_title_eps.get(1).unwrap();
416 assert_eq!("Return Of The Macks", ep2.title());
417 assert_eq!(Some("tag:soundcloud,2010:tracks/430832790"), ep2.guid());
418 assert_eq!(
419 Some(
420 "https://feeds.soundcloud.com/stream/430832790-streetfightwcrs-return-of-the-macks.mp3"
421 ),
422 ep2.uri()
423 );
424 assert_eq!(
425 &dbqueries::get_episode(
426 Some("tag:soundcloud,2010:tracks/430832790"),
427 "Return Of The Macks",
428 show_id
429 )?,
430 ep2
431 );
432
433 // second title
434 let same_title_eps: Vec<_> = eps
435 .into_iter()
436 .filter(|e| e.title() == "Street Fight Q&A")
437 .collect();
438
439 assert_eq!(2, same_title_eps.len());
440 let ep1 = same_title_eps.get(0).unwrap();
441 assert_eq!("Street Fight Q&A", ep1.title());
442 assert_eq!(Some("tag:soundcloud,2010:tracks/658646834"), ep1.guid());
443 assert_eq!(
444 Some(
445 "https://feeds.soundcloud.com/stream/658646834-streetfightwcrs-street-fight-qa-1.mp3"
446 ),
447 ep1.uri()
448 );
449 assert_eq!(
450 &dbqueries::get_episode(
451 Some("tag:soundcloud,2010:tracks/658646834"),
452 "Street Fight Q&A",
453 show_id
454 )?,
455 ep1
456 );
457
458 let ep2 = same_title_eps.get(1).unwrap();
459 assert_eq!("Street Fight Q&A", ep2.title());
460 assert_eq!(Some("tag:soundcloud,2010:tracks/624834786"), ep2.guid());
461 assert_eq!(
462 Some(
463 "https://feeds.soundcloud.com/stream/624834786-streetfightwcrs-street-fight-qa.mp3"
464 ),
465 ep2.uri()
466 );
467 assert_eq!(
468 &dbqueries::get_episode(
469 Some("tag:soundcloud,2010:tracks/624834786"),
470 "Street Fight Q&A",
471 show_id
472 )?,
473 ep2
474 );
475
476 Ok(())
477 }
478 }