src/global/structs/item.rs

442 lines · 14685 bytes

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