src/global/structs/subscriptions.rs

84c4617332578aaf4e9ee68a0a2d7d6258e48243
youtube-tui/src/global/structs/subscriptions.rs history · blame · raw

377 lines · 11281 bytes

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