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