src/global/structs/item.rs

520 lines · 17222 bytes

  1use crate::global::{functions::*, traits::CollectionItem};
  2use invidious::{channel::Channel, hidden::*, universal::Playlist as FullPlaylist, video::Video};
  3use serde::{Deserialize, Serialize};
  4use std::fmt::Display;
  5
  6use super::Errors;
  7
  8/// Items are things like a single video/playlist and channel
  9// they are displayed by the item info widget in `iteminfo.rs`
 10#[derive(Clone, Serialize, Deserialize)]
 11#[serde(tag = "type", content = "data")]
 12pub enum Item {
 13    // minivideos are all videos that appeared without actually clicking into the video
 14    MiniVideo(MiniVideoItem),
 15    MiniPlaylist(MiniPlaylistItem),
 16    MiniChannel(MiniChannelItem),
 17    FullVideo(FullVideoItem),
 18    FullPlaylist(FullPlaylistItem),
 19    FullChannel(FullChannelItem),
 20    Page(bool), // true: next false: prev
 21    Unknown(SearchItemTransition),
 22}
 23
 24impl CollectionItem for Item {
 25    fn id(&self) -> Option<&str> {
 26        self.id()
 27    }
 28
 29    fn children_ids(&self) -> Vec<&str> {
 30        if let Self::FullPlaylist(playlist) = self {
 31            playlist
 32                .videos
 33                .iter()
 34                .map(|video| video.id().unwrap())
 35                .collect::<Vec<_>>()
 36        } else {
 37            Vec::new()
 38        }
 39    }
 40}
 41
 42/// stores information of a previewed video
 43#[derive(Clone, Serialize, Deserialize, Eq)]
 44pub struct MiniVideoItem {
 45    pub title: String,
 46    pub id: String,
 47    pub thumbnail_url: String,
 48    pub length: String,
 49    pub views: Option<String>,
 50    pub channel: String,
 51    pub channel_id: String,
 52    pub published: Option<String>,
 53    pub timestamp: Option<u64>,
 54    pub description: Option<String>,
 55}
 56
 57impl PartialOrd for MiniVideoItem {
 58    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
 59        other.timestamp.partial_cmp(&self.timestamp)
 60        // self.timestamp.partial_cmp(&other.timestamp)
 61    }
 62}
 63
 64impl Ord for MiniVideoItem {
 65    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
 66        self.timestamp
 67            .unwrap_or_default()
 68            .cmp(&other.timestamp.unwrap_or_default())
 69    }
 70}
 71
 72impl PartialEq for MiniVideoItem {
 73    fn eq(&self, other: &Self) -> bool {
 74        self.id == other.id
 75    }
 76}
 77
 78/// stores information of a previewed playlist
 79#[derive(Clone, Serialize, Deserialize)]
 80pub struct MiniPlaylistItem {
 81    pub title: String,
 82    pub id: String,
 83    pub channel: String,
 84    pub channel_id: String,
 85    pub video_count: u32,
 86    pub thumbnail_url: String,
 87}
 88
 89/// stores information of a previewed channel
 90#[derive(Clone, Serialize, Deserialize)]
 91pub struct MiniChannelItem {
 92    pub name: String,
 93    pub id: String,
 94    pub thumbnail_url: String,
 95    pub sub_count: u32,
 96    pub sub_count_text: String,
 97    pub video_count: u32,
 98    pub description: String,
 99}
100
101/// stores information of a viewed video
102#[derive(Clone, Serialize, Deserialize)]
103pub struct FullVideoItem {
104    pub title: String,
105    pub id: String,
106    pub thumbnail_url: String,
107    pub length: String,
108    pub views: String,
109    pub channel: String,
110    pub channel_id: String,
111    pub sub_count: String,
112    pub published: String,
113    pub description: String,
114    pub likes: String,
115    // pub dislikes: Option<String>, TODO
116    pub genre: String,
117}
118
119/// stores information of a viewed playlist
120#[derive(Clone, Serialize, Deserialize)]
121pub struct FullPlaylistItem {
122    pub title: String,
123    pub id: String,
124    pub channel: String,
125    pub channel_id: String,
126    pub video_count: u32,
127    pub description: String,
128    pub views: String,
129    pub thumbnail_url: String,
130    pub videos: Vec<Item>,
131}
132
133/// stores information of a viewed channel
134#[derive(Clone, Serialize, Deserialize)]
135pub struct FullChannelItem {
136    pub name: String,
137    pub id: String,
138    pub thumbnail_url: String,
139    pub sub_count: u32,
140    pub sub_count_text: String,
141    pub total_views: String,
142    pub created: String,
143    pub autogenerated: bool,
144    pub description: String,
145}
146
147impl Display for Item {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.write_str(match self {
150            Self::MiniVideo(video) => &video.title,
151            Self::MiniPlaylist(playlist) => &playlist.title,
152            Self::MiniChannel(channel) => &channel.name,
153            Self::FullVideo(video) => &video.title,
154            Self::FullPlaylist(playlist) => &playlist.title,
155            Self::FullChannel(channel) => &channel.name,
156            Self::Page(b) => {
157                if *b {
158                    "Next page"
159                } else {
160                    "Previous page"
161                }
162            }
163            Self::Unknown(_) => "Unknown item",
164        })
165    }
166}
167
168impl Item {
169    /// returns the id of an item, `None` is self is Unknown
170    pub fn id(&self) -> Option<&str> {
171        match self {
172            Self::MiniVideo(MiniVideoItem { id, .. })
173            | Self::MiniChannel(MiniChannelItem { id, .. })
174            | Self::MiniPlaylist(MiniPlaylistItem { id, .. })
175            | Self::FullVideo(FullVideoItem { id, .. })
176            | Self::FullChannel(FullChannelItem { id, .. })
177            | Self::FullPlaylist(FullPlaylistItem { id, .. }) => Some(id),
178            Self::Unknown(_) | Self::Page(_) => None,
179        }
180    }
181
182    /// check if self is Self::Unknown
183    pub fn is_unknown(&self) -> bool {
184        matches!(self, Self::Unknown(_))
185    }
186}
187
188impl Item {
189    /// stript self into a FullVideoItem
190    pub fn fullvideo(&self) -> Result<&FullVideoItem, Errors> {
191        match self {
192            Self::FullVideo(fullvideo) => Ok(fullvideo),
193            _ => Err(Errors::StrError("not a full video")),
194        }
195    }
196
197    /// stript self into a MiniVideoItem
198    pub fn minivideo(&self) -> Result<&MiniVideoItem, Errors> {
199        match self {
200            Self::MiniVideo(minivideo) => Ok(minivideo),
201            _ => Err(Errors::StrError("not a mini video")),
202        }
203    }
204
205    /// stript self into a MiniPlaylistItem
206    pub fn miniplaylist(&self) -> Result<&MiniPlaylistItem, Errors> {
207        match self {
208            Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
209            _ => Err(Errors::StrError("not a mini playlist")),
210        }
211    }
212
213    /// stript self into a FullPlaylistItem
214    pub fn fullplaylist(&self) -> Result<&FullPlaylistItem, Errors> {
215        match self {
216            Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
217            _ => Err(Errors::StrError("not a full playlist")),
218        }
219    }
220
221    /// stript self into a MiniChannelItem
222    pub fn minichannel(&self) -> Result<&MiniChannelItem, Errors> {
223        match self {
224            Self::MiniChannel(minichannel) => Ok(minichannel),
225            _ => Err(Errors::StrError("not a mini channel")),
226        }
227    }
228
229    pub fn fullchannel(&self) -> Result<&FullChannelItem, Errors> {
230        match self {
231            Self::FullChannel(fullchannel) => Ok(fullchannel),
232            _ => Err(Errors::StrError("not a full channel")),
233        }
234    }
235}
236
237impl Item {
238    /// stript self into a FullVideoItem
239    pub fn into_fullvideo(self) -> Result<FullVideoItem, Errors> {
240        match self {
241            Self::FullVideo(fullvideo) => Ok(fullvideo),
242            _ => Err(Errors::StrError("not a full video")),
243        }
244    }
245
246    /// stript self into a MiniVideoItem
247    pub fn into_minivideo(self) -> Result<MiniVideoItem, Errors> {
248        match self {
249            Self::MiniVideo(minivideo) => Ok(minivideo),
250            _ => Err(Errors::StrError("not a mini video")),
251        }
252    }
253
254    /// stript self into a MiniPlaylistItem
255    pub fn into_miniplaylist(self) -> Result<MiniPlaylistItem, Errors> {
256        match self {
257            Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
258            _ => Err(Errors::StrError("not a mini playlist")),
259        }
260    }
261
262    /// stript self into a FullPlaylistItem
263    pub fn into_fullplaylist(self) -> Result<FullPlaylistItem, Errors> {
264        match self {
265            Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
266            _ => Err(Errors::StrError("not a full playlist")),
267        }
268    }
269
270    /// stript self into a MiniChannelItem
271    pub fn into_minichannel(self) -> Result<MiniChannelItem, Errors> {
272        match self {
273            Self::MiniChannel(minichannel) => Ok(minichannel),
274            _ => Err(Errors::StrError("not a mini channel")),
275        }
276    }
277
278    pub fn into_fullchannel(self) -> Result<FullChannelItem, Errors> {
279        match self {
280            Self::FullChannel(fullchannel) => Ok(fullchannel),
281            _ => Err(Errors::StrError("not a full channel")),
282        }
283    }
284}
285
286impl Item {
287    /// returns the file save path for thumbnails (which is by their id)
288    /// returns `invalid` if the item does not have a thumbnail
289    pub fn thumbnail_id(&self) -> &str {
290        match self {
291            Self::MiniVideo(video) => &video.id,
292            Self::MiniPlaylist(playlist) => &playlist.id,
293            Self::MiniChannel(channel) => &channel.id,
294            Self::FullVideo(video) => &video.id,
295            Self::FullPlaylist(playlist) => &playlist.id,
296            Self::FullChannel(channel) => &channel.id,
297            Self::Unknown(_) | Self::Page(_) => "invalid",
298        }
299    }
300
301    /// parse `TrendingVideo` into `Self`
302    pub fn from_trending_video(original: TrendingVideo, image_index: usize) -> Self {
303        Self::MiniVideo(MiniVideoItem {
304            title: original.title,
305            id: original.id,
306            thumbnail_url: original.thumbmails[image_index].url.clone(),
307            length: secs_display_string(original.length),
308            views: Some(viewcount_text(original.views)),
309            channel: original.author,
310            channel_id: original.author_id,
311            timestamp: Some(original.published),
312            published: Some(format!(
313                "{} [{}]",
314                original.published_text,
315                date_text(original.published)
316            )),
317            description: Some(original.description),
318        })
319    }
320
321    /// parse `PopularItem` into `Self`
322    pub fn from_popular_item(original: PopularItem, image_index: usize) -> Self {
323        Self::MiniVideo(MiniVideoItem {
324            title: original.title,
325            id: original.id,
326            thumbnail_url: original.thumbnails[image_index].url.clone(),
327            length: secs_display_string(original.length),
328            views: Some(viewcount_text(original.views)),
329            channel: original.author,
330            channel_id: original.author_id,
331            timestamp: Some(original.published),
332            published: Some(format!(
333                "{} [{}]",
334                original.published_text,
335                date_text(original.published)
336            )),
337            description: None,
338        })
339    }
340
341    /// parse `Playlist` into `Self`
342    pub fn from_mini_playlist(original: Playlist) -> Self {
343        Self::MiniPlaylist(MiniPlaylistItem {
344            title: original.title,
345            id: original.id,
346            channel: original.author,
347            channel_id: original.author_id,
348            video_count: original.video_count,
349            thumbnail_url: original.thumbnail,
350        })
351    }
352
353    /// parse `SearchItem` into `Self`
354    pub fn from_search_item(original: SearchItem, image_index: usize) -> Self {
355        match original {
356            SearchItem::Video {
357                title,
358                id,
359                author,
360                author_id,
361                length,
362                thumbnails,
363                description,
364                views,
365                published,
366                published_text,
367                ..
368            } => Self::MiniVideo(MiniVideoItem {
369                title,
370                id,
371                thumbnail_url: thumbnails[image_index].url.clone(),
372                length: secs_display_string(length as u32),
373                views: Some(viewcount_text(views)),
374                channel: author,
375                channel_id: author_id,
376                timestamp: Some(published),
377                published: Some(format!("{} [{}]", published_text, date_text(published))),
378                description: Some(description),
379            }),
380            SearchItem::Playlist {
381                title,
382                id,
383                author,
384                author_id,
385                video_count,
386                thumbnail,
387                ..
388            } => Self::MiniPlaylist(MiniPlaylistItem {
389                title,
390                id,
391                channel: author,
392                channel_id: author_id,
393                video_count,
394                thumbnail_url: thumbnail,
395            }),
396            SearchItem::Channel {
397                name,
398                id,
399                thumbnails,
400                subscribers,
401                video_count,
402                description,
403                ..
404            } => Self::MiniChannel(MiniChannelItem {
405                name,
406                id,
407                thumbnail_url: format!("https://{}", thumbnails[image_index].url),
408                video_count,
409                sub_count: subscribers,
410                sub_count_text: viewcount_text(subscribers as u64),
411                description,
412            }),
413            SearchItem::Unknown(searchitem_transitional) => Self::Unknown(searchitem_transitional),
414        }
415    }
416
417    /// parse `Video` into `Self`
418    pub fn from_full_video(original: Video, image_index: usize) -> Self {
419        Self::FullVideo(FullVideoItem {
420            title: original.title,
421            id: original.id,
422            thumbnail_url: original.thumbnails[image_index].url.clone(),
423            length: secs_display_string(original.length),
424            views: viewcount_text(original.views),
425            channel: original.author,
426            channel_id: original.author_id,
427            sub_count: original.sub_count_text,
428            published: format!(
429                "{} [{}]",
430                original.published_text,
431                date_text(original.published)
432            ),
433            description: original.description,
434            likes: viewcount_text(original.likes as u64),
435            genre: original.genre,
436        })
437    }
438
439    /// parse `FullPlaylist` into `Self`
440    pub fn from_full_playlist(original: FullPlaylist, image_index: usize) -> Self {
441        Self::FullPlaylist(FullPlaylistItem {
442            title: original.title,
443            id: original.id,
444            channel: original.author,
445            channel_id: original.author_id,
446            video_count: original.video_count,
447            description: original.description,
448            views: viewcount_text(original.views),
449            thumbnail_url: original.thumbnail,
450            videos: original
451                .videos
452                .into_iter()
453                .map(|video| Self::from_playlist_item(video, image_index))
454                .collect(),
455        })
456    }
457
458    /// parse `PlaylistItem` into `Self`
459    pub fn from_playlist_item(original: PlaylistItem, image_index: usize) -> Self {
460        Self::MiniVideo(MiniVideoItem {
461            title: original.title,
462            id: original.id,
463            thumbnail_url: original.thumbnails[image_index].url.clone(),
464            length: secs_display_string(original.length),
465            views: None,
466            channel: original.author,
467            channel_id: original.author_id,
468            timestamp: None,
469            published: None,
470            description: None,
471        })
472    }
473
474    /// parse `Channel` into `Self`
475    pub fn from_full_channel(original: Channel, image_index: usize) -> Self {
476        Self::FullChannel(FullChannelItem {
477            name: original.name,
478            id: original.id,
479            thumbnail_url: original.thumbnails[image_index].url.clone(),
480            sub_count: original.sub_count,
481            sub_count_text: viewcount_text(original.sub_count as u64),
482            total_views: viewcount_text(original.total_views),
483            created: date_text(original.joined),
484            autogenerated: original.auto_generated,
485            description: original.description,
486        })
487    }
488
489    /// parse `ChannelVideo` into `Self`
490    pub fn from_channel_video(original: ChannelVideo, image_index: usize) -> Self {
491        Self::MiniVideo(MiniVideoItem {
492            title: original.title,
493            id: original.id,
494            thumbnail_url: original.thumbnails[image_index].url.clone(),
495            length: secs_display_string(original.length),
496            views: Some(viewcount_text(original.view_count)),
497            channel: original.author,
498            channel_id: original.author_id,
499            timestamp: Some(original.published),
500            published: Some(format!(
501                "{} [{}]",
502                original.published_text,
503                date_text(original.published)
504            )),
505            description: Some(original.description),
506        })
507    }
508
509    /// parse `Playlist` into `Self`
510    pub fn from_channel_playlist(original: Playlist) -> Self {
511        Self::MiniPlaylist(MiniPlaylistItem {
512            title: original.title,
513            id: original.id,
514            channel: original.author,
515            channel_id: original.author_id,
516            video_count: original.video_count,
517            thumbnail_url: original.thumbnail,
518        })
519    }
520}