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