Debian Codegraph @

podcasts-gtk/src/utils.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // utils.rs
2 //
3 // Copyright 2018 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 anyhow::{Context, Result, anyhow, bail};
21 use async_channel::Sender;
22 use async_channel::unbounded;
23 use chrono::prelude::*;
24 use futures_util::StreamExt;
25 use glib::clone;
26 use glib::object::WeakRef;
27 use gtk::FileFilter;
28 use gtk::Widget;
29 use gtk::prelude::*;
30 use gtk::{gio, glib};
31 use regex::Regex;
32 use serde_json::Value;
33 use std::collections::HashSet;
34 use std::sync::{Arc, LazyLock, Mutex};
35 use std::time::{Duration, Instant};
36 use url::Url;
37
38 use crate::app::Action;
39 use crate::feed_manager::FEED_MANAGER;
40 use crate::i18n::{i18n, i18n_f};
41 use podcasts_data::dbqueries;
42 use podcasts_data::downloader::client_builder;
43 use podcasts_data::opml;
44 use podcasts_data::utils::checkup;
45 use podcasts_data::{ShowId, Source};
46
47 /// Copied from the gtk-macros crate
48 ///
49 /// Send an event through a async_channel::Sender
50 ///
51 /// - Before:
52 ///
53 /// Example:
54 ///
55 /// ```no_run
56 /// sender.send(Action::DoThing).expect("Failed to send DoThing through the glib channel?");
57 /// ```
58 ///
59 /// - After:
60 ///
61 /// Example:
62 ///
63 /// ```no_run
64 /// send!(self.sender, Action::DoThing);
65 /// ```
66 #[macro_export]
67 macro_rules! send {
68 ($sender:expr, $action:expr) => {
69 if let Err(err) = $sender.send($action).await {
70 panic!(
71 "Failed to send \"{}\" action due to {}",
72 stringify!($action),
73 err
74 );
75 }
76 };
77 }
78
79 /// Same as send! but not async.
80 /// Should not be used from async functions.
81 #[macro_export]
82 macro_rules! send_blocking {
83 ($sender:expr, $action:expr) => {
84 if let Err(err) = $sender.send_blocking($action) {
85 panic!(
86 "Failed to send \"{}\" action due to {}",
87 stringify!($action),
88 err
89 );
90 }
91 };
92 }
93
94 /// Lazy evaluates and loads widgets to the parent `container` widget.
95 ///
96 /// Accepts an `IntoIterator`, `data`, as the source from which each widget
97 /// will be constructed. An `FnMut` function that returns the desired
98 /// widget should be passed as the widget `constructor`. You can also specify
99 /// a `callback` that will be executed when the iteration finish.
100 ///
101 /// ```no_run
102 /// # struct Message;
103 /// # struct MessageWidget(gtk::Label);
104 ///
105 /// # impl MessageWidget {
106 /// # fn new(_: Message) -> Self {
107 /// # MessageWidget(gtk::Label::new("A message"))
108 /// # }
109 /// # }
110 ///
111 /// let messages: Vec<Message> = Vec::new();
112 /// let list = gtk::ListBox::new();
113 /// let constructor = |m| MessageWidget::new(m).0;
114 /// lazy_load(messages, list, constructor, || {});
115 /// ```
116 ///
117 /// If you have already constructed the widgets and only want to
118 /// load them to the parent you can pass a closure that returns it's
119 /// own argument to the constructor.
120 ///
121 /// ```no_run
122 /// # use std::collections::binary_heap::BinaryHeap;
123 /// let widgets: BinaryHeap<gtk::Button> = BinaryHeap::new();
124 /// let list = gtk::ListBox::new();
125 /// lazy_load(widgets, list, |w| w, || {});
126 /// ```
127 pub(crate) async fn lazy_load<C, W, T>(
128 data: Vec<T>,
129 container: WeakRef<W>,
130 constructor: C,
131 ) -> Vec<Result<(), glib::JoinError>>
132 where
133 T: 'static,
134 W: IsA<Widget> + Sized + 'static,
135 C: Fn(T) -> W + 'static,
136 {
137 let (sender, receiver) = unbounded::<W>();
138
139 let h1 =
140 crate::MAINCONTEXT.spawn_local_with_priority(glib::source::Priority::LOW, async move {
141 let mut total_duration = Duration::default();
142 let mut count = 0;
143
144 for item in data {
145 let start = Instant::now();
146 let widget = constructor(item);
147
148 let duration = start.elapsed();
149 trace!("Created single widget in: {:?}", duration);
150 total_duration += duration;
151 count += 1;
152
153 if let Err(err) = sender.send(widget).await {
154 debug!("Got SendError, Channel is closed: {}", err);
155 return;
156 };
157
158 tokio::task::yield_now().await;
159 }
160
161 debug!("Created {} widgets in: {:?}", count, total_duration);
162 });
163
164 let h2 = crate::MAINCONTEXT.spawn_local_with_priority(
165 glib::source::Priority::DEFAULT_IDLE,
166 async move {
167 receiver
168 .chunks(25)
169 .for_each(move |widgets| {
170 trace!("Received {} widgets", &widgets.len());
171 insert_widgets_idle(widgets, container.clone())
172 })
173 .await
174 },
175 );
176
177 futures_util::future::join_all([h1, h2]).await
178 }
179
180 async fn insert_widgets_idle<W>(data: Vec<W>, container: WeakRef<W>)
181 where
182 W: IsA<Widget> + Sized + 'static,
183 {
184 let widget_count = data.len();
185
186 let mut count = 0;
187 let mut start = Instant::now();
188
189 let mut batch_construction_time_total = Duration::default();
190
191 for widget in data {
192 let w_start = Instant::now();
193 insert_widget_dynamic(widget, &container);
194 let w_duration = w_start.elapsed();
195 trace!("Inserted single widget in: {:?}", w_duration);
196 count += 1;
197 batch_construction_time_total += w_duration;
198
199 let duration = start.elapsed();
200 if duration > Duration::from_millis(1) {
201 trace!("Inserted batch of {} widgets in: {:?}", count, duration);
202 tokio::task::yield_now().await;
203 count = 0;
204 start = Instant::now();
205 }
206 }
207
208 debug!(
209 "Inserted {} widgets in: {:?}",
210 widget_count, batch_construction_time_total
211 );
212 }
213
214 fn insert_widget_dynamic<W: IsA<Widget> + Sized>(widget: W, container: &WeakRef<W>) {
215 let container = match container.upgrade() {
216 Some(c) => c,
217 None => return,
218 };
219
220 if let Some(listbox) = container.dynamic_cast_ref::<gtk::ListBox>() {
221 listbox.append(&widget);
222 } else if let Some(flowbox) = container.dynamic_cast_ref::<gtk::FlowBox>() {
223 flowbox.append(&widget);
224 } else {
225 unreachable!("Failed to downcast widget. {}", container.value_type());
226 }
227
228 widget.set_visible(true);
229 }
230
231 static IGNORESHOWS: LazyLock<Arc<Mutex<HashSet<ShowId>>>> =
232 LazyLock::new(|| Arc::new(Mutex::new(HashSet::new())));
233
234 pub(crate) fn ignore_show(id: ShowId) -> Result<bool> {
235 IGNORESHOWS
236 .lock()
237 .map(|mut guard| guard.insert(id))
238 .map_err(|err| anyhow!("{err}"))
239 }
240
241 pub(crate) fn unignore_show(id: ShowId) -> Result<bool> {
242 IGNORESHOWS
243 .lock()
244 .map(|mut guard| guard.remove(&id))
245 .map_err(|err| anyhow!("{err}"))
246 }
247
248 pub(crate) fn get_ignored_shows() -> Result<Vec<ShowId>> {
249 IGNORESHOWS
250 .lock()
251 .map(|guard| guard.iter().cloned().collect::<Vec<_>>())
252 .map_err(|err| anyhow!("{err}"))
253 }
254
255 pub(crate) fn cleanup(cleanup_date: DateTime<Utc>) {
256 if let Err(err) = checkup(cleanup_date) {
257 error!("Check up failed: {err}");
258 }
259 }
260
261 pub(crate) async fn subscribe(sender: &Sender<Action>, feed: String) {
262 let mut error_source = None; // <- auto unsub from this
263 if let Err(e) = async {
264 let source = dbqueries::get_source_from_uri(&feed).or_else(|_| Source::from_url(&feed))?;
265 error_source = Some(source.clone());
266 let source_id = source.id();
267 info!("Subscribing to {feed}");
268 FEED_MANAGER.refresh(sender, vec![source]).await;
269 let show = dbqueries::get_podcast_from_source_id(source_id)?;
270 send!(sender, Action::RefreshAllViews);
271 send!(sender, Action::GoToShow(Arc::new(show.clone())));
272 Ok::<(), anyhow::Error>(())
273 }
274 .await
275 {
276 error!("Failed to subscribe: {feed} {e}");
277 // auto unsubscribe
278 if let Some(error_source) = error_source {
279 // only unsub if no Show was imported from the source.
280 if dbqueries::get_podcast_from_source_id(error_source.id()).is_err() {
281 if let Err(remove_err) = dbqueries::remove_source(&error_source) {
282 error!("failed to remove failed source! {remove_err} {feed}");
283 } else {
284 info!("auto removed source that failed to import {feed}");
285 }
286 }
287 }
288 // TODO show the actual error (like "content didn't start with rss feed"),
289 // but pipeline doesn't pass useful errors yet
290 send!(
291 sender,
292 Action::ErrorNotification(i18n_f(
293 "Failed to subscribe to feed: {}",
294 &[&feed.to_string()]
295 ))
296 );
297 }
298 }
299
300 // FIXME: the signature should be `fn foo(s: Url) -> Result<Url>`
301 pub(crate) async fn itunes_to_rss(url: &str) -> Result<String> {
302 let id = itunes_id_from_url(url).ok_or_else(|| anyhow!("Failed to find an iTunes ID."))?;
303 itunes_lookup_id(id).await
304 }
305
306 fn itunes_id_from_url(url: &str) -> Option<u32> {
307 static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/id([0-9]+)").unwrap());
308
309 // Get the itunes id from the url
310 let itunes_id = RE.captures_iter(url).next()?.get(1)?.as_str();
311 // Parse it to a u32, this *should* never fail
312 itunes_id.parse::<u32>().ok()
313 }
314
315 async fn itunes_lookup_id(id: u32) -> Result<String> {
316 let url = format!("https://itunes.apple.com/lookup?id={}&entity=podcast", id);
317 let req: Value = client_builder()
318 .build()?
319 .get(&url)
320 .send()
321 .await?
322 .json()
323 .await?;
324 let rssurl = || -> Option<&str> { req.get("results")?.get(0)?.get("feedUrl")?.as_str() };
325 rssurl()
326 .map(From::from)
327 .ok_or_else(|| anyhow!("Failed to get url from itunes response"))
328 }
329
330 /// Convert soundcloud page links to rss feed links.
331 /// Works for users and playlists.
332 pub(crate) async fn soundcloud_to_rss(url: &Url) -> Result<Url> {
333 // Turn: https://soundcloud.com/chapo-trap-house
334 // into: https://feeds.soundcloud.com/users/soundcloud:users:211911700/sounds.rss
335 let (user_id, playlist_id) = soundcloud_lookup_id(url)
336 .await
337 .ok_or_else(|| anyhow!("Failed to find a soundcloud ID."))?;
338 if playlist_id != 0 {
339 let url = format!(
340 "https://feeds.soundcloud.com/playlists/soundcloud:playlists:{}/sounds.rss",
341 playlist_id
342 );
343 Ok(Url::parse(&url)?)
344 } else if user_id != 0 {
345 let url = format!(
346 "https://feeds.soundcloud.com/users/soundcloud:users:{}/sounds.rss",
347 user_id
348 );
349 Ok(Url::parse(&url)?)
350 } else {
351 Err(anyhow!("No valid id's in soundcloud page."))
352 }
353 }
354
355 /// Extract (user, playlist) id's from a soundcloud page.
356 /// The id's are 0 if none was found.
357 /// If fetching the html page fails an Error is returned.
358 async fn soundcloud_lookup_id(url: &Url) -> Option<(u64, u64)> {
359 static RE_U: LazyLock<Regex> =
360 LazyLock::new(|| Regex::new(r"soundcloud://users:([0-9]+)").unwrap());
361 static RE_P: LazyLock<Regex> =
362 LazyLock::new(|| Regex::new(r"soundcloud://playlists:([0-9]+)").unwrap());
363
364 let url_str = url.to_string();
365 let client = client_builder().build().ok()?;
366 let response = client.get(&url_str).send();
367 let response_text = response.await.ok()?.text().await.ok()?;
368 let user_id = RE_U
369 .captures_iter(&response_text)
370 .next()
371 .and_then(|r| r.get(1).map(|u| u.as_str()));
372 let playlist_id = RE_P
373 .captures_iter(&response_text)
374 .next()
375 .and_then(|r| r.get(1).map(|u| u.as_str()));
376 // Parse it to a u64, this *should* never fail
377 Some((
378 user_id.and_then(|id| id.parse::<u64>().ok()).unwrap_or(0),
379 playlist_id
380 .and_then(|id| id.parse::<u64>().ok())
381 .unwrap_or(0),
382 ))
383 }
384
385 pub(crate) async fn on_import_clicked(window: &gtk::ApplicationWindow, sender: &Sender<Action>) {
386 // Set a filter to show only xml files
387 let filter = FileFilter::new();
388 FileFilter::set_name(&filter, Some(i18n("OPML file").as_str()));
389 filter.add_mime_type("application/xml");
390 filter.add_mime_type("text/xml");
391 filter.add_mime_type("text/x-opml");
392
393 let filters = gio::ListStore::new::<gtk::FileFilter>();
394 filters.append(&filter);
395
396 // Create the FileChooser Dialog
397 let dialog = gtk::FileDialog::builder()
398 .title(i18n(
399 "Select the file from which to you want to import shows.",
400 ))
401 .accept_label(i18n("_Import"))
402 .filters(&filters)
403 .build();
404
405 if let Ok(file) = dialog.open_future(Some(window)).await {
406 if let Some(path) = file.peek_path() {
407 // spawn a thread to avoid blocking ui during import
408 let result = gio::spawn_blocking(clone!(
409 #[strong]
410 sender,
411 move || {
412 // Parse the file and import the feeds
413 opml::import_from_file(path)
414 .map(|sources| {
415 // Refresh the successfully parsed feeds to index them
416 FEED_MANAGER.schedule_refresh(&sender, sources);
417 })
418 .context("PARSE")
419 }
420 ))
421 .await;
422
423 if let Err(err) = result.unwrap_or_else(|e| bail!("Import Thread Error {e:#?}")) {
424 let text = i18n_f("Failed to parse the imported file {}", &[&err.to_string()]);
425 send!(sender, Action::ErrorNotification(text));
426 }
427 }
428 };
429 }
430
431 pub(crate) async fn on_export_clicked(window: &gtk::ApplicationWindow, sender: &Sender<Action>) {
432 // Set a filter to show only xml files
433 let filter = FileFilter::new();
434 FileFilter::set_name(&filter, Some(i18n("OPML file").as_str()));
435 filter.add_mime_type("application/xml");
436 filter.add_mime_type("text/xml");
437 filter.add_mime_type("text/x-opml");
438
439 let filters = gio::ListStore::new::<gtk::FileFilter>();
440 filters.append(&filter);
441
442 // Create the FileChooser Dialog
443 let dialog = gtk::FileDialog::builder()
444 // Translators: Show as a noun, meaning Podcast-Shows.
445 .title(i18n("Export shows to…"))
446 .accept_label(i18n("_Export"))
447 .initial_name(format!(
448 "{}.opml",
449 // Translators: This is the string of the suggested name for the exported opml file
450 i18n("gnome-podcasts-exported-shows")
451 ))
452 .filters(&filters)
453 .build();
454
455 if let Ok(file) = dialog.save_future(Some(window)).await {
456 if let Some(path) = file.peek_path() {
457 debug!("File selected: {:?}", path);
458 let result = gio::spawn_blocking(move || {
459 opml::export_from_db(path, &i18n("GNOME Podcasts Subscriptions"))
460 })
461 .await;
462 if let Ok(Err(err)) = result {
463 let text = i18n("Failed to export podcasts");
464 error!("Failed to export podcasts: {err}");
465 send!(sender, Action::ErrorNotification(text));
466 }
467 }
468 };
469 }
470
•471 /* Disable tests that need a network connection
472
473 #[cfg(test)]
474 mod tests {
475 use super::*;
476 use anyhow::Result;
477 use podcasts_data::database::truncate_db;
478 use podcasts_data::dbqueries;
479 use podcasts_data::pipeline::pipeline;
480 use podcasts_data::utils::get_download_dir;
481 use podcasts_data::{Save, Source};
482 use std::fs;
483 use std::path::PathBuf;
484
485 #[tokio::test]
486 async fn test_itunes_to_rss() -> Result<()> {
487 let itunes_url = "https://itunes.apple.com/podcast/id1195206601";
488 // they keep changing the urls
489 let rss_url = "https://feeds.acast.com/public/shows/f5b64019-68c3-57d4-b70b-043e63e5cbf6";
490 let rss_url2 = "https://rss.acast.com/intercepted-with-jeremy-scahill";
491 let result_url = itunes_to_rss(itunes_url).await?;
492 assert!(result_url == rss_url || result_url == rss_url2);
493
494 let itunes_url = "https://itunes.apple.com/podcast/id000000000000000";
495 assert!(itunes_to_rss(itunes_url).await.is_err());
496 Ok(())
497 }
498
499 #[test]
500 fn test_itunes_id() -> Result<()> {
501 let id = 1195206601;
502 let itunes_url = "https://itunes.apple.com/podcast/id1195206601";
503 assert_eq!(id, itunes_id_from_url(itunes_url).unwrap());
504 Ok(())
505 }
506
507 #[tokio::test]
508 async fn test_itunes_lookup_id() -> Result<()> {
509 let id = 1195206601;
510 // they keep changing the urls
511 let rss_url = "https://feeds.acast.com/public/shows/f5b64019-68c3-57d4-b70b-043e63e5cbf6";
512 let rss_url2 = "https://rss.acast.com/intercepted-with-jeremy-scahill";
513 let result_url = itunes_lookup_id(id).await?;
514 assert!(result_url == rss_url || result_url == rss_url2);
515
516 let id = 000000000;
517 assert!(itunes_lookup_id(id).await.is_err());
518 Ok(())
519 }
520
521 #[tokio::test]
522 async fn test_soundcloud_to_rss() -> Result<()> {
523 let soundcloud_url = Url::parse("https://soundcloud.com/chapo-trap-house")?;
524 let rss_url = String::from(
525 "https://feeds.soundcloud.com/users/soundcloud:users:211911700/sounds.rss",
526 );
527 assert_eq!(
528 Url::parse(&rss_url)?,
529 soundcloud_to_rss(&soundcloud_url).await?
530 );
531
532 let soundcloud_url =
533 Url::parse("https://soundcloud.com/id000000000000000ajlsfhlsfhwoerzuweioh")?;
534 assert!(soundcloud_to_rss(&soundcloud_url).await.is_err());
535 Ok(())
536 }
537
538 #[tokio::test]
539 async fn test_soundcloud_playlist_to_rss() -> Result<()> {
540 // valid playlist
541 let soundcloud_url =
542 Url::parse("https://soundcloud.com/languagetransfer/sets/introduction-to-italian")?;
543 let rss_url = String::from(
544 "https://feeds.soundcloud.com/playlists/soundcloud:playlists:220248349/sounds.rss",
545 );
546 assert_eq!(
547 Url::parse(&rss_url)?,
548 soundcloud_to_rss(&soundcloud_url).await?
549 );
550
551 // invalid playlist link
552 let soundcloud_url =
553 Url::parse("https://soundcloud.com/languagetransfer/sets/does-not-exist")?;
554 assert!(soundcloud_to_rss(&soundcloud_url).await.is_err());
555
556 // user page with a playlist pinned at the top, should return user rss not playlist
557 let soundcloud_url = Url::parse("https://soundcloud.com/yung-chomsky")?;
558 let rss_url = String::from(
559 "https://feeds.soundcloud.com/users/soundcloud:users:418603470/sounds.rss",
560 );
561 assert_eq!(
562 Url::parse(&rss_url)?,
563 soundcloud_to_rss(&soundcloud_url).await?
564 );
565
566 // playlist without rss entries
567 let soundcloud_url =
568 Url::parse("https://soundcloud.com/yung-chomsky/sets/music-for-podcasts-volume-1")?;
569 let rss_url = String::from(
570 "https://feeds.soundcloud.com/playlists/soundcloud:playlists:1165448311/sounds.rss",
571 );
572 assert_eq!(
573 Url::parse(&rss_url)?,
574 soundcloud_to_rss(&soundcloud_url).await?
575 );
576 Ok(())
577 }
578
579 #[test]
580 #[ignore]
581 fn should_refresh_cached_image_when_the_image_uri_changes() -> Result<()> {
582 truncate_db()?;
583 let mut original_feed = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
584 original_feed.push("resources/test/feeds/2018-01-20-LinuxUnplugged.xml");
585 let original_url = format!(
586 "{}{}",
587 "file:/",
588 fs::canonicalize(original_feed)?.to_str().unwrap()
589 );
590 println!("Made it here! (1)");
591 let mut source = Source::from_url(&original_url)?;
592 println!("Made it here! (2)");
593 source.set_http_etag(None);
594 source.set_last_modified(None);
595 let sid = source.save()?.id();
596 println!("Made it here! (3)");
597 let rt = tokio::runtime::Runtime::new()?;
598 rt.block_on(pipeline(vec![source]))?;
599 println!("Made it here! (4)");
600 println!("The source id is {}!", sid.0);
601 dbqueries::get_sources().unwrap().iter().for_each(|s| {
602 println!("{}:{}", s.id().0, s.uri());
603 });
604
605 let original = dbqueries::get_podcast_from_source_id(sid)?;
606 println!("Made it here! (5)");
607 let original_image_uri = original.image_uri();
608 let original_image_uri_hash = original.image_uri_hash();
609 let original_image_cached = original.image_cached();
610 let download_dir = get_download_dir(original.title())?;
611 let image_path = download_dir + "/cover.jpeg";
612 let original_image_file_size = fs::metadata(&image_path)?.len(); // 693,343
613 println!("Made it here! (6)");
614
615 // Update the URI and refresh the feed
616 let mut new_feed = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
617 new_feed.push("resources/test/feeds/2020-12-19-LinuxUnplugged.xml");
618 let mut source = dbqueries::get_source_from_id(sid)?;
619 let new_url = format!(
620 "{}{}",
621 "file:/",
622 fs::canonicalize(new_feed)?.to_str().unwrap()
623 );
624 source.set_uri(new_url);
625 source.set_http_etag(None);
626 source.set_last_modified(None);
627 source.save()?;
628 println!("Made it here! (7)");
629 let rt = tokio::runtime::Runtime::new()?;
630 rt.block_on(pipeline(vec![source]))?;
631
632 println!("Made it here! (8)");
633 let new = dbqueries::get_podcast_from_source_id(sid)?;
634 let new_image_uri = new.image_uri();
635 let new_image_uri_hash = new.image_uri_hash();
636 let new_image_cached = new.image_cached();
637 let new_image_file_size = fs::metadata(&image_path)?.len();
638
639 println!("Made it here! (9)");
640 assert_eq!(original.title(), new.title());
641 assert_ne!(original_image_uri, new_image_uri);
642 assert_ne!(original_image_uri_hash, new_image_uri_hash);
643 assert_ne!(original_image_cached, new_image_cached);
644 assert_ne!(original_image_file_size, new_image_file_size);
645
646 fs::remove_file(image_path)?;
647 Ok(())
648 }
649 }
•650 */