Debian Codegraph @

podcasts-data/src/models/new_episode.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // new_episode.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 chrono::prelude::*;
21 use diesel::prelude::*;
22 use rfc822_sanitizer::parse_from_rfc2822_with_fallback as parse_rfc822;
23
24 use crate::database::connection;
25 use crate::dbqueries;
26 use crate::errors::DataError;
27 use crate::models::episode::EpisodeId;
28 use crate::models::{Episode, EpisodeMinimal, EpisodeModel, Index, Insert, ShowId, Update};
29 use crate::parser;
30 use crate::schema::episodes;
31 use crate::utils::url_cleaner;
32
33 #[derive(Insertable, AsChangeset)]
34 #[diesel(table_name = episodes)]
35 #[derive(Debug, Clone, Default, Builder, PartialEq)]
36 #[builder(default)]
37 #[builder(derive(Debug))]
38 #[builder(setter(into))]
39 pub(crate) struct NewEpisode {
40 title: String,
41 uri: Option<String>,
42 description: Option<String>,
43 image_uri: Option<String>,
44 length: Option<i32>,
45 duration: Option<i32>,
46 play_position: i32,
47 guid: Option<String>,
48 epoch: NaiveDateTime,
49 show_id: ShowId,
50 }
51
52 impl From<NewEpisodeMinimal> for NewEpisode {
53 fn from(e: NewEpisodeMinimal) -> Self {
54 NewEpisodeBuilder::default()
55 .title(e.title)
56 .uri(e.uri)
57 .image_uri(e.image_uri)
58 .duration(e.duration)
59 .epoch(e.epoch)
60 .show_id(e.show_id)
61 .guid(e.guid)
62 .build()
63 .unwrap()
64 }
65 }
66
67 impl Insert<()> for NewEpisode {
68 type Error = DataError;
69
70 /// Should not be called directly, call index() instead.
71 fn insert(&self) -> Result<(), DataError> {
72 use crate::schema::episodes::dsl::*;
73 let db = connection();
74 let mut con = db.get()?;
75
76 info!("Inserting {:?}", self.title);
77 diesel::insert_into(episodes)
78 .values(self)
79 .execute(&mut con)
80 .map_err(From::from)
81 .map(|_| ())
82 }
83 }
84
85 impl Update<(), EpisodeId> for NewEpisode {
86 type Error = DataError;
87
88 fn update(&self, episode_id: EpisodeId) -> Result<(), DataError> {
89 use crate::schema::episodes::dsl::*;
90 let db = connection();
91 let mut con = db.get()?;
92
93 info!("Updating {:?}", self.title);
94 diesel::update(episodes.filter(id.eq(episode_id)))
95 .set(self)
96 .execute(&mut con)
97 .map_err(From::from)
98 .map(|_| ())
99 }
100 }
101
102 impl Index<(), EpisodeId> for NewEpisode {
103 type Error = DataError;
104
105 // Does not update the episode description if it's the only thing that has
106 // changed.
107 fn index(&self) -> Result<(), DataError> {
108 let exists = dbqueries::episode_exists(self.guid(), self.title(), self.show_id())?;
109
110 if exists {
111 let other = dbqueries::get_episode_minimal(self.guid(), self.title(), self.show_id())?;
112
113 if self != &other {
114 self.update(other.id())
115 } else {
116 Ok(())
117 }
118 } else {
119 self.insert()
120 }
121 }
122 }
123
124 impl PartialEq<EpisodeMinimal> for NewEpisode {
125 fn eq(&self, other: &EpisodeMinimal) -> bool {
126 (self.title() == other.title())
127 && (self.uri() == other.uri())
128 && (self.image_uri() == other.image_uri())
129 && (self.duration() == other.duration())
130 && (self.epoch() == other.epoch())
131 && (self.guid() == other.guid())
132 && (self.show_id() == other.show_id())
133 }
134 }
135
136 impl PartialEq<Episode> for NewEpisode {
137 fn eq(&self, other: &Episode) -> bool {
138 (self.title() == other.title())
139 && (self.uri() == other.uri())
140 && (self.image_uri() == other.image_uri())
141 && (self.duration() == other.duration())
142 && (self.play_position() == other.play_position())
143 && (self.epoch() == other.epoch())
144 && (self.guid() == other.guid())
145 && (self.show_id() == other.show_id())
146 && (self.description() == other.description())
147 && (self.length() == other.length())
148 }
149 }
150
151 impl NewEpisode {
152 /// Parses an `rss::Item` into a `NewEpisode` Struct.
153 #[allow(dead_code)]
154 pub(crate) fn new(item: &rss::Item, show_id: ShowId) -> Result<Self, DataError> {
155 NewEpisodeMinimal::new(item, show_id).map(|ep| ep.into_new_episode(item))
156 }
157
158 #[allow(dead_code)]
159 pub(crate) fn to_episode(&self) -> Result<Episode, DataError> {
160 self.index()?;
161
162 dbqueries::get_episode(self.guid(), self.title(), self.show_id)
163 }
164 }
165
166 // Ignore the following getters. They are used in unit tests mainly.
167 impl NewEpisode {
168 pub(crate) fn title(&self) -> &str {
169 self.title.as_ref()
170 }
171
172 pub(crate) fn uri(&self) -> Option<&str> {
173 self.uri.as_deref()
174 }
175 pub(crate) fn image_uri(&self) -> Option<&str> {
176 self.image_uri.as_deref()
177 }
178
179 pub(crate) fn description(&self) -> Option<&str> {
180 self.description.as_deref()
181 }
182
183 pub(crate) fn guid(&self) -> Option<&str> {
184 self.guid.as_deref()
185 }
186
187 pub(crate) fn epoch(&self) -> NaiveDateTime {
188 self.epoch
189 }
190
191 pub(crate) fn duration(&self) -> Option<i32> {
192 self.duration
193 }
194
195 pub(crate) fn play_position(&self) -> i32 {
196 self.play_position
197 }
198
199 pub(crate) fn length(&self) -> Option<i32> {
200 self.length
201 }
202
203 pub(crate) fn show_id(&self) -> ShowId {
204 self.show_id
205 }
206 }
207
208 #[derive(Insertable, AsChangeset)]
209 #[diesel(table_name = episodes)]
210 #[derive(Debug, Clone, Builder, PartialEq)]
211 #[builder(derive(Debug))]
212 #[builder(setter(into))]
213 pub(crate) struct NewEpisodeMinimal {
214 title: String,
215 uri: Option<String>,
216 image_uri: Option<String>,
217 length: Option<i32>,
218 duration: Option<i32>,
219 #[builder(default = "0")]
220 play_position: i32,
221 epoch: NaiveDateTime,
222 guid: Option<String>,
223 show_id: ShowId,
224 }
225
226 impl PartialEq<EpisodeMinimal> for NewEpisodeMinimal {
227 fn eq(&self, other: &EpisodeMinimal) -> bool {
228 (self.title() == other.title())
229 && (self.uri() == other.uri())
230 && (self.image_uri() == other.image_uri())
231 && (self.duration() == other.duration())
232 && (self.epoch() == other.epoch())
233 && (self.guid() == other.guid())
234 && (self.show_id() == other.show_id())
235 }
236 }
237
238 impl NewEpisodeMinimal {
239 pub(crate) fn new(item: &rss::Item, parent_id: ShowId) -> Result<Self, DataError> {
240 if item.title().is_none() {
241 let err = DataError::ParseEpisodeError {
242 reason: "No title specified for this Episode.".into(),
243 parent_id,
244 };
245
246 return Err(err);
247 }
248
249 let title = item.title().unwrap().trim().to_owned();
250 let guid = item.guid().map(|s| s.value().trim().to_owned());
251
252 // Get the mime type, the `http` url and the length from the enclosure
253 // http://www.rssboard.org/rss-specification#ltenclosuregtSubelementOfLtitemgt
254 let enc = item.enclosure();
255
256 // Get the url
257 let uri = enc.map(|s| url_cleaner(s.url().trim()));
258
259 let image = item
260 .itunes_ext()
261 .and_then(|i| i.image())
262 .map(|s| s.to_owned());
263
264 // Get the size of the content, it should be in bytes
265 let length = enc.and_then(|x| x.length().parse().ok());
266
267 // Default to rfc2822 representation of epoch 0.
268 let date = parse_rfc822(item.pub_date().unwrap_or("Thu, 1 Jan 1970 00:00:00 +0000"));
269 // Should treat information from the rss feeds as invalid by default.
270 // Case: "Thu, 05 Aug 2016 06:00:00 -0400" <-- Actually that was friday.
271 let epoch = date
272 .map(|x| DateTime::<Utc>::from(x).naive_utc())
273 .unwrap_or_default();
274
275 let duration = parser::parse_itunes_duration(item.itunes_ext());
276
277 NewEpisodeMinimalBuilder::default()
278 .title(title)
279 .uri(uri)
280 .image_uri(image)
281 .length(length)
282 .duration(duration)
283 .epoch(epoch)
284 .guid(guid)
285 .show_id(parent_id)
286 .build()
287 .map_err(|err| DataError::BuilderError(format!("{err}")))
288 }
289
290 // TODO: TryInto is stabilizing in rustc v1.26!
291 // ^ Jokes on you past self!
292 pub(crate) fn into_new_episode(self, item: &rss::Item) -> NewEpisode {
293 let description = item.content().or(item.description()).map(|s| {
294 let sanitized_html = ammonia::Builder::new()
295 // Remove `rel` attributes from `<a>` tags
296 .link_rel(None)
297 .clean(s.trim())
298 .to_string();
299 sanitized_html
300 });
301
302 NewEpisodeBuilder::default()
303 .title(self.title)
304 .uri(self.uri)
305 .image_uri(self.image_uri)
306 .duration(self.duration)
307 .epoch(self.epoch)
308 .show_id(self.show_id)
309 .guid(self.guid)
310 .length(self.length)
311 .description(description)
312 .build()
313 .unwrap()
314 }
315 }
316
317 // Ignore the following getters. They are used in unit tests mainly.
318 impl NewEpisodeMinimal {
319 pub(crate) fn title(&self) -> &str {
320 self.title.as_ref()
321 }
322
323 pub(crate) fn uri(&self) -> Option<&str> {
324 self.uri.as_deref()
325 }
326
327 pub(crate) fn image_uri(&self) -> Option<&str> {
328 self.image_uri.as_deref()
329 }
330
331 pub(crate) fn guid(&self) -> Option<&str> {
332 self.guid.as_deref()
333 }
334
335 pub(crate) fn duration(&self) -> Option<i32> {
336 self.duration
337 }
338
339 pub(crate) fn epoch(&self) -> NaiveDateTime {
340 self.epoch
341 }
342
343 pub(crate) fn show_id(&self) -> ShowId {
344 self.show_id
345 }
346 }
347
348 #[cfg(test)]
349 mod tests {
350 use crate::database::truncate_db;
351 use crate::dbqueries;
352 use crate::models::new_episode::{NewEpisodeMinimal, NewEpisodeMinimalBuilder};
353 use crate::models::*;
354 use anyhow::Result;
355 use chrono::prelude::*;
356
357 use rss::Channel;
358
359 use std::fs::File;
360 use std::io::BufReader;
361 use std::sync::LazyLock;
362
363 /// randomly chosen
364 const TEST_SHOW_ID: ShowId = ShowId(42);
365
366 // TODO: Add tests for other feeds too.
367 // Especially if you find an *interesting* generated feed.
368
369 // Known prebuilt expected objects.
370 static EXPECTED_MINIMAL_INTERCEPTED_1: LazyLock<NewEpisodeMinimal> = LazyLock::new(|| {
371 NewEpisodeMinimalBuilder::default()
372 .title("The Super Bowl of Racism")
373 .uri(Some(String::from(
374 "http://traffic.megaphone.fm/PPY6458293736.mp3",
375 )))
376 .image_uri(None)
377 .guid(Some(String::from("7df4070a-9832-11e7-adac-cb37b05d5e24")))
378 .epoch(
379 DateTime::<Utc>::from_timestamp(1505296800, 0)
380 .unwrap()
381 .naive_utc(),
382 )
383 .length(Some(66738886))
384 .duration(Some(4171))
385 .show_id(TEST_SHOW_ID)
386 .build()
387 .unwrap()
388 });
389 static EXPECTED_MINIMAL_INTERCEPTED_2: LazyLock<NewEpisodeMinimal> = LazyLock::new(|| {
390 NewEpisodeMinimalBuilder::default()
391 .title("Atlas Golfed — U.S.-Backed Think Tanks Target Latin America")
392 .uri(Some(String::from(
393 "http://traffic.megaphone.fm/FL5331443769.mp3",
394 )))
395 .image_uri(None)
396 .guid(Some(String::from("7c207a24-e33f-11e6-9438-eb45dcf36a1d")))
397 .epoch(
398 DateTime::<Utc>::from_timestamp(1502272800, 0)
399 .unwrap()
400 .naive_utc(),
401 )
402 .length(Some(67527575))
403 .duration(Some(4415))
404 .show_id(TEST_SHOW_ID)
405 .build()
406 .unwrap()
407 });
408 static EXPECTED_INTERCEPTED_1: LazyLock<NewEpisode> = LazyLock::new(|| {
409 let descr = "NSA whistleblower Edward Snowden discusses the massive Equifax data \
410 breach and allegations of Russian interference in the US election. \
411 Commentator Shaun King explains his call for a boycott of the NFL and \
412 talks about his campaign to bring violent neo-Nazis to justice. Rapper \
413 Open Mike Eagle performs.";
414
415 NewEpisodeBuilder::default()
416 .title("The Super Bowl of Racism")
417 .uri(Some(String::from(
418 "http://traffic.megaphone.fm/PPY6458293736.mp3",
419 )))
420 .image_uri(None)
421 .description(Some(String::from(descr)))
422 .guid(Some(String::from("7df4070a-9832-11e7-adac-cb37b05d5e24")))
423 .length(Some(66738886))
424 .epoch(
425 DateTime::<Utc>::from_timestamp(1505296800, 0)
426 .unwrap()
427 .naive_utc(),
428 )
429 .duration(Some(4171))
430 .show_id(TEST_SHOW_ID)
431 .build()
432 .unwrap()
433 });
434 static EXPECTED_INTERCEPTED_2: LazyLock<NewEpisode> = LazyLock::new(|| {
435 let descr = "This week on Intercepted: Jeremy gives an update on the aftermath of \
436 Blackwater’s 2007 massacre of Iraqi civilians. Intercept reporter Lee \
437 Fang lays out how a network of libertarian think tanks called the Atlas \
438 Network is insidiously shaping political infrastructure in Latin \
439 America. We speak with attorney and former Hugo Chavez adviser Eva \
440 Golinger about the Venezuela\'s political turmoil.And we hear Claudia \
441 Lizardo of the Caracas-based band, La Pequeña Revancha, talk about her \
442 music and hopes for Venezuela.";
443
444 NewEpisodeBuilder::default()
445 .title("Atlas Golfed — U.S.-Backed Think Tanks Target Latin America")
446 .uri(Some(String::from(
447 "http://traffic.megaphone.fm/FL5331443769.mp3",
448 )))
449 .image_uri(None)
450 .description(Some(String::from(descr)))
451 .guid(Some(String::from("7c207a24-e33f-11e6-9438-eb45dcf36a1d")))
452 .length(Some(67527575))
453 .epoch(
454 DateTime::<Utc>::from_timestamp(1502272800, 0)
455 .unwrap()
456 .naive_utc(),
457 )
458 .duration(Some(4415))
459 .show_id(TEST_SHOW_ID)
460 .build()
461 .unwrap()
462 });
463 static UPDATED_DURATION_INTERCEPTED_1: LazyLock<NewEpisode> = LazyLock::new(|| {
464 NewEpisodeBuilder::default()
465 .title("The Super Bowl of Racism")
466 .uri(Some(String::from(
467 "http://traffic.megaphone.fm/PPY6458293736.mp3",
468 )))
469 .image_uri(None)
470 .description(Some(String::from("New description")))
471 .guid(Some(String::from("7df4070a-9832-11e7-adac-cb37b05d5e24")))
472 .length(Some(66738886))
473 .epoch(
474 DateTime::<Utc>::from_timestamp(1505296800, 0)
475 .unwrap()
476 .naive_utc(),
477 )
478 .duration(Some(424242))
479 .show_id(TEST_SHOW_ID)
480 .build()
481 .unwrap()
482 });
483 static EXPECTED_MINIMAL_LUP_1: LazyLock<NewEpisodeMinimal> = LazyLock::new(|| {
484 NewEpisodeMinimalBuilder::default()
485 .title("Hacking Devices with Kali Linux | LUP 214")
486 .uri(Some(String::from(
487 "http://www.podtrac.com/pts/redirect.mp3/traffic.libsyn.com/jnite/lup-0214.mp3",
488 )))
489 .image_uri(None)
490 .guid(Some(String::from("78A682B4-73E8-47B8-88C0-1BE62DD4EF9D")))
491 .length(Some(46479789))
492 .epoch(
493 DateTime::<Utc>::from_timestamp(1505280282, 0)
494 .unwrap()
495 .naive_utc(),
496 )
497 .duration(Some(5733))
498 .show_id(TEST_SHOW_ID)
499 .build()
500 .unwrap()
501 });
502 static EXPECTED_MINIMAL_LUP_2: LazyLock<NewEpisodeMinimal> = LazyLock::new(|| {
503 NewEpisodeMinimalBuilder::default()
504 .title("Gnome Does it Again | LUP 213")
505 .uri(Some(String::from(
506 "http://www.podtrac.com/pts/redirect.mp3/traffic.libsyn.com/jnite/lup-0213.mp3",
507 )))
508 .image_uri(None)
509 .guid(Some(String::from("1CE57548-B36C-4F14-832A-5D5E0A24E35B")))
510 .epoch(
511 DateTime::<Utc>::from_timestamp(1504670247, 0)
512 .unwrap()
513 .naive_utc(),
514 )
515 .length(Some(36544272))
516 .duration(Some(4491))
517 .show_id(TEST_SHOW_ID)
518 .build()
519 .unwrap()
520 });
521 static EXPECTED_LUP_1: LazyLock<NewEpisode> = LazyLock::new(|| {
522 let descr = "Audit your network with a couple of easy commands on Kali Linux. Chris \
523 decides to blow off a little steam by attacking his IoT devices, Wes has \
524 the scope on Equifax blaming open source &amp; the Beard just saved the \
525 show. It’s a really packed episode!";
526
527 NewEpisodeBuilder::default()
528 .title("Hacking Devices with Kali Linux | LUP 214")
529 .uri(Some(String::from(
530 "http://www.podtrac.com/pts/redirect.mp3/traffic.libsyn.com/jnite/lup-0214.mp3",
531 )))
532 .image_uri(None)
533 .description(Some(String::from(descr)))
534 .guid(Some(String::from("78A682B4-73E8-47B8-88C0-1BE62DD4EF9D")))
535 .length(Some(46479789))
536 .epoch(
537 DateTime::<Utc>::from_timestamp(1505280282, 0)
538 .unwrap()
539 .naive_utc(),
540 )
541 .duration(Some(5733))
542 .show_id(TEST_SHOW_ID)
543 .build()
544 .unwrap()
545 });
546 static EXPECTED_LUP_2: LazyLock<NewEpisode> = LazyLock::new(|| {
547 let descr = "<p>The Gnome project is about to solve one of our audience's biggest Wayland’s \
548 concerns. But as the project takes on a new level of relevance, decisions for \
549 the next version of Gnome have us worried about the future.</p>\n\n<p>Plus we \
550 chat with Wimpy about the Ubuntu Rally in NYC, Microsoft’s sneaky move to turn \
551 Windows 10 into the “ULTIMATE LINUX RUNTIME”, community news &amp; more!</p>";
552
553 NewEpisodeBuilder::default()
554 .title("Gnome Does it Again | LUP 213")
555 .uri(Some(String::from(
556 "http://www.podtrac.com/pts/redirect.mp3/traffic.libsyn.com/jnite/lup-0213.mp3",
557 )))
558 .image_uri(None)
559 .description(Some(String::from(descr)))
560 .guid(Some(String::from("1CE57548-B36C-4F14-832A-5D5E0A24E35B")))
561 .length(Some(36544272))
562 .epoch(
563 DateTime::<Utc>::from_timestamp(1504670247, 0)
564 .unwrap()
565 .naive_utc(),
566 )
567 .duration(Some(4491))
568 .show_id(TEST_SHOW_ID)
569 .build()
570 .unwrap()
571 });
572
573 static EXPECTED_NDR_1: LazyLock<NewEpisode> = LazyLock::new(|| {
574 let descr = "<p>Die aktuellen Meldungen aus der NDR Info Nachrichtenredaktion.</p>";
575
576 NewEpisodeBuilder::default()
577 .title("Nachrichten")
578 .uri(Some(String::from(
579 "https://mediandr-a.akamaihd.net/download/podcasts/podcast4450/AU-20240313-2303-4300.mp3",
580 )))
581 .description(Some(String::from(descr)))
582 .guid(Some(String::from("AU-20240313-2303-4300-A")))
583 .length(None)
584 .epoch(DateTime::<Utc>::from_timestamp(1710367140, 0).unwrap().naive_utc())
585 .duration(Some(202))
586 .show_id(TEST_SHOW_ID)
587 .image_uri(Some("https://www.ndr.de/nachrichten/info/nachrichten660_v-quadratl.jpg".to_string()))
588 .build()
589 .unwrap()
590 });
591
592 static EXPECTED_NDR_2: LazyLock<NewEpisode> = LazyLock::new(|| {
593 let descr = "<p>Die aktuellen Meldungen aus der NDR Info Nachrichtenredaktion.</p>";
594
595 NewEpisodeBuilder::default()
596 .title("Nachrichten")
597 .uri(Some(String::from(
598 "https://mediandr-a.akamaihd.net/download/podcasts/podcast4450/AU-20240314-1705-4100.mp3",
599 )))
600 .description(Some(String::from(descr)))
601 .guid(Some(String::from("AU-20240314-1705-4100-A")))
602 .length(None)
603 .epoch(DateTime::<Utc>::from_timestamp(1710431940, 0).unwrap().naive_utc())
604 .duration(Some(300))
605 .show_id(TEST_SHOW_ID)
606 .image_uri(Some("https://www.ndr.de/nachrichten/info/nachrichten660_v-quadratl.jpg".to_string()))
607 .build()
608 .unwrap()
609 });
610
611 static EXPECTED_NDR_3: LazyLock<NewEpisode> = LazyLock::new(|| {
612 let descr = "<p>Die aktuellen Meldungen aus der NDR Info Nachrichtenredaktion.</p>";
613
614 NewEpisodeBuilder::default()
615 .title("TITLE_UPDATED")
616 .uri(Some(String::from(
617 "https://mediandr-a.akamaihd.net/download/podcasts/podcast4450/AU-20240314-1705-4100.mp3",
618 )))
619 .description(Some(String::from(descr)))
620 .guid(Some(String::from("AU-20240314-1705-4100-A")))
621 .length(None)
622 .epoch(DateTime::<Utc>::from_timestamp(2000000000, 0).unwrap().naive_utc())
623 .duration(Some(300))
624 .show_id(TEST_SHOW_ID)
625 .image_uri(Some("https://www.ndr.de/nachrichten/info/nachrichten660_v-quadratl.jpg".to_string()))
626 .build()
627 .unwrap()
628 });
629
•630 /* Disable tests that needs XML feed
631 #[test]
632 fn test_new_episode_minimal_intercepted() -> Result<()> {
633 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
634 let channel = Channel::read_from(BufReader::new(file))?;
635
636 let episode = channel.items().iter().nth(14).unwrap();
637 let ep = NewEpisodeMinimal::new(episode, TEST_SHOW_ID)?;
638 assert_eq!(ep, *EXPECTED_MINIMAL_INTERCEPTED_1);
639
640 let episode = channel.items().iter().nth(15).unwrap();
641 let ep = NewEpisodeMinimal::new(episode, TEST_SHOW_ID)?;
642 assert_eq!(ep, *EXPECTED_MINIMAL_INTERCEPTED_2);
643 Ok(())
644 }
645
646 #[test]
647 fn test_new_episode_intercepted() -> Result<()> {
648 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
649 let channel = Channel::read_from(BufReader::new(file))?;
650
651 let episode = channel.items().iter().nth(14).unwrap();
652 let ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
653 assert_eq!(ep, *EXPECTED_INTERCEPTED_1);
654
655 let episode = channel.items().iter().nth(15).unwrap();
656 let ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
657
658 assert_eq!(ep, *EXPECTED_INTERCEPTED_2);
659 Ok(())
660 }
661
662 #[test]
663 fn test_new_episode_minimal_lup() -> Result<()> {
664 let file = File::open("tests/feeds/2018-01-20-LinuxUnplugged.xml")?;
665 let channel = Channel::read_from(BufReader::new(file))?;
666
667 let episode = channel.items().iter().nth(18).unwrap();
668 let ep = NewEpisodeMinimal::new(episode, TEST_SHOW_ID)?;
669 assert_eq!(ep, *EXPECTED_MINIMAL_LUP_1);
670
671 let episode = channel.items().iter().nth(19).unwrap();
672 let ep = NewEpisodeMinimal::new(episode, TEST_SHOW_ID)?;
673 assert_eq!(ep, *EXPECTED_MINIMAL_LUP_2);
674 Ok(())
675 }
676
677 #[test]
678 fn test_new_episode_lup() -> Result<()> {
679 let file = File::open("tests/feeds/2018-01-20-LinuxUnplugged.xml")?;
680 let channel = Channel::read_from(BufReader::new(file))?;
681
682 let episode = channel.items().iter().nth(18).unwrap();
683 let ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
684 assert_eq!(ep, *EXPECTED_LUP_1);
685
686 let episode = channel.items().iter().nth(19).unwrap();
687 let ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
688 assert_eq!(ep, *EXPECTED_LUP_2);
689 Ok(())
690 }
691
692 #[test]
693 fn test_minimal_into_new_episode() -> Result<()> {
694 truncate_db()?;
695
696 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
697 let channel = Channel::read_from(BufReader::new(file))?;
698
699 let item = channel.items().iter().nth(14).unwrap();
700 let ep = EXPECTED_MINIMAL_INTERCEPTED_1
701 .clone()
702 .into_new_episode(item);
703 assert_eq!(ep, *EXPECTED_INTERCEPTED_1);
704
705 let item = channel.items().iter().nth(15).unwrap();
706 let ep = EXPECTED_MINIMAL_INTERCEPTED_2
707 .clone()
708 .into_new_episode(item);
709 assert_eq!(ep, *EXPECTED_INTERCEPTED_2);
710 Ok(())
711 }
712
713 #[test]
714 fn test_new_episode_insert() -> Result<()> {
715 truncate_db()?;
716
717 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
718 let channel = Channel::read_from(BufReader::new(file))?;
719
720 let episode = channel.items().iter().nth(14).unwrap();
721 let new_ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
722 new_ep.index()?;
723 let ep = dbqueries::get_episode(new_ep.guid(), new_ep.title(), new_ep.show_id())?;
724
725 assert_eq!(new_ep, ep);
726 assert_eq!(&new_ep, &*EXPECTED_INTERCEPTED_1);
727 assert_eq!(&*EXPECTED_INTERCEPTED_1, &ep);
728
729 let episode = channel.items().iter().nth(15).unwrap();
730 let new_ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
731 new_ep.index()?;
732 let ep = dbqueries::get_episode(new_ep.guid(), new_ep.title(), new_ep.show_id())?;
733
734 assert_eq!(new_ep, ep);
735 assert_eq!(&new_ep, &*EXPECTED_INTERCEPTED_2);
736 assert_eq!(&*EXPECTED_INTERCEPTED_2, &ep);
737 Ok(())
738 }
•739 */
740
741 #[test]
742 fn test_new_episode_update() -> Result<()> {
743 truncate_db()?;
744 let old = EXPECTED_INTERCEPTED_1.clone().to_episode()?;
745
746 let updated = &*UPDATED_DURATION_INTERCEPTED_1;
747 updated.update(old.id())?;
748 let new = dbqueries::get_episode(old.guid(), old.title(), old.show_id())?;
749
750 // Assert that updating does not change the id and show_id
751 assert_ne!(old, new);
752 assert_eq!(old.id(), new.id());
753 assert_eq!(old.show_id(), new.show_id());
754
755 assert_eq!(updated, &new);
756 assert_ne!(updated, &old);
757 Ok(())
758 }
759
760 #[test]
761 fn test_new_episode_index() -> Result<()> {
762 truncate_db()?;
763 let expected = &*EXPECTED_INTERCEPTED_1;
764
765 // First insert
766 assert!(expected.index().is_ok());
767 // Second identical, This should take the early return path
768 assert!(expected.index().is_ok());
769 // Get the episode
770 let old = dbqueries::get_episode(expected.guid(), expected.title(), expected.show_id())?;
771 // Assert that NewPodcast is equal to the Indexed one
772 assert_eq!(*expected, old);
773
774 let updated = &*UPDATED_DURATION_INTERCEPTED_1;
775
776 // Update the podcast
777 assert!(updated.index().is_ok());
778 // Get the new Podcast
779 let new = dbqueries::get_episode(expected.guid(), expected.title(), expected.show_id())?;
780 // Assert it's diff from the old one.
781 assert_ne!(new, old);
782 assert_eq!(*updated, new);
783 assert_eq!(new.id(), old.id());
784 assert_eq!(new.show_id(), old.show_id());
785 Ok(())
786 }
787
788 #[test]
789 fn test_new_episode_to_episode() -> Result<()> {
790 let expected = &*EXPECTED_INTERCEPTED_1;
791
792 // Assert insert() produces the same result that you would get with to_podcast()
793 truncate_db()?;
794 expected.index()?;
795 let old = dbqueries::get_episode(expected.guid(), expected.title(), expected.show_id())?;
796 let ep = expected.to_episode()?;
797 assert_eq!(old, ep);
798
799 // Same as above, diff order
800 truncate_db()?;
801 let ep = expected.to_episode()?;
802
803 // did not make a new insert, updated
804 expected.index()?;
805 assert_eq!(dbqueries::get_episodes()?.len(), 1);
806
807 let old = dbqueries::get_episode(expected.guid(), expected.title(), expected.show_id())?;
808 assert_eq!(old, ep);
809 Ok(())
810 }
811
•812
813 /* Disable tests that need xml feeds
814 // https://gitlab.gnome.org/World/podcasts/-/issues/216
815 // new episode is imported, always same title, different guid
816 #[test]
817 fn test_feed_ndr() -> Result<()> {
818 truncate_db()?;
819
820 let file = File::open("tests/feeds/2024-03-13-ndr.xml")?;
821 let channel = Channel::read_from(BufReader::new(file))?;
822
823 let episode = channel.items().iter().nth(1).unwrap();
824 let new_ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
825 new_ep.index()?;
826 let ep = dbqueries::get_episode(new_ep.guid(), new_ep.title(), new_ep.show_id())?;
827
828 assert_eq!(new_ep, ep);
829 assert_eq!(&new_ep, &*EXPECTED_NDR_1);
830 assert_eq!(&*EXPECTED_NDR_1, &ep);
831
832 let file = File::open("tests/feeds/2024-03-14-ndr.xml")?;
833 let channel = Channel::read_from(BufReader::new(file))?;
834
835 let episode = channel.items().iter().nth(1).unwrap();
836 let new_ep = NewEpisode::new(episode, TEST_SHOW_ID)?;
837 new_ep.index()?;
838 let ep = dbqueries::get_episode(new_ep.guid(), new_ep.title(), new_ep.show_id())?;
839
840 assert_eq!(new_ep, ep);
841 assert_eq!(&new_ep, &*EXPECTED_NDR_2);
842 assert_eq!(&*EXPECTED_NDR_2, &ep);
843
844 let all_eps = dbqueries::get_episodes()?;
845 assert_eq!(2, all_eps.len());
846
847 // update one of the ep's title and epoch
848 let new_ep = &*EXPECTED_NDR_3;
849 new_ep.index()?;
850
851 // https://gitlab.gnome.org/World/podcasts/-/issues/151
852 // Title update
853 let ep = dbqueries::get_episode(new_ep.guid(), new_ep.title(), new_ep.show_id())?;
854 assert_eq!(new_ep, &ep);
855 assert_eq!(new_ep, &*EXPECTED_NDR_3);
856 assert_eq!(&*EXPECTED_NDR_3, &ep);
857 assert_eq!(
858 DateTime::<Utc>::from_timestamp(2000000000, 0)
859 .unwrap()
860 .naive_utc(),
861 ep.epoch()
862 );
863 assert_eq!("TITLE_UPDATED", ep.title());
864
865 let all_eps = dbqueries::get_episodes()?;
866 assert_eq!(2, all_eps.len());
867
868 Ok(())
869 }
•870 */
871 }