src/global/structs/subscriptions.rs

303 lines · 8251 bytes

  1use super::*;
  2use crate::global::{
  3    functions::{download_all_images, DownloadRequest},
  4    traits::{Collection, CollectionItem},
  5};
  6use home::home_dir;
  7use serde::*;
  8use std::{
  9    error::Error,
 10    fmt::Display,
 11    fs::{self, OpenOptions},
 12    io::Write,
 13    sync::{atomic::AtomicU32, mpsc, Arc},
 14    thread,
 15};
 16use typemap::Key;
 17
 18#[derive(Serialize, Deserialize, Default, Clone)]
 19/// id, videos
 20pub struct Subscriptions(pub Vec<SubItem>);
 21
 22impl Key for Subscriptions {
 23    type Value = Self;
 24}
 25
 26impl Subscriptions {
 27    /// Res<(success, failed)>
 28    pub fn sync(
 29        &mut self,
 30        client: &InvidiousClient,
 31        image_index: usize,
 32        download_thumbnails: bool,
 33    ) -> (u32, u32) {
 34        let failed = Arc::new(AtomicU32::new(0));
 35        let success = Arc::new(AtomicU32::new(0));
 36
 37        let len = self.0.len();
 38        let (tx, rx) = mpsc::channel();
 39        let mut channels = Vec::new();
 40        std::mem::swap(&mut self.0, &mut channels);
 41
 42        channels.into_iter().for_each(|mut item| {
 43            let tx = tx.clone();
 44            let client = client.clone();
 45            let success = success.clone();
 46            let failed = failed.clone();
 47            thread::spawn(move || {
 48                let res = sync_one(&item.channel.id, &client, image_index, download_thumbnails);
 49                match res {
 50                    Ok(synced) => {
 51                        success.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
 52                        item = synced;
 53                    }
 54                    Err(_) => {
 55                        failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
 56                        item.videos.clear()
 57                    }
 58                }
 59                tx.send(item)
 60            });
 61        });
 62
 63        for item in rx.into_iter().take(len) {
 64            self.0.push(item);
 65        }
 66
 67        self.0.sort();
 68
 69        let _ = self.save();
 70
 71        (
 72            success.load(std::sync::atomic::Ordering::Relaxed),
 73            failed.load(std::sync::atomic::Ordering::Relaxed),
 74        )
 75    }
 76
 77    pub fn sync_one(
 78        &mut self,
 79        id: &str,
 80        client: &InvidiousClient,
 81        image_index: usize,
 82        download_thumbnails: bool,
 83    ) -> Result<(), Box<dyn Error>> {
 84        let synced = sync_one(id, client, image_index, download_thumbnails)?;
 85        for item in self.0.iter_mut() {
 86            if *item == synced {
 87                *item = SubItem {
 88                    // synced.has_new = !synced.videos.is_empty
 89                    has_new: synced.has_new && synced.videos.first() != item.videos.first(),
 90                    ..synced
 91                };
 92                return Ok(());
 93            }
 94        }
 95
 96        self.0.push(synced);
 97        self.0.sort();
 98
 99        self.save()?;
100        Ok(())
101    }
102
103    pub fn remove_one(&mut self, id: &str) -> bool {
104        if let Some(i) = self.0.iter().position(|item| item.channel.id == id) {
105            self.0.remove(i);
106            return true;
107        }
108
109        false
110    }
111
112    pub fn get_all_videos(&self) -> Vec<MiniVideoItem> {
113        let mut videos = self
114            .0
115            .iter()
116            .flat_map(|item| item.videos.clone())
117            .collect::<Vec<_>>();
118        videos.sort();
119        videos
120    }
121
122    pub fn get_channels(&self) -> Vec<FullChannelItem> {
123        self.0.iter().map(|item| item.channel.clone()).collect()
124    }
125}
126
127fn sync_one(
128    id: &str,
129    client: &InvidiousClient,
130    image_index: usize,
131    download_thumbnails: bool,
132) -> Result<SubItem, Box<dyn Error>> {
133    let (tx, rx) = mpsc::sync_channel(1);
134
135    let client2 = client.clone();
136    let id2 = id.to_string();
137    thread::spawn(move || {
138        tx.send(
139            client2
140                .0
141                .channel(&id2, None)
142                .map(|channel| Item::from_full_channel(channel, image_index).into_fullchannel())
143                .ok(),
144        )
145    });
146    let mut videos = client
147        .0
148        .channel_videos(id, None)?
149        .videos
150        .into_iter()
151        .map(|video| {
152            Item::from_channel_video(video, image_index)
153                .into_minivideo()
154                .unwrap()
155        })
156        .collect::<Vec<_>>();
157    videos.sort();
158
159    let channel = rx
160        .recv()
161        .unwrap()
162        .ok_or(Errors::StrError("failed to get channel info {id}"))??;
163
164    if download_thumbnails {
165        let thumbnails: Vec<Option<DownloadRequest>> = videos
166            .iter()
167            .map(|video| {
168                Some(DownloadRequest {
169                    url: video.thumbnail_url.clone(),
170                    id: video.id.clone(),
171                })
172            })
173            .chain(
174                [Some(DownloadRequest {
175                    url: channel.thumbnail_url.clone(),
176                    id: channel.id.clone(),
177                })]
178                .into_iter(),
179            )
180            .collect::<Vec<_>>();
181        thread::spawn(move || {
182            download_all_images(thumbnails);
183        });
184    }
185
186    Ok(SubItem {
187        channel,
188        has_new: !videos.is_empty(),
189        videos,
190        last_sync: chrono::Utc::now().timestamp() as u64,
191    })
192}
193
194#[derive(Clone, Serialize, Deserialize)]
195pub struct SubItem {
196    pub channel: FullChannelItem,
197    pub videos: Vec<MiniVideoItem>,
198    pub last_sync: u64,
199    pub has_new: bool,
200}
201
202impl Eq for SubItem {}
203impl Ord for SubItem {
204    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
205        self.partial_cmp(other).unwrap()
206    }
207}
208
209impl Display for SubItem {
210    fn fmt(&self, f: &mut __private::Formatter<'_>) -> std::fmt::Result {
211        f.write_str(&self.channel.name)
212    }
213}
214
215impl PartialEq for SubItem {
216    fn eq(&self, other: &Self) -> bool {
217        self.channel.id == other.channel.id
218    }
219}
220
221impl PartialOrd for SubItem {
222    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
223        let get_timestamp = |item: &Self| match item.videos.first() {
224            Some(video) => video.timestamp.unwrap(),
225            None => 0,
226        };
227        get_timestamp(other).partial_cmp(&get_timestamp(self))
228    }
229}
230
231impl CollectionItem for SubItem {
232    fn id(&self) -> Option<&str> {
233        Some(&self.channel.id)
234    }
235
236    fn children_ids(&self) -> Vec<&str> {
237        self.videos
238            .iter()
239            .map(|video| video.id.as_str())
240            .collect::<_>()
241    }
242}
243
244impl Collection<SubItem> for Subscriptions {
245    const INDEX_PATH: &'static str = ".local/share/youtube-tui/subscriptions.json";
246
247    fn items(&self) -> &Vec<SubItem> {
248        &self.0
249    }
250
251    fn items_mut(&mut self) -> &mut Vec<SubItem> {
252        &mut self.0
253    }
254
255    fn from_items(items: Vec<SubItem>) -> Self {
256        Self(items)
257    }
258
259    fn save(&self) -> Result<(), Box<dyn Error>> {
260        let mut file = OpenOptions::new()
261            .truncate(true)
262            .write(true)
263            .create(true)
264            .open(home_dir().unwrap().join(Self::INDEX_PATH))?;
265
266        let save_string = serde_json::to_string_pretty(self)?;
267        file.write_all(save_string.as_bytes())?;
268        Ok(())
269    }
270
271    fn push(&mut self, _: SubItem, _: Option<usize>) -> Result<(), Box<dyn Error>> {
272        unimplemented!("not in use");
273    }
274
275    fn load() -> Self {
276        let path = home_dir().unwrap().join(Self::INDEX_PATH);
277        let res = (|| -> Result<Self, Box<dyn Error>> {
278            let file_string = fs::read_to_string(&path)?;
279            let deserialized = serde_json::from_str(&file_string)?;
280            Ok(deserialized)
281        })();
282
283        // if res is err, then the file either doesn't exist of has be altered incorrectly, in
284        // which case returns Self::default()
285        if let Ok(mut subs) = res {
286            subs.0.sort();
287            subs
288        } else {
289            // if the file does exist, back it up
290            // if it doesn't exist, it will throw an error but we dont care
291            let mut new_path = path.clone();
292            new_path.pop();
293            new_path.push(format!(
294                "{}.{}.old",
295                Self::INDEX_PATH,
296                chrono::offset::Local::now()
297            ));
298            let _ = fs::rename(&path, &new_path);
299
300            Self::default()
301        }
302    }
303}