| 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: >k::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: >k::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 |
#[cfg(test)] |
| 472 |
mod tests { |
| 473 |
use super::*; |
| 474 |
use anyhow::Result; |
| 475 |
use podcasts_data::database::truncate_db; |
| 476 |
use podcasts_data::dbqueries; |
| 477 |
use podcasts_data::pipeline::pipeline; |
| 478 |
use podcasts_data::utils::get_download_dir; |
| 479 |
use podcasts_data::{Save, Source}; |
| 480 |
use std::fs; |
| 481 |
use std::path::PathBuf; |
| 482 |
|
| 483 |
#[tokio::test] |
| 484 |
async fn test_itunes_to_rss() -> Result<()> { |
| 485 |
let itunes_url = "https://itunes.apple.com/podcast/id1195206601"; |
| 486 |
// they keep changing the urls |
| 487 |
let rss_url = "https://feeds.acast.com/public/shows/f5b64019-68c3-57d4-b70b-043e63e5cbf6"; |
| 488 |
let rss_url2 = "https://rss.acast.com/intercepted-with-jeremy-scahill"; |
| 489 |
let result_url = itunes_to_rss(itunes_url).await?; |
| 490 |
assert!(result_url == rss_url || result_url == rss_url2); |
| 491 |
|
| 492 |
let itunes_url = "https://itunes.apple.com/podcast/id000000000000000"; |
| 493 |
assert!(itunes_to_rss(itunes_url).await.is_err()); |
| 494 |
Ok(()) |
| 495 |
} |
| 496 |
|
| 497 |
#[test] |
| 498 |
fn test_itunes_id() -> Result<()> { |
| 499 |
let id = 1195206601; |
| 500 |
let itunes_url = "https://itunes.apple.com/podcast/id1195206601"; |
| 501 |
assert_eq!(id, itunes_id_from_url(itunes_url).unwrap()); |
| 502 |
Ok(()) |
| 503 |
} |
| 504 |
|
| 505 |
#[tokio::test] |
| 506 |
async fn test_itunes_lookup_id() -> Result<()> { |
| 507 |
let id = 1195206601; |
| 508 |
// they keep changing the urls |
| 509 |
let rss_url = "https://feeds.acast.com/public/shows/f5b64019-68c3-57d4-b70b-043e63e5cbf6"; |
| 510 |
let rss_url2 = "https://rss.acast.com/intercepted-with-jeremy-scahill"; |
| 511 |
let result_url = itunes_lookup_id(id).await?; |
| 512 |
assert!(result_url == rss_url || result_url == rss_url2); |
| 513 |
|
| 514 |
let id = 000000000; |
| 515 |
assert!(itunes_lookup_id(id).await.is_err()); |
| 516 |
Ok(()) |
| 517 |
} |
| 518 |
|
| 519 |
#[tokio::test] |
| 520 |
async fn test_soundcloud_to_rss() -> Result<()> { |
| 521 |
let soundcloud_url = Url::parse("https://soundcloud.com/chapo-trap-house")?; |
| 522 |
let rss_url = String::from( |
| 523 |
"https://feeds.soundcloud.com/users/soundcloud:users:211911700/sounds.rss", |
| 524 |
); |
| 525 |
assert_eq!( |
| 526 |
Url::parse(&rss_url)?, |
| 527 |
soundcloud_to_rss(&soundcloud_url).await? |
| 528 |
); |
| 529 |
|
| 530 |
let soundcloud_url = |
| 531 |
Url::parse("https://soundcloud.com/id000000000000000ajlsfhlsfhwoerzuweioh")?; |
| 532 |
assert!(soundcloud_to_rss(&soundcloud_url).await.is_err()); |
| 533 |
Ok(()) |
| 534 |
} |
| 535 |
|
| 536 |
#[tokio::test] |
| 537 |
async fn test_soundcloud_playlist_to_rss() -> Result<()> { |
| 538 |
// valid playlist |
| 539 |
let soundcloud_url = |
| 540 |
Url::parse("https://soundcloud.com/languagetransfer/sets/introduction-to-italian")?; |
| 541 |
let rss_url = String::from( |
| 542 |
"https://feeds.soundcloud.com/playlists/soundcloud:playlists:220248349/sounds.rss", |
| 543 |
); |
| 544 |
assert_eq!( |
| 545 |
Url::parse(&rss_url)?, |
| 546 |
soundcloud_to_rss(&soundcloud_url).await? |
| 547 |
); |
| 548 |
|
| 549 |
// invalid playlist link |
| 550 |
let soundcloud_url = |
| 551 |
Url::parse("https://soundcloud.com/languagetransfer/sets/does-not-exist")?; |
| 552 |
assert!(soundcloud_to_rss(&soundcloud_url).await.is_err()); |
| 553 |
|
| 554 |
// user page with a playlist pinned at the top, should return user rss not playlist |
| 555 |
let soundcloud_url = Url::parse("https://soundcloud.com/yung-chomsky")?; |
| 556 |
let rss_url = String::from( |
| 557 |
"https://feeds.soundcloud.com/users/soundcloud:users:418603470/sounds.rss", |
| 558 |
); |
| 559 |
assert_eq!( |
| 560 |
Url::parse(&rss_url)?, |
| 561 |
soundcloud_to_rss(&soundcloud_url).await? |
| 562 |
); |
| 563 |
|
| 564 |
// playlist without rss entries |
| 565 |
let soundcloud_url = |
| 566 |
Url::parse("https://soundcloud.com/yung-chomsky/sets/music-for-podcasts-volume-1")?; |
| 567 |
let rss_url = String::from( |
| 568 |
"https://feeds.soundcloud.com/playlists/soundcloud:playlists:1165448311/sounds.rss", |
| 569 |
); |
| 570 |
assert_eq!( |
| 571 |
Url::parse(&rss_url)?, |
| 572 |
soundcloud_to_rss(&soundcloud_url).await? |
| 573 |
); |
| 574 |
Ok(()) |
| 575 |
} |
| 576 |
|
| 577 |
#[test] |
| 578 |
#[ignore] |
| 579 |
fn should_refresh_cached_image_when_the_image_uri_changes() -> Result<()> { |
| 580 |
truncate_db()?; |
| 581 |
let mut original_feed = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 582 |
original_feed.push("resources/test/feeds/2018-01-20-LinuxUnplugged.xml"); |
| 583 |
let original_url = format!( |
| 584 |
"{}{}", |
| 585 |
"file:/", |
| 586 |
fs::canonicalize(original_feed)?.to_str().unwrap() |
| 587 |
); |
| 588 |
println!("Made it here! (1)"); |
| 589 |
let mut source = Source::from_url(&original_url)?; |
| 590 |
println!("Made it here! (2)"); |
| 591 |
source.set_http_etag(None); |
| 592 |
source.set_last_modified(None); |
| 593 |
let sid = source.save()?.id(); |
| 594 |
println!("Made it here! (3)"); |
| 595 |
let rt = tokio::runtime::Runtime::new()?; |
| 596 |
rt.block_on(pipeline(vec![source]))?; |
| 597 |
println!("Made it here! (4)"); |
| 598 |
println!("The source id is {}!", sid.0); |
| 599 |
dbqueries::get_sources().unwrap().iter().for_each(|s| { |
| 600 |
println!("{}:{}", s.id().0, s.uri()); |
| 601 |
}); |
| 602 |
|
| 603 |
let original = dbqueries::get_podcast_from_source_id(sid)?; |
| 604 |
println!("Made it here! (5)"); |
| 605 |
let original_image_uri = original.image_uri(); |
| 606 |
let original_image_uri_hash = original.image_uri_hash(); |
| 607 |
let original_image_cached = original.image_cached(); |
| 608 |
let download_dir = get_download_dir(original.title())?; |
| 609 |
let image_path = download_dir + "/cover.jpeg"; |
| 610 |
let original_image_file_size = fs::metadata(&image_path)?.len(); // 693,343 |
| 611 |
println!("Made it here! (6)"); |
| 612 |
|
| 613 |
// Update the URI and refresh the feed |
| 614 |
let mut new_feed = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 615 |
new_feed.push("resources/test/feeds/2020-12-19-LinuxUnplugged.xml"); |
| 616 |
let mut source = dbqueries::get_source_from_id(sid)?; |
| 617 |
let new_url = format!( |
| 618 |
"{}{}", |
| 619 |
"file:/", |
| 620 |
fs::canonicalize(new_feed)?.to_str().unwrap() |
| 621 |
); |
| 622 |
source.set_uri(new_url); |
| 623 |
source.set_http_etag(None); |
| 624 |
source.set_last_modified(None); |
| 625 |
source.save()?; |
| 626 |
println!("Made it here! (7)"); |
| 627 |
let rt = tokio::runtime::Runtime::new()?; |
| 628 |
rt.block_on(pipeline(vec![source]))?; |
| 629 |
|
| 630 |
println!("Made it here! (8)"); |
| 631 |
let new = dbqueries::get_podcast_from_source_id(sid)?; |
| 632 |
let new_image_uri = new.image_uri(); |
| 633 |
let new_image_uri_hash = new.image_uri_hash(); |
| 634 |
let new_image_cached = new.image_cached(); |
| 635 |
let new_image_file_size = fs::metadata(&image_path)?.len(); |
| 636 |
|
| 637 |
println!("Made it here! (9)"); |
| 638 |
assert_eq!(original.title(), new.title()); |
| 639 |
assert_ne!(original_image_uri, new_image_uri); |
| 640 |
assert_ne!(original_image_uri_hash, new_image_uri_hash); |
| 641 |
assert_ne!(original_image_cached, new_image_cached); |
| 642 |
assert_ne!(original_image_file_size, new_image_file_size); |
| 643 |
|
| 644 |
fs::remove_file(image_path)?; |
| 645 |
Ok(()) |
| 646 |
} |
| 647 |
} |