src/global/structs/subscriptions.rs

376 lines · 11280 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, Formatter},
 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    if let Some(channel) = &channel {
240        let _ = update_channel_cache(channel, image_index);
241    }
242
243    Ok((videos, channel))
244}
245
246fn update_channel_cache(
247    channel: &FullChannelItem,
248    image_index: usize,
249) -> Result<(), Box<dyn Error>> {
250    let home_dir = home_dir().unwrap();
251    let cache_path = home_dir.join(format!(".cache/youtube-tui/channels/{}.json", channel.id));
252
253    if let Some(parent) = cache_path.parent() {
254        fs::create_dir_all(parent)?;
255    }
256
257    let item = crate::global::structs::Item::from_full_channel(
258        crate::global::traits::SearchProviderWrapper::channel(&channel.id)?,
259        image_index,
260    );
261
262    fs::write(&cache_path, serde_json::to_string(&item)?)?;
263    Ok(())
264}
265
266#[derive(Clone, Serialize, Deserialize)]
267pub struct SubItem {
268    pub channel: FullChannelItem,
269    pub videos: Vec<MiniVideoItem>,
270    pub last_sync: u64,
271    pub last_sync_channel: u64,
272    pub has_new: bool,
273}
274
275impl Eq for SubItem {}
276impl Ord for SubItem {
277    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
278        let get_timestamp = |item: &Self| match item.videos.first() {
279            Some(video) => video.timestamp.unwrap(),
280            None => 0,
281        };
282        get_timestamp(other).cmp(&get_timestamp(self))
283    }
284}
285
286impl Display for SubItem {
287    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
288        f.write_str(&self.channel.name)
289    }
290}
291
292impl PartialEq for SubItem {
293    fn eq(&self, other: &Self) -> bool {
294        self.channel.id == other.channel.id
295    }
296}
297
298impl PartialOrd for SubItem {
299    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
300        Some(self.cmp(other))
301    }
302}
303
304impl CollectionItem for SubItem {
305    fn id(&self) -> Option<&str> {
306        Some(&self.channel.id)
307    }
308
309    fn children_ids(&self) -> Vec<&str> {
310        self.videos
311            .iter()
312            .map(|video| video.id.as_str())
313            .collect::<_>()
314    }
315}
316
317impl Collection<SubItem> for Subscriptions {
318    const INDEX_PATH: &'static str = ".local/share/youtube-tui/subscriptions.json";
319
320    fn items(&self) -> &Vec<SubItem> {
321        &self.0
322    }
323
324    fn items_mut(&mut self) -> &mut Vec<SubItem> {
325        &mut self.0
326    }
327
328    fn from_items(items: Vec<SubItem>) -> Self {
329        Self(items)
330    }
331
332    fn save(&self) -> Result<(), Box<dyn Error>> {
333        let mut file = OpenOptions::new()
334            .truncate(true)
335            .write(true)
336            .create(true)
337            .open(home_dir().unwrap().join(Self::INDEX_PATH))?;
338
339        let save_string = serde_json::to_string_pretty(self)?;
340        file.write_all(save_string.as_bytes())?;
341        Ok(())
342    }
343
344    fn push(&mut self, _: SubItem) -> Result<(), Box<dyn Error>> {
345        unimplemented!("not in use");
346    }
347
348    fn load() -> Self {
349        let path = home_dir().unwrap().join(Self::INDEX_PATH);
350        let res = (|| -> Result<Self, Box<dyn Error>> {
351            let file_string = fs::read_to_string(&path)?;
352            let deserialized = serde_json::from_str(&file_string)?;
353            Ok(deserialized)
354        })();
355
356        // if res is err, then the file either doesn't exist of has be altered incorrectly, in
357        // which case returns Self::default()
358        if let Ok(mut subs) = res {
359            subs.0.sort();
360            subs
361        } else {
362            // if the file does exist, back it up
363            // if it doesn't exist, it will throw an error but we dont care
364            let mut new_path = path.clone();
365            new_path.pop();
366            new_path.push(format!(
367                "{}.{}.old",
368                Self::INDEX_PATH,
369                chrono::offset::Local::now()
370            ));
371            let _ = fs::rename(&path, &new_path);
372
373            Self::default()
374        }
375    }
376}