Debian Codegraph @

podcasts-data/src/feed.rs

raw symbols ◀ ▶ SCIP
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 /* Disable tests that require XML feeds
198 #[test]
199 fn test_complete_index() -> Result<()> {
200 truncate_db()?;
201
202 let feeds: Vec<_> = URLS
203 .iter()
204 .map(|&(path, url)| {
205 // Create and insert a Source into db
206 let s = Source::from_url(url).unwrap();
207 get_feed(path, s.id())
208 })
209 .collect();
210
211 // Index the channels
212 for feed in feeds {
213 feed.index()?
214 }
215
216 // Assert the index rows equal the controlled results
217 assert_eq!(dbqueries::get_sources()?.len(), 6);
218 assert_eq!(dbqueries::get_podcasts()?.len(), 6);
219 assert_eq!(dbqueries::get_episodes()?.len(), 404);
220 Ok(())
221 }
222
223 #[test]
224 fn test_feed_parse_podcast() -> Result<()> {
225 truncate_db()?;
226
227 let path = "tests/feeds/2018-01-20-Intercepted.xml";
228 let feed = get_feed(path, TEST_SOURCE_ID);
229
230 let file = fs::File::open(path)?;
231 let channel = Channel::read_from(BufReader::new(file))?;
232
233 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
234 assert_eq!(feed.parse_podcast(), pd);
235 Ok(())
236 }
237
238 #[test]
239 fn test_feed_index_channel_items() -> Result<()> {
240 truncate_db()?;
241
242 let path = "tests/feeds/2018-01-20-Intercepted.xml";
243 let feed = get_feed(path, TEST_SOURCE_ID);
244 let pd = feed.parse_podcast().to_podcast()?;
245
246 feed.index_channel_items(pd)?;
247 assert_eq!(dbqueries::get_podcasts()?.len(), 1);
248 assert_eq!(dbqueries::get_episodes()?.len(), 43);
249 Ok(())
250 }
251
252 #[test]
253 fn test_feed_non_utf8() -> Result<()> {
254 truncate_db()?;
255
256 let path = "tests/feeds/2022-series-i-cinema.xml";
257 let feed = get_feed(path, TEST_SOURCE_ID);
258
259 let file = fs::File::open(path)?;
260 let channel = Channel::read_from(BufReader::new(file))?;
261
262 let description = feed.channel.description();
263 assert_eq!(
264 description,
265 "Els clàssics, les novetats de la cartellera i les millors sèries, tot en un sol podcast."
266 );
267 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
268 assert_eq!(feed.parse_podcast(), pd);
269 Ok(())
270 }
271
272 // https://gitlab.gnome.org/World/podcasts/-/issues/239
273 #[test]
274 fn test_feed_same_title_different_guid() -> Result<()> {
275 truncate_db()?;
276
277 let path = "tests/feeds/de-grote.xml";
278 let feed = get_feed(path, TEST_SOURCE_ID);
279 let pd = feed.parse_podcast().to_podcast()?;
280
281 feed.index_channel_items(pd)?;
282 assert_eq!(dbqueries::get_podcasts()?.len(), 1);
283 assert_eq!(dbqueries::get_episodes()?.len(), 12);
284 Ok(())
285 }
286
287 // https://gitlab.gnome.org/World/podcasts/-/issues/239
288 #[test]
289 fn test_feed_same_title_no_guid() -> Result<()> {
290 truncate_db()?;
291
292 let path = "tests/feeds/de-grote-no-guid.xml";
293 let feed = get_feed(path, TEST_SOURCE_ID);
294 let pd = feed.parse_podcast().to_podcast()?;
295
296 feed.index_channel_items(pd)?;
297
298 let eps = dbqueries::get_episodes()?;
299
300 assert_eq!(1, dbqueries::get_podcasts()?.len());
301 assert_eq!(2, eps.len());
302
303 // latest episode (latest item in feed), previous items with same title are ignored
304 let ep1 = eps.get(0).unwrap();
305 assert_eq!(
306 Some(
307 "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"
308 ),
309 ep1.uri()
310 );
311
312 // teaser (first item in feed)
313 let ep2 = eps.get(1).unwrap();
314 assert_eq!(
315 Some(
316 "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"
317 ),
318 ep2.uri()
319 );
320
321 Ok(())
322 }
323
324 // https://gitlab.gnome.org/World/podcasts/-/issues/204
325 #[test]
326 fn test_reruns() -> Result<()> {
327 truncate_db()?;
328
329 let path = "tests/feeds/2020-12-29-replyall.xml";
330 let feed = get_feed(path, TEST_SOURCE_ID);
331 let pd = feed.parse_podcast().to_podcast()?;
332 feed.index_channel_items(pd)?;
333 let show_id = dbqueries::get_podcasts()?.get(0).unwrap().id();
334
335 let eps = dbqueries::get_episodes()?;
336 let rerun_eps: Vec<_> = eps
337 .into_iter()
338 .filter(|e| e.title() == "#86 Man of the People")
339 .collect();
340
341 assert_eq!(rerun_eps.len(), 2);
342 // rerun
343 let ep1 = rerun_eps.get(0).unwrap();
344 assert_eq!("#86 Man of the People", ep1.title());
345 assert_eq!(Some("c16006fa-e2c3-11e9-be80-bf4954f39568"), ep1.guid());
346 assert_eq!(
347 Some("https://traffic.megaphone.fm/GLT8202680871.mp3?updated=1607019082"),
348 ep1.uri()
349 );
350 assert_eq!(
351 &dbqueries::get_episode(
352 Some("c16006fa-e2c3-11e9-be80-bf4954f39568"),
353 "#86 Man of the People",
354 show_id
355 )?,
356 ep1
357 );
358
359 // original run
360 let ep2 = rerun_eps.get(1).unwrap();
361 assert_eq!("#86 Man of the People", ep2.title());
362 assert_eq!(Some("3e7f1804-affc-11e6-892a-bb965a8b4a3f"), ep2.guid());
363 assert_eq!(
364 Some("https://traffic.megaphone.fm/GLT1103232835.mp3?updated=1486920888"),
365 ep2.uri()
366 );
367 assert_eq!(
368 &dbqueries::get_episode(
369 Some("3e7f1804-affc-11e6-892a-bb965a8b4a3f"),
370 "#86 Man of the People",
371 show_id
372 )?,
373 ep2
374 );
375
376 Ok(())
377 }
378
379 #[test]
380 // has same title and &amp; sign in title
381 fn test_same_title_streetfight() -> Result<()> {
382 truncate_db()?;
383
384 let path = "tests/feeds/2024-03-15-streetfightradio.xml";
385 let feed = get_feed(path, TEST_SOURCE_ID);
386 let pd = feed.parse_podcast().to_podcast()?;
387 feed.index_channel_items(pd)?;
388 let show_id = dbqueries::get_podcasts()?.get(0).unwrap().id();
389
390 let eps = dbqueries::get_episodes()?;
391 let same_title_eps: Vec<_> = eps
392 .clone()
393 .into_iter()
394 .filter(|e| e.title() == "Return Of The Macks")
395 .collect();
396
397 assert_eq!(2, same_title_eps.len());
398 let ep1 = same_title_eps.get(0).unwrap();
399 assert_eq!("Return Of The Macks", ep1.title());
400 assert_eq!(Some("tag:soundcloud,2010:tracks/501720369"), ep1.guid());
401 assert_eq!(
402 Some(
403 "https://feeds.soundcloud.com/stream/501720369-streetfightwcrs-return-of-the-macks-1.mp3"
404 ),
405 ep1.uri()
406 );
407 assert_eq!(
408 &dbqueries::get_episode(
409 Some("tag:soundcloud,2010:tracks/501720369"),
410 "Return Of The Macks",
411 show_id
412 )?,
413 ep1
414 );
415
416 let ep2 = same_title_eps.get(1).unwrap();
417 assert_eq!("Return Of The Macks", ep2.title());
418 assert_eq!(Some("tag:soundcloud,2010:tracks/430832790"), ep2.guid());
419 assert_eq!(
420 Some(
421 "https://feeds.soundcloud.com/stream/430832790-streetfightwcrs-return-of-the-macks.mp3"
422 ),
423 ep2.uri()
424 );
425 assert_eq!(
426 &dbqueries::get_episode(
427 Some("tag:soundcloud,2010:tracks/430832790"),
428 "Return Of The Macks",
429 show_id
430 )?,
431 ep2
432 );
433
434 // second title
435 let same_title_eps: Vec<_> = eps
436 .into_iter()
437 .filter(|e| e.title() == "Street Fight Q&A")
438 .collect();
439
440 assert_eq!(2, same_title_eps.len());
441 let ep1 = same_title_eps.get(0).unwrap();
442 assert_eq!("Street Fight Q&A", ep1.title());
443 assert_eq!(Some("tag:soundcloud,2010:tracks/658646834"), ep1.guid());
444 assert_eq!(
445 Some(
446 "https://feeds.soundcloud.com/stream/658646834-streetfightwcrs-street-fight-qa-1.mp3"
447 ),
448 ep1.uri()
449 );
450 assert_eq!(
451 &dbqueries::get_episode(
452 Some("tag:soundcloud,2010:tracks/658646834"),
453 "Street Fight Q&A",
454 show_id
455 )?,
456 ep1
457 );
458
459 let ep2 = same_title_eps.get(1).unwrap();
460 assert_eq!("Street Fight Q&A", ep2.title());
461 assert_eq!(Some("tag:soundcloud,2010:tracks/624834786"), ep2.guid());
462 assert_eq!(
463 Some(
464 "https://feeds.soundcloud.com/stream/624834786-streetfightwcrs-street-fight-qa.mp3"
465 ),
466 ep2.uri()
467 );
468 assert_eq!(
469 &dbqueries::get_episode(
470 Some("tag:soundcloud,2010:tracks/624834786"),
471 "Street Fight Q&A",
472 show_id
473 )?,
474 ep2
475 );
476
477 Ok(())
478 }
•479 */
480 }