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