use super::*; use crate::global::{ functions::{download_all_images, DownloadRequest}, traits::{Collection, CollectionItem}, }; use home::home_dir; use serde::*; use std::{ error::Error, fmt::Display, fs::{self, OpenOptions}, io::Write, sync::{atomic::AtomicU32, mpsc, Arc}, thread, }; use typemap::Key; #[derive(Serialize, Deserialize, Default, Clone)] /// id, videos pub struct Subscriptions(pub Vec); impl Key for Subscriptions { type Value = Self; } impl Subscriptions { /// Res<(success, failed)> pub fn sync( &mut self, client: &InvidiousClient, image_index: usize, download_thumbnails: bool, ) -> (u32, u32) { let failed = Arc::new(AtomicU32::new(0)); let success = Arc::new(AtomicU32::new(0)); let len = self.0.len(); let (tx, rx) = mpsc::channel(); let mut channels = Vec::new(); std::mem::swap(&mut self.0, &mut channels); channels.into_iter().for_each(|mut item| { let tx = tx.clone(); let client = client.clone(); let success = success.clone(); let failed = failed.clone(); thread::spawn(move || { let res = sync_one(&item.channel.id, &client, image_index, download_thumbnails); match res { Ok(synced) => { success.fetch_add(1, std::sync::atomic::Ordering::Relaxed); item = synced; } Err(_) => { failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed); item.videos.clear() } } tx.send(item) }); }); for item in rx.into_iter().take(len) { self.0.push(item); } self.0.sort(); let _ = self.save(); ( success.load(std::sync::atomic::Ordering::Relaxed), failed.load(std::sync::atomic::Ordering::Relaxed), ) } pub fn sync_one( &mut self, id: &str, client: &InvidiousClient, image_index: usize, download_thumbnails: bool, ) -> Result<(), Box> { let synced = sync_one(id, client, image_index, download_thumbnails)?; for item in self.0.iter_mut() { if *item == synced { *item = SubItem { // synced.has_new = !synced.videos.is_empty has_new: synced.has_new && synced.videos.first() != item.videos.first(), ..synced }; return Ok(()); } } self.0.push(synced); self.0.sort(); self.save()?; Ok(()) } pub fn remove_one(&mut self, id: &str) -> bool { if let Some(i) = self.0.iter().position(|item| item.channel.id == id) { self.0.remove(i); return true; } false } pub fn get_all_videos(&self) -> Vec { let mut videos = self .0 .iter() .flat_map(|item| item.videos.clone()) .collect::>(); videos.sort(); videos } pub fn get_channels(&self) -> Vec { self.0.iter().map(|item| item.channel.clone()).collect() } } fn sync_one( id: &str, client: &InvidiousClient, image_index: usize, download_thumbnails: bool, ) -> Result> { let (tx, rx) = mpsc::sync_channel(1); let client2 = client.clone(); let id2 = id.to_string(); thread::spawn(move || { tx.send( client2 .0 .channel(&id2, None) .map(|channel| Item::from_full_channel(channel, image_index).into_fullchannel()) .ok(), ) }); let mut videos = client .0 .channel_videos(id, None)? .videos .into_iter() .map(|video| { Item::from_channel_video(video, image_index) .into_minivideo() .unwrap() }) .collect::>(); videos.sort(); let channel = rx .recv() .unwrap() .ok_or(Errors::StrError("failed to get channel info {id}"))??; if download_thumbnails { let thumbnails: Vec> = videos .iter() .map(|video| { Some(DownloadRequest { url: video.thumbnail_url.clone(), id: video.id.clone(), }) }) .chain( [Some(DownloadRequest { url: channel.thumbnail_url.clone(), id: channel.id.clone(), })] .into_iter(), ) .collect::>(); thread::spawn(move || { download_all_images(thumbnails); }); } Ok(SubItem { channel, has_new: !videos.is_empty(), videos, last_sync: chrono::Utc::now().timestamp() as u64, }) } #[derive(Clone, Serialize, Deserialize)] pub struct SubItem { pub channel: FullChannelItem, pub videos: Vec, pub last_sync: u64, pub has_new: bool, } impl Eq for SubItem {} impl Ord for SubItem { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.partial_cmp(other).unwrap() } } impl Display for SubItem { fn fmt(&self, f: &mut __private::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.channel.name) } } impl PartialEq for SubItem { fn eq(&self, other: &Self) -> bool { self.channel.id == other.channel.id } } impl PartialOrd for SubItem { fn partial_cmp(&self, other: &Self) -> Option { let get_timestamp = |item: &Self| match item.videos.first() { Some(video) => video.timestamp.unwrap(), None => 0, }; get_timestamp(other).partial_cmp(&get_timestamp(self)) } } impl CollectionItem for SubItem { fn id(&self) -> Option<&str> { Some(&self.channel.id) } fn children_ids(&self) -> Vec<&str> { self.videos .iter() .map(|video| video.id.as_str()) .collect::<_>() } } impl Collection for Subscriptions { const INDEX_PATH: &'static str = ".local/share/youtube-tui/subscriptions.json"; fn items(&self) -> &Vec { &self.0 } fn items_mut(&mut self) -> &mut Vec { &mut self.0 } fn from_items(items: Vec) -> Self { Self(items) } fn save(&self) -> Result<(), Box> { let mut file = OpenOptions::new() .truncate(true) .write(true) .create(true) .open(home_dir().unwrap().join(Self::INDEX_PATH))?; let save_string = serde_json::to_string_pretty(self)?; file.write_all(save_string.as_bytes())?; Ok(()) } fn push(&mut self, _: SubItem, _: Option) -> Result<(), Box> { unimplemented!("not in use"); } fn load() -> Self { let path = home_dir().unwrap().join(Self::INDEX_PATH); let res = (|| -> Result> { let file_string = fs::read_to_string(&path)?; let deserialized = serde_json::from_str(&file_string)?; Ok(deserialized) })(); // if res is err, then the file either doesn't exist of has be altered incorrectly, in // which case returns Self::default() if let Ok(mut subs) = res { subs.0.sort(); subs } else { // if the file does exist, back it up // if it doesn't exist, it will throw an error but we dont care let mut new_path = path.clone(); new_path.pop(); new_path.push(format!( "{}.{}.old", Self::INDEX_PATH, chrono::offset::Local::now() )); let _ = fs::rename(&path, &new_path); Self::default() } } }