Debian Codegraph @

podcasts-data/src/models/new_show.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // new_show.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 diesel::prelude::*;
21
22 use crate::errors::DataError;
23 use crate::models::{Index, Insert, Update};
24 use crate::models::{Show, ShowId, SourceId};
25 use crate::schema::shows;
26
27 use crate::database::connection;
28 use crate::dbqueries;
29 use crate::utils::{calculate_hash, u64_to_vec_u8, url_cleaner};
30
31 #[cfg(test)]
32 use crate::utils::vec_u8_to_u64;
33
34 use chrono::{NaiveDateTime, Utc};
35
36 #[derive(Insertable, AsChangeset)]
37 #[diesel(table_name = shows)]
38 #[derive(Debug, Clone, Default, Builder)]
39 #[builder(default)]
40 #[builder(derive(Debug))]
41 #[builder(setter(into))]
42 pub(crate) struct NewShow {
43 title: String,
44 link: String,
45 description: String,
46 image_uri: Option<String>,
47 image_uri_hash: Option<Vec<u8>>,
48 image_cached: Option<NaiveDateTime>,
49 source_id: SourceId,
50 }
51
52 impl Insert<()> for NewShow {
53 type Error = DataError;
54
55 fn insert(&self) -> Result<(), Self::Error> {
56 use crate::schema::shows::dsl::*;
57 let db = connection();
58 let mut con = db.get()?;
59
60 diesel::insert_into(shows)
61 .values(self)
62 .execute(&mut con)
63 .map(|_| ())
64 .map_err(From::from)
65 }
66 }
67
68 impl Update<(), ShowId> for NewShow {
69 type Error = DataError;
70
71 fn update(&self, show_id: ShowId) -> Result<(), Self::Error> {
72 use crate::schema::shows::dsl::*;
73 let db = connection();
74 let mut con = db.get()?;
75
76 info!("Updating {}", self.title);
77 diesel::update(shows.filter(id.eq(show_id)))
78 .set(self)
79 .execute(&mut con)
80 .map(|_| ())
81 .map_err(From::from)
82 }
83 }
84
85 // TODO: Maybe return an Enum<Action(Resut)> Instead.
86 // It would make unti testing better too.
87 impl Index<(), ShowId> for NewShow {
88 type Error = DataError;
89
90 fn index(&self) -> Result<(), DataError> {
91 let exists = dbqueries::podcast_exists(self.source_id)?;
92
93 if exists {
94 let other = dbqueries::get_podcast_from_source_id(self.source_id)?;
95
96 if self != &other {
97 self.update(other.id())
98 } else {
99 Ok(())
100 }
101 } else {
102 self.insert()
103 }
104 }
105 }
106
107 impl PartialEq<NewShow> for NewShow {
108 fn eq(&self, other: &NewShow) -> bool {
109 (self.link() == other.link())
110 && (self.title() == other.title())
111 && (self.image_uri() == other.image_uri())
112 && (self.description() == other.description())
113 && (self.source_id() == other.source_id())
114 }
115 }
116
117 impl PartialEq<Show> for NewShow {
118 fn eq(&self, other: &Show) -> bool {
119 (self.link() == other.link())
120 && (self.title() == other.title())
121 && (self.image_uri() == other.image_uri())
122 && (self.description() == other.description())
123 && (self.source_id() == other.source_id())
124 }
125 }
126
127 impl NewShow {
128 /// Parses a `rss::Channel` into a `NewShow` Struct.
129 pub(crate) fn new(chan: &rss::Channel, source_id: SourceId) -> NewShow {
130 let title = chan.title().trim();
131 let link = url_cleaner(chan.link().trim());
132
133 let description = ammonia::Builder::new()
134 // Remove `rel` attributes from `<a>` tags
135 .link_rel(None)
136 .clean(chan.description().trim())
137 .to_string();
138
139 // Try to get the itunes img first
140 let itunes_img = chan
141 .itunes_ext()
142 .and_then(|s| s.image().map(|url| url.trim()))
143 .map(|s| s.to_owned());
144 // If itunes is None, try to get the channel.image from the rss spec
145 let image_uri = itunes_img.or_else(|| chan.image().map(|s| s.url().trim().to_owned()));
146
147 let mut hash: Option<Vec<u8>> = None;
148 if let Some(i) = &image_uri {
149 hash = Some(u64_to_vec_u8(calculate_hash(i)));
150 }
151
152 NewShowBuilder::default()
153 .title(title)
154 .description(description)
155 .link(link)
156 .image_uri(image_uri)
157 .image_uri_hash(hash)
158 .image_cached(Utc::now().naive_utc())
159 .source_id(source_id)
160 .build()
161 .unwrap()
162 }
163
164 // Look out for when tryinto lands into stable.
165 pub(crate) fn to_podcast(&self) -> Result<Show, DataError> {
166 self.index()?;
167 dbqueries::get_podcast_from_source_id(self.source_id)
168 }
169 }
170
171 // Ignore the following geters. They are used in unit tests mainly.
172 impl NewShow {
173 pub(crate) fn source_id(&self) -> SourceId {
174 self.source_id
175 }
176
177 pub(crate) fn title(&self) -> &str {
178 &self.title
179 }
180
181 pub(crate) fn link(&self) -> &str {
182 &self.link
183 }
184
185 pub(crate) fn description(&self) -> &str {
186 &self.description
187 }
188
189 pub(crate) fn image_uri(&self) -> Option<&str> {
190 self.image_uri.as_deref()
191 }
192
193 #[cfg(test)]
194 pub fn image_uri_hash(&self) -> Option<u64> {
195 if let Some(b) = &self.image_uri_hash {
196 return Some(vec_u8_to_u64(b.clone()));
197 }
198 None
199 }
200
201 #[cfg(test)]
202 pub(crate) fn image_cached(&self) -> Option<NaiveDateTime> {
203 self.image_cached
204 }
205 }
206
207 #[cfg(test)]
208 mod tests {
209 use super::*;
210
211 use anyhow::Result;
212 use rss::Channel;
213
214 use crate::database::truncate_db;
215 use crate::models::NewShowBuilder;
216
217 use std::fs::File;
218 use std::io::BufReader;
219 use std::sync::LazyLock;
220
221 const TEST_SOURCE_ID: SourceId = SourceId(42);
222
223 // Pre-built expected NewShow structs.
224 static EXPECTED_INTERCEPTED: LazyLock<NewShow> = LazyLock::new(|| {
225 let descr = "The people behind The Intercept’s fearless reporting and incisive \
226 commentary—Jeremy Scahill, Glenn Greenwald, Betsy Reed and \
227 others—discuss the crucial issues of our time: national security, civil \
228 liberties, foreign policy, and criminal justice. Plus interviews with \
229 artists, thinkers, and newsmakers who challenge our preconceptions about \
230 the world we live in.";
231
232 NewShowBuilder::default()
233 .title("Intercepted with Jeremy Scahill")
234 .link("https://theintercept.com/podcasts")
235 .description(descr)
236 .image_uri(Some(String::from(
237 "http://static.megaphone.fm/podcasts/d5735a50-d904-11e6-8532-73c7de466ea6/image/\
238 uploads_2F1484252190700-qhn5krasklbce3dh-a797539282700ea0298a3a26f7e49b0b_\
239 2FIntercepted_COVER%2B_281_29.png",
240 )))
241 .source_id(TEST_SOURCE_ID)
242 .build()
243 .unwrap()
244 });
245 static EXPECTED_LUP: LazyLock<NewShow> = LazyLock::new(|| {
246 let descr = "An open show powered by community LINUX Unplugged takes the best \
247 attributes of open collaboration and focuses them into a weekly \
248 lifestyle show about Linux.";
249
250 NewShowBuilder::default()
251 .title("LINUX Unplugged Podcast")
252 .link("http://www.jupiterbroadcasting.com/")
253 .description(descr)
254 .image_uri(Some(String::from(
255 "http://www.jupiterbroadcasting.com/images/LASUN-Badge1400.jpg",
256 )))
257 .source_id(TEST_SOURCE_ID)
258 .build()
259 .unwrap()
260 });
261 static EXPECTED_TIPOFF: LazyLock<NewShow> = LazyLock::new(|| {
262 let desc = "<p>Welcome to The Tip Off- the podcast where we take you behind the \
263 scenes of some of the best investigative journalism from recent years. \
264 Each episode we’ll be digging into an investigative scoop- hearing from \
265 the journalists behind the work as they tell us about the leads, the \
266 dead-ends and of course, the tip offs. There’ll be car chases, slammed \
267 doors, terrorist cells, meetings in dimly lit bars and cafes, wrangling \
268 with despotic regimes and much more. So if you’re curious about the fun, \
269 complicated detective work that goes into doing great investigative \
270 journalism- then this is the podcast for you.</p>";
271
272 NewShowBuilder::default()
273 .title("The Tip Off")
274 .link("http://www.acast.com/thetipoff")
275 .description(desc)
276 .image_uri(Some(String::from(
277 "https://imagecdn.acast.com/image?h=1500&w=1500&source=http%3A%2F%2Fi1.sndcdn.\
278 com%2Favatars-000317856075-a2coqz-original.jpg",
279 )))
280 .source_id(TEST_SOURCE_ID)
281 .build()
282 .unwrap()
283 });
284 static EXPECTED_STARS: LazyLock<NewShow> = LazyLock::new(|| {
285 let descr = "<p>The first audio drama from Tor Labs and Gideon Media, Steal the Stars \
286 is a gripping noir science fiction thriller in 14 episodes: Forbidden \
287 love, a crashed UFO, an alien body, and an impossible heist unlike any \
288 ever attempted - scripted by Mac Rogers, the award-winning playwright \
289 and writer of the multi-million download The Message and LifeAfter.</p>";
290 let img = "https://dfkfj8j276wwv.cloudfront.net/images/2c/5f/a0/1a/2c5fa01a-ae78-4a8c-\
291 b183-7311d2e436c3/b3a4aa57a576bb662191f2a6bc2a436c8c4ae256ecffaff5c4c54fd42e\
292 923914941c264d01efb1833234b52c9530e67d28a8cebbe3d11a4bc0fbbdf13ecdf1c3.jpeg";
293
294 NewShowBuilder::default()
295 .title("Steal the Stars")
296 .link("http://tor-labs.com/")
297 .description(descr)
298 .image_uri(Some(String::from(img)))
299 .source_id(TEST_SOURCE_ID)
300 .build()
301 .unwrap()
302 });
303 static EXPECTED_CODE: LazyLock<NewShow> = LazyLock::new(|| {
304 let descr = "A podcast about humans and technology. Panelists: Coraline Ada Ehmke, \
305 David Brady, Jessica Kerr, Jay Bobo, Astrid Countee and Sam \
306 Livingston-Gray. Brought to you by @therubyrep.";
307
308 NewShowBuilder::default()
309 .title("Greater Than Code")
310 .link("https://www.greaterthancode.com/")
311 .description(descr)
312 .image_uri(Some(String::from(
313 "http://www.greaterthancode.com/wp-content/uploads/2016/10/code1400-4.jpg",
314 )))
315 .source_id(TEST_SOURCE_ID)
316 .build()
317 .unwrap()
318 });
319 static EXPECTED_ELLINOFRENEIA: LazyLock<NewShow> = LazyLock::new(|| {
320 NewShowBuilder::default()
321 .title("Ελληνοφρένεια")
322 .link("https://ellinofreneia.sealabs.net/feed.rss")
323 .description("Ανεπίσημο feed της Ελληνοφρένειας")
324 .image_uri(Some("https://ellinofreneia.sealabs.net/logo.png".into()))
325 .source_id(TEST_SOURCE_ID)
326 .build()
327 .unwrap()
328 });
329 static UPDATED_DESC_INTERCEPTED: LazyLock<NewShow> = LazyLock::new(|| {
330 NewShowBuilder::default()
331 .title("Intercepted with Jeremy Scahill")
332 .link("https://theintercept.com/podcasts")
333 .description("New Description")
334 .image_uri(Some(String::from(
335 "http://static.megaphone.fm/podcasts/d5735a50-d904-11e6-8532-73c7de466ea6/image/\
336 uploads_2F1484252190700-qhn5krasklbce3dh-a797539282700ea0298a3a26f7e49b0b_\
337 2FIntercepted_COVER%2B_281_29.png",
338 )))
339 .source_id(TEST_SOURCE_ID)
340 .build()
341 .unwrap()
342 });
343
•344
345 /* Disable tests that needs XML feed
346 #[test]
347 fn test_new_podcast_intercepted() -> Result<()> {
348 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
349 let channel = Channel::read_from(BufReader::new(file))?;
350
351 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
352 assert_eq!(*EXPECTED_INTERCEPTED, pd);
353 Ok(())
354 }
355
356 #[test]
357 fn test_new_podcast_lup() -> Result<()> {
358 let file = File::open("tests/feeds/2018-01-20-LinuxUnplugged.xml")?;
359 let channel = Channel::read_from(BufReader::new(file))?;
360
361 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
362 assert_eq!(*EXPECTED_LUP, pd);
363 Ok(())
364 }
365
366 #[test]
367 fn test_new_podcast_thetipoff() -> Result<()> {
368 let file = File::open("tests/feeds/2018-01-20-TheTipOff.xml")?;
369 let channel = Channel::read_from(BufReader::new(file))?;
370
371 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
372 assert_eq!(*EXPECTED_TIPOFF, pd);
373 Ok(())
374 }
375
376 #[test]
377 fn test_new_podcast_steal_the_stars() -> Result<()> {
378 let file = File::open("tests/feeds/2018-01-20-StealTheStars.xml")?;
379 let channel = Channel::read_from(BufReader::new(file))?;
380
381 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
382 assert_eq!(*EXPECTED_STARS, pd);
383 Ok(())
384 }
385
386 #[test]
387 fn test_new_podcast_greater_than_code() -> Result<()> {
388 let file = File::open("tests/feeds/2018-01-20-GreaterThanCode.xml")?;
389 let channel = Channel::read_from(BufReader::new(file))?;
390
391 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
392 assert_eq!(*EXPECTED_CODE, pd);
393 Ok(())
394 }
395
396 #[test]
397 fn test_new_podcast_ellinofreneia() -> Result<()> {
398 let file = File::open("tests/feeds/2018-03-28-Ellinofreneia.xml")?;
399 let channel = Channel::read_from(BufReader::new(file))?;
400
401 let pd = NewShow::new(&channel, TEST_SOURCE_ID);
402 assert_eq!(*EXPECTED_ELLINOFRENEIA, pd);
403 Ok(())
404 }
405
406 #[test]
407 // This maybe could be a doc test on insert.
408 fn test_new_podcast_insert() -> Result<()> {
409 truncate_db()?;
410 let file = File::open("tests/feeds/2018-01-20-Intercepted.xml")?;
411 let channel = Channel::read_from(BufReader::new(file))?;
412
413 let npd = NewShow::new(&channel, TEST_SOURCE_ID);
414 npd.insert()?;
415 let pd = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
416
417 assert_eq!(npd, pd);
418 assert_eq!(*EXPECTED_INTERCEPTED, npd);
419 assert_eq!(&*EXPECTED_INTERCEPTED, &pd);
420 Ok(())
421 }
•422 */
423
424 #[test]
425 // TODO: Add more test/checks
426 // Currently there's a test that only checks new description or title.
427 // If you have time and want to help, implement the test for the other fields
428 // too.
429 fn test_new_podcast_update() -> Result<()> {
430 truncate_db()?;
431 let old = EXPECTED_INTERCEPTED.to_podcast()?;
432
433 let updated = &*UPDATED_DESC_INTERCEPTED;
434 updated.update(old.id())?;
435 let new = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
436
437 assert_ne!(old, new);
438 assert_eq!(old.id(), new.id());
439 assert_eq!(old.source_id(), new.source_id());
440 assert_eq!(updated, &new);
441 assert_ne!(updated, &old);
442 Ok(())
443 }
444
445 #[test]
446 fn test_new_podcast_index() -> Result<()> {
447 truncate_db()?;
448
449 // First insert
450 assert!(EXPECTED_INTERCEPTED.index().is_ok());
451 // Second identical, This should take the early return path
452 assert!(EXPECTED_INTERCEPTED.index().is_ok());
453 // Get the podcast
454 let old = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
455 // Assert that NewShow is equal to the Indexed one
456 assert_eq!(&*EXPECTED_INTERCEPTED, &old);
457
458 let updated = &*UPDATED_DESC_INTERCEPTED;
459
460 // Update the podcast
461 assert!(updated.index().is_ok());
462 // Get the new Show
463 let new = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
464 // Assert it's diff from the old one.
465 assert_ne!(new, old);
466 assert_eq!(new.id(), old.id());
467 assert_eq!(new.source_id(), old.source_id());
468 Ok(())
469 }
470
471 #[test]
472 fn test_to_podcast() -> Result<()> {
473 // Assert insert() produces the same result that you would get with to_podcast()
474 truncate_db()?;
475 EXPECTED_INTERCEPTED.insert()?;
476 let old = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
477 let pd = EXPECTED_INTERCEPTED.to_podcast()?;
478 assert_eq!(old, pd);
479
480 // Same as above, diff order
481 truncate_db()?;
482 let pd = EXPECTED_INTERCEPTED.to_podcast()?;
483 // This should error as a unique constrain violation
484 assert!(EXPECTED_INTERCEPTED.insert().is_err());
485 let old = dbqueries::get_podcast_from_source_id(TEST_SOURCE_ID)?;
486 assert_eq!(old, pd);
487 Ok(())
488 }
489 }