src/global/structs/item.rs

84c4617332578aaf4e9ee68a0a2d7d6258e48243
youtube-tui/src/global/structs/item.rs history · blame · raw

485 lines · 16117 bytes

36 symbols in this file
  1use crate::global::common::{
  2    channel::Channel, hidden::*, universal::Playlist as FullPlaylist, video::Video, CommonChannel,
  3    CommonPlaylist, CommonVideo,
  4};
  5use crate::global::{functions::*, traits::CollectionItem};
  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    #[allow(clippy::non_canonical_partial_ord_impl)]
 62    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
 63        // order with recent on top
 64        Some(other.cmp(self))
 65    }
 66}
 67
 68impl Ord for MiniVideoItem {
 69    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
 70        self.timestamp
 71            .unwrap_or_default()
 72            .cmp(&other.timestamp.unwrap_or_default())
 73    }
 74}
 75
 76impl PartialEq for MiniVideoItem {
 77    fn eq(&self, other: &Self) -> bool {
 78        self.id == other.id
 79    }
 80}
 81
 82/// stores information of a previewed playlist
 83#[derive(Clone, Serialize, Deserialize)]
 84pub struct MiniPlaylistItem {
 85    pub title: String,
 86    pub id: String,
 87    pub channel: String,
 88    pub channel_id: String,
 89    pub video_count: u32,
 90    pub thumbnail_url: String,
 91}
 92
 93/// stores information of a previewed channel
 94#[derive(Clone, Serialize, Deserialize)]
 95pub struct MiniChannelItem {
 96    pub name: String,
 97    pub id: String,
 98    pub thumbnail_url: String,
 99    pub sub_count: u32,
100    pub sub_count_text: String,
101    pub video_count: u32,
102    pub description: String,
103}
104
105/// stores information of a viewed video
106#[derive(Clone, Serialize, Deserialize)]
107pub struct FullVideoItem {
108    pub title: String,
109    pub id: String,
110    pub thumbnail_url: String,
111    pub length: String,
112    pub views: String,
113    pub channel: String,
114    pub channel_id: String,
115    pub sub_count: String,
116    pub published: String,
117    pub description: String,
118    pub likes: String,
119    // pub dislikes: Option<String>, TODO
120    pub genre: String,
121}
122
123/// stores information of a viewed playlist
124#[derive(Clone, Serialize, Deserialize)]
125pub struct FullPlaylistItem {
126    pub title: String,
127    pub id: String,
128    pub channel: String,
129    pub channel_id: String,
130    pub video_count: u32,
131    pub description: String,
132    pub views: String,
133    pub thumbnail_url: String,
134    pub videos: Vec<Item>,
135}
136
137/// stores information of a viewed channel
138#[derive(Clone, Serialize, Deserialize)]
139pub struct FullChannelItem {
140    pub name: String,
141    pub id: String,
142    pub thumbnail_url: String,
143    pub sub_count: u32,
144    pub sub_count_text: String,
145    pub total_views: String,
146    pub created: String,
147    pub autogenerated: bool,
148    pub description: String,
149}
150
151impl Display for Item {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.write_str(match self {
154            Self::MiniVideo(video) => &video.title,
155            Self::MiniPlaylist(playlist) => &playlist.title,
156            Self::MiniChannel(channel) => &channel.name,
157            Self::FullVideo(video) => &video.title,
158            Self::FullPlaylist(playlist) => &playlist.title,
159            Self::FullChannel(channel) => &channel.name,
160            Self::Page(b) => {
161                if *b {
162                    "Next page"
163                } else {
164                    "Previous page"
165                }
166            } // Self::Unknown(_) => "Unknown item",
167        })
168    }
169}
170
171impl Item {
172    /// returns the id of an item, `None` is self is Unknown
173    pub fn id(&self) -> Option<&str> {
174        match self {
175            Self::MiniVideo(MiniVideoItem { id, .. })
176            | Self::MiniChannel(MiniChannelItem { id, .. })
177            | Self::MiniPlaylist(MiniPlaylistItem { id, .. })
178            | Self::FullVideo(FullVideoItem { id, .. })
179            | Self::FullChannel(FullChannelItem { id, .. })
180            | Self::FullPlaylist(FullPlaylistItem { id, .. }) => Some(id),
181            Self::Page(_) => None,
182        }
183    }
184}
185
186impl Item {
187    /// stript self into a FullVideoItem
188    pub fn fullvideo(&self) -> Result<&FullVideoItem, Errors> {
189        match self {
190            Self::FullVideo(fullvideo) => Ok(fullvideo),
191            _ => Err(Errors::StrError("not a full video")),
192        }
193    }
194
195    /// stript self into a MiniVideoItem
196    pub fn minivideo(&self) -> Result<&MiniVideoItem, Errors> {
197        match self {
198            Self::MiniVideo(minivideo) => Ok(minivideo),
199            _ => Err(Errors::StrError("not a mini video")),
200        }
201    }
202
203    /// stript self into a MiniPlaylistItem
204    pub fn miniplaylist(&self) -> Result<&MiniPlaylistItem, Errors> {
205        match self {
206            Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
207            _ => Err(Errors::StrError("not a mini playlist")),
208        }
209    }
210
211    /// stript self into a FullPlaylistItem
212    pub fn fullplaylist(&self) -> Result<&FullPlaylistItem, Errors> {
213        match self {
214            Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
215            _ => Err(Errors::StrError("not a full playlist")),
216        }
217    }
218
219    /// stript self into a MiniChannelItem
220    pub fn minichannel(&self) -> Result<&MiniChannelItem, Errors> {
221        match self {
222            Self::MiniChannel(minichannel) => Ok(minichannel),
223            _ => Err(Errors::StrError("not a mini channel")),
224        }
225    }
226
227    pub fn fullchannel(&self) -> Result<&FullChannelItem, Errors> {
228        match self {
229            Self::FullChannel(fullchannel) => Ok(fullchannel),
230            _ => Err(Errors::StrError("not a full channel")),
231        }
232    }
233}
234
235impl Item {
236    /// stript self into a FullVideoItem
237    pub fn into_fullvideo(self) -> Result<FullVideoItem, Errors> {
238        match self {
239            Self::FullVideo(fullvideo) => Ok(fullvideo),
240            _ => Err(Errors::StrError("not a full video")),
241        }
242    }
243
244    /// stript self into a MiniVideoItem
245    pub fn into_minivideo(self) -> Result<MiniVideoItem, Errors> {
246        match self {
247            Self::MiniVideo(minivideo) => Ok(minivideo),
248            _ => Err(Errors::StrError("not a mini video")),
249        }
250    }
251
252    /// stript self into a MiniPlaylistItem
253    pub fn into_miniplaylist(self) -> Result<MiniPlaylistItem, Errors> {
254        match self {
255            Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
256            _ => Err(Errors::StrError("not a mini playlist")),
257        }
258    }
259
260    /// stript self into a FullPlaylistItem
261    pub fn into_fullplaylist(self) -> Result<FullPlaylistItem, Errors> {
262        match self {
263            Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
264            _ => Err(Errors::StrError("not a full playlist")),
265        }
266    }
267
268    /// stript self into a MiniChannelItem
269    pub fn into_minichannel(self) -> Result<MiniChannelItem, Errors> {
270        match self {
271            Self::MiniChannel(minichannel) => Ok(minichannel),
272            _ => Err(Errors::StrError("not a mini channel")),
273        }
274    }
275
276    pub fn into_fullchannel(self) -> Result<FullChannelItem, Errors> {
277        match self {
278            Self::FullChannel(fullchannel) => Ok(fullchannel),
279            _ => Err(Errors::StrError("not a full channel")),
280        }
281    }
282}
283
284impl Item {
285    /// returns the file save path for thumbnails (which is by their id)
286    /// returns `invalid` if the item does not have a thumbnail
287    pub fn thumbnail_id(&self) -> &str {
288        match self {
289            Self::MiniVideo(video) => &video.id,
290            Self::MiniPlaylist(playlist) => &playlist.id,
291            Self::MiniChannel(channel) => &channel.id,
292            Self::FullVideo(video) => &video.id,
293            Self::FullPlaylist(playlist) => &playlist.id,
294            Self::FullChannel(channel) => &channel.id,
295            Self::Page(_) => "invalid",
296        }
297    }
298
299    /// parse `CommonVideo` into `Self`
300    pub fn from_common_video(original: CommonVideo, image_index: usize) -> Self {
301        Self::MiniVideo(MiniVideoItem {
302            title: original.title,
303            id: original.id,
304            thumbnail_url: if original.thumbnails.is_empty() {
305                String::new()
306            } else {
307                original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
308                    .url
309                    .clone()
310            },
311            length: secs_display_string(original.length),
312            views: Some(viewcount_text(original.views)),
313            channel: original.author,
314            channel_id: original.author_id,
315            timestamp: Some(original.published),
316            published: Some(format!(
317                "{} [{}]",
318                original.published_text,
319                date_text(original.published)
320            )),
321            description: Some(original.description),
322        })
323    }
324
325    /// parse `CommonPlaylist` into `Self`
326    pub fn from_common_playlist(original: CommonPlaylist) -> Self {
327        Self::MiniPlaylist(MiniPlaylistItem {
328            title: original.title,
329            id: original.id,
330            channel: original.author,
331            channel_id: original.author_id,
332            video_count: original.video_count.max(0) as u32,
333            thumbnail_url: original.thumbnail,
334        })
335    }
336
337    /// parse `CommonChannel` into `Self`
338    pub fn from_common_channel(original: CommonChannel, image_index: usize) -> Self {
339        Self::MiniChannel(MiniChannelItem {
340            name: original.name,
341            id: original.id,
342            thumbnail_url: if !original.thumbnails.is_empty() {
343                let url = original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
344                    .url
345                    .clone();
346                if url.starts_with("https://") {
347                    url
348                } else {
349                    format!("https://{url}")
350                }
351            } else {
352                "".to_string()
353            },
354            video_count: original.video_count,
355            sub_count: original.subscribers,
356            sub_count_text: viewcount_text(original.subscribers as u64),
357            description: original.description,
358        })
359    }
360
361    /// parse `PopularItem` into `Self`
362    pub fn from_popular_item(original: PopularItem, image_index: usize) -> Self {
363        Self::MiniVideo(MiniVideoItem {
364            title: original.title,
365            id: original.id,
366            thumbnail_url: if !original.thumbnails.is_empty() {
367                original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
368                    .url
369                    .clone()
370            } else {
371                "".to_string()
372            },
373            length: secs_display_string(original.length),
374            views: Some(viewcount_text(original.views)),
375            channel: original.author,
376            channel_id: original.author_id,
377            timestamp: Some(original.published),
378            published: Some(format!(
379                "{} [{}]",
380                original.published_text,
381                date_text(original.published)
382            )),
383            description: None,
384        })
385    }
386
387    /// parse `SearchItem` into `Self`
388    pub fn from_search_item(original: SearchItem, image_index: usize) -> Self {
389        match original {
390            SearchItem::Video(vid) => Self::from_common_video(vid, image_index),
391            SearchItem::Channel(chan) => Self::from_common_channel(chan, image_index),
392            SearchItem::Playlist(list) => Self::from_common_playlist(list),
393        }
394    }
395
396    /// parse `Video` into `Self`
397    pub fn from_full_video(original: Video, image_index: usize) -> Self {
398        Self::FullVideo(FullVideoItem {
399            title: original.title,
400            id: original.id,
401            thumbnail_url: if !original.thumbnails.is_empty() {
402                original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
403                    .url
404                    .clone()
405            } else {
406                "".to_string()
407            },
408            length: secs_display_string(original.length),
409            views: viewcount_text(original.views),
410            channel: original.author,
411            channel_id: original.author_id,
412            sub_count: original.sub_count_text,
413            published: format!(
414                "{} [{}]",
415                original.published_text,
416                date_text(original.published)
417            ),
418            description: original.description,
419            likes: viewcount_text(original.likes as u64),
420            genre: original.genre,
421        })
422    }
423
424    /// parse `FullPlaylist` into `Self`
425    pub fn from_full_playlist(original: FullPlaylist, image_index: usize) -> Self {
426        Self::FullPlaylist(FullPlaylistItem {
427            title: original.title,
428            id: original.id,
429            channel: original.author,
430            channel_id: original.author_id,
431            video_count: original.video_count,
432            description: original.description,
433            views: viewcount_text(original.views),
434            thumbnail_url: original.thumbnail,
435            videos: original
436                .videos
437                .into_iter()
438                .map(|video| Self::from_playlist_item(video, image_index))
439                .collect(),
440        })
441    }
442
443    /// parse `PlaylistItem` into `Self`
444    pub fn from_playlist_item(original: PlaylistItem, image_index: usize) -> Self {
445        Self::MiniVideo(MiniVideoItem {
446            title: original.title,
447            id: original.id,
448            thumbnail_url: if !original.thumbnails.is_empty() {
449                original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
450                    .url
451                    .clone()
452            } else {
453                "".to_string()
454            },
455            length: secs_display_string(original.length),
456            views: None,
457            channel: original.author,
458            channel_id: original.author_id,
459            timestamp: None,
460            published: None,
461            description: None,
462        })
463    }
464
465    /// parse `Channel` into `Self`
466    pub fn from_full_channel(original: Channel, image_index: usize) -> Self {
467        Self::FullChannel(FullChannelItem {
468            name: original.name,
469            id: original.id,
470            thumbnail_url: if !original.thumbnails.is_empty() {
471                original.thumbnails[image_index.min(original.thumbnails.len() - 1)]
472                    .url
473                    .clone()
474            } else {
475                "".to_string()
476            },
477            sub_count: original.subscribers,
478            sub_count_text: viewcount_text(original.subscribers as u64),
479            total_views: viewcount_text(original.total_views),
480            created: date_text(original.joined),
481            autogenerated: original.auto_generated,
482            description: original.description,
483        })
484    }
485}