src/global/structs/subscriptions.rs

352 lines · 10586 bytes

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