src/global/structs/rustypipe.rs

432 lines · 14439 bytes

  1use crate::global::common::{
  2    channel::Channel, hidden::SearchItem, universal::Playlist, video::Video, CommonChannel,
  3    CommonImage, CommonPlaylist, CommonThumbnail, CommonVideo,
  4};
  5use rustypipe::{
  6    client::RustyPipe,
  7    model::{
  8        richtext::{ToHtml, ToPlaintext},
  9        ChannelItem, PlaylistItem, Thumbnail, VideoItem, YouTubeItem,
 10    },
 11    param::search_filter::{ItemType, Length, Order, SearchFilter, UploadDate},
 12};
 13
 14use crate::{
 15    config::{SearchFilterDate, SearchFilterDuration, SearchFilterSort, SearchFilterType},
 16    global::{functions::viewcount_text, traits::SearchProviderTrait},
 17    RUNTIME,
 18};
 19
 20#[derive(Clone)]
 21pub struct RustyPipeWrapper(RustyPipe);
 22
 23impl Default for RustyPipeWrapper {
 24    fn default() -> Self {
 25        Self(
 26            RustyPipe::builder()
 27                .storage_dir(home::home_dir().unwrap().join(".local/share/rustypipe"))
 28                .build()
 29                .unwrap(),
 30        )
 31    }
 32}
 33
 34fn thumbnail_convert(thumb: Thumbnail) -> CommonThumbnail {
 35    CommonThumbnail {
 36        quality: "unknown".to_string(),
 37        url: thumb.url,
 38        width: thumb.width,
 39        height: thumb.height,
 40    }
 41}
 42
 43fn image_convert(thumb: Thumbnail) -> CommonImage {
 44    CommonImage {
 45        url: thumb.url,
 46        width: thumb.width,
 47        height: thumb.height,
 48    }
 49}
 50
 51fn video_item_convert(video: VideoItem) -> CommonVideo {
 52    crate::global::common::CommonVideo {
 53        title: video.name,
 54        id: video.id,
 55        author: video
 56            .channel
 57            .clone()
 58            .map(|c| c.name)
 59            .unwrap_or("Unknown channel".to_string()),
 60        author_id: video
 61            .channel
 62            .clone()
 63            .map(|c| c.id)
 64            .unwrap_or("Unknown channel id".to_string()),
 65        author_url: video
 66            .channel
 67            .map(|c| format!("https://www.youtube.com/channel/{}", c.id))
 68            .unwrap_or("Unknown channel id".to_string()),
 69        thumbnails: video.thumbnail.into_iter().map(thumbnail_convert).collect(),
 70        description: video.short_description.clone().unwrap_or_default(),
 71        description_html: video.short_description.unwrap_or_default(),
 72        views: video.view_count.unwrap_or_default(),
 73        length: video.duration.unwrap_or_default(),
 74        published: video
 75            .publish_date
 76            .map(|t| t.unix_timestamp() as u64)
 77            .unwrap_or_default(),
 78        published_text: video
 79            .publish_date_txt
 80            .unwrap_or("Unknown publish date".to_string()),
 81        premiere_timestamp: 0,
 82        live: video.is_live,
 83        premium: false,
 84        upcoming: video.is_upcoming,
 85    }
 86}
 87
 88fn playlist_item_convert(playlist: PlaylistItem) -> CommonPlaylist {
 89    crate::global::common::CommonPlaylist {
 90        title: playlist.name,
 91        id: playlist.id,
 92        thumbnail: playlist
 93            .thumbnail
 94            .into_iter()
 95            .map(|item| item.url)
 96            .collect(),
 97        author: playlist
 98            .channel
 99            .clone()
100            .map(|c| c.name)
101            .unwrap_or("Unknown channel".to_string()),
102        author_id: playlist
103            .channel
104            .clone()
105            .map(|c| c.id)
106            .unwrap_or("Unknown channel id".to_string()),
107        author_verified: playlist
108            .channel
109            .map(|c| c.verification.verified())
110            .unwrap_or_default(),
111        video_count: playlist.video_count.unwrap_or_default() as i32,
112        videos: Vec::new(),
113    }
114}
115
116fn channel_item_convert(channel: ChannelItem) -> CommonChannel {
117    crate::global::common::CommonChannel {
118        name: channel.name,
119        url: format!("https://www.youtube.com/channel/{}", channel.id),
120        id: channel.id,
121        verified: channel.verification.verified(),
122        thumbnails: channel.avatar.into_iter().map(image_convert).collect(),
123        auto_generated: false,
124        subscribers: channel.subscriber_count.unwrap_or_default() as u32,
125        video_count: 0,
126        description: channel.short_description.clone(),
127        description_html: channel.short_description,
128    }
129}
130
131impl SearchProviderTrait for RustyPipeWrapper {
132    fn supports_video(&self) -> bool {
133        true
134    }
135
136    fn video(
137        &self,
138        id: &str,
139    ) -> Result<crate::global::common::video::Video, Box<dyn std::error::Error>> {
140        let query = self.0.query();
141        let (player, details) = RUNTIME
142            .get()
143            .unwrap()
144            .block_on(async { futures::join!(query.player(id), query.video_details(id)) });
145
146        let player = player?;
147        let details = details?;
148
149        Ok(Video {
150            r#type: "video".to_string(),
151            title: player
152                .details
153                .name
154                .unwrap_or("<Unable to fetch video name>".to_string()),
155            id: player.details.id,
156            thumbnails: player
157                .details
158                .thumbnail
159                .iter()
160                .cloned()
161                .map(thumbnail_convert)
162                .collect(),
163            storyboards: Vec::new(),
164            description: details.description.to_plaintext(),
165            description_html: details.description.to_html(),
166            published: details
167                .publish_date
168                .map(|time| time.to_utc().unix_timestamp() as u64)
169                .unwrap_or_default(),
170            published_text: details
171                .publish_date_txt
172                .unwrap_or("Unknown publish date".to_string()),
173            keywords: player.details.keywords,
174            views: details.view_count,
175            likes: details.like_count.unwrap_or_default(),
176            dislikes: 0, // TODO
177            paid: false,
178            premium: false,
179            family_friendly: false,
180            allowed_regions: Vec::new(),
181            genre: String::from("Unknown genre"),
182            genre_url: None,
183            author: details.channel.name,
184            author_id: details.channel.id.clone(),
185            author_url: format!("https://www.youtube.com/channel/{}", details.channel.id),
186            author_thumbnails: details
187                .channel
188                .avatar
189                .iter()
190                .cloned()
191                .map(image_convert)
192                .collect(),
193            sub_count_text: viewcount_text(details.channel.subscriber_count.unwrap_or(0)),
194            length: player.details.duration,
195            allow_ratings: true,
196            rating: 0_f32,
197            listed: true,
198            live: player.details.is_live,
199            upcoming: false,
200            premiere_timestamp: 0,
201            dash: "No dash".to_string(),
202            adaptive_formats: Vec::new(),   // TODO
203            format_streams: Vec::new(),     // TODO
204            captions: Vec::new(),           // TODO
205            recommended_videos: Vec::new(), // TODO
206        })
207    }
208
209    fn supports_search(&self) -> bool {
210        true
211    }
212
213    fn search(
214        &self,
215        filters: &crate::config::Search,
216    ) -> Result<Vec<crate::global::common::hidden::SearchItem>, Box<dyn std::error::Error>> {
217        let date = match filters.filters.date {
218            SearchFilterDate::None => None,
219            SearchFilterDate::Hour => Some(UploadDate::Hour),
220            SearchFilterDate::Day => Some(UploadDate::Day),
221            SearchFilterDate::Week => Some(UploadDate::Week),
222            SearchFilterDate::Month => Some(UploadDate::Month),
223            SearchFilterDate::Year => Some(UploadDate::Year),
224        };
225
226        let sort = match filters.filters.sort {
227            SearchFilterSort::Relevance => None,
228            SearchFilterSort::Date => Some(Order::Date),
229            SearchFilterSort::Views => Some(Order::Views),
230            SearchFilterSort::Rating => Some(Order::Rating),
231        };
232
233        let duration = match filters.filters.duration {
234            SearchFilterDuration::None => None,
235            SearchFilterDuration::Long => Some(Length::Long),
236            SearchFilterDuration::Short => Some(Length::Short),
237            SearchFilterDuration::Medium => Some(Length::Medium),
238        };
239
240        let r#type = match filters.filters.r#type {
241            SearchFilterType::All => None,
242            SearchFilterType::Video => Some(ItemType::Video),
243            SearchFilterType::Playlist => Some(ItemType::Playlist),
244            SearchFilterType::Channel => Some(ItemType::Channel),
245        };
246
247        let res = RUNTIME.get().unwrap().block_on(
248            self.0.query().search_filter(
249                filters.query.clone(),
250                &SearchFilter::new()
251                    .date_opt(date)
252                    .sort_opt(sort)
253                    .length_opt(duration)
254                    .item_type_opt(r#type),
255            ),
256        )?;
257
258        Ok(res
259            .items
260            .items
261            .into_iter()
262            .map(|item: YouTubeItem| match item {
263                YouTubeItem::Video(video) => SearchItem::Video(video_item_convert(video)),
264                YouTubeItem::Playlist(playlist) => {
265                    SearchItem::Playlist(playlist_item_convert(playlist))
266                }
267                YouTubeItem::Channel(channel) => SearchItem::Channel(channel_item_convert(channel)),
268            })
269            .collect())
270    }
271
272    fn supports_channel(&self) -> bool {
273        true
274    }
275
276    fn channel(
277        &self,
278        id: &str,
279    ) -> Result<crate::global::common::channel::Channel, Box<dyn std::error::Error>> {
280        let q = self.0.query();
281        let (info, artist) = RUNTIME
282            .get()
283            .unwrap()
284            .block_on(async { futures::join!(q.channel_info(id), q.music_artist(id, false)) });
285
286        let info = info?;
287        let artist = artist?;
288
289        Ok(Channel {
290            name: artist.name,
291            id: info.id,
292            url: info.url,
293            banners: Vec::new(), // TODO?
294            thumbnails: artist.header_image.into_iter().map(image_convert).collect(),
295            subscribers: info.subscriber_count.unwrap_or_default() as u32,
296            total_views: info.view_count.unwrap_or_default(),
297            joined: info
298                .create_date
299                .map(|d| d.with_hms(0, 0, 0).unwrap().as_utc().unix_timestamp())
300                .unwrap_or_default() as u64,
301            auto_generated: false,
302            family_friendly: false,
303            description: info.description.clone(),
304            description_html: info.description,
305            allowed_regions: Vec::new(), // TODO
306            lastest_videos: Vec::new(),
307            related_channels: Vec::new(),
308        })
309    }
310
311    fn supports_trending(&self) -> bool {
312        true
313    }
314
315    fn trending(
316        &self,
317    ) -> Result<Vec<crate::global::common::CommonVideo>, Box<dyn std::error::Error>> {
318        let res = RUNTIME.get().unwrap().block_on(self.0.query().trending())?;
319
320        Ok(res.into_iter().map(video_item_convert).collect())
321    }
322
323    fn supports_playlist(&self) -> bool {
324        true
325    }
326
327    fn playlist(
328        &self,
329        id: &str,
330    ) -> Result<crate::global::common::universal::Playlist, Box<dyn std::error::Error>> {
331        let res = RUNTIME
332            .get()
333            .unwrap()
334            .block_on(self.0.query().playlist(id))?;
335
336        Ok(Playlist {
337            title: res.name,
338            id: res.id,
339            thumbnail: res.thumbnail.into_iter().map(|t| t.url).collect(),
340            author: res
341                .channel
342                .clone()
343                .map(|c| c.name)
344                .unwrap_or("Unknown channel".to_string()),
345            author_id: res
346                .channel
347                .clone()
348                .map(|c| c.id)
349                .unwrap_or("Unknown channel".to_string()),
350            author_thumbnails: Vec::new(), // TODO why?
351            description: res
352                .description
353                .clone()
354                .map(|t| t.to_plaintext())
355                .unwrap_or_default(),
356            description_html: res.description.map(|t| t.to_html()).unwrap_or_default(),
357            video_count: res.video_count as u32,
358            views: 0,
359            updated: res
360                .last_update
361                .map(|d| d.with_hms(0, 0, 0).unwrap().as_utc().unix_timestamp())
362                .unwrap_or_default() as u64,
363            listed: true,
364            videos: res
365                .videos
366                .items
367                .into_iter()
368                .map(|item| crate::global::common::hidden::PlaylistItem {
369                    title: item.name,
370                    id: item.id,
371                    author: res
372                        .channel
373                        .clone()
374                        .map(|c| c.name)
375                        .unwrap_or("Unknown channel".to_string()),
376                    author_id: res
377                        .channel
378                        .clone()
379                        .map(|c| c.id)
380                        .unwrap_or("Unknown channel id".to_string()),
381                    author_url: res
382                        .channel
383                        .clone()
384                        .map(|c| format!("https://www.youtube.com/channel/{}", c.id))
385                        .unwrap_or("Unknown channel id".to_string()),
386                    thumbnails: item.thumbnail.into_iter().map(thumbnail_convert).collect(),
387                    index: 0,
388                    length: res.video_count as u32,
389                })
390                .collect(),
391        })
392    }
393
394    fn supports_channel_videos(&self) -> bool {
395        true
396    }
397
398    fn channel_videos(&self, id: &str) -> Result<Vec<CommonVideo>, Box<dyn std::error::Error>> {
399        let res = RUNTIME
400            .get()
401            .unwrap()
402            .block_on(self.0.query().channel_videos(id))?;
403
404        Ok(res
405            .content
406            .items
407            .into_iter()
408            .map(video_item_convert)
409            .collect())
410    }
411
412    fn supports_channel_playlists(&self) -> bool {
413        true
414    }
415
416    fn channel_playlists(
417        &self,
418        id: &str,
419    ) -> Result<Vec<CommonPlaylist>, Box<dyn std::error::Error>> {
420        let res = RUNTIME
421            .get()
422            .unwrap()
423            .block_on(self.0.query().channel_playlists(id))?;
424
425        Ok(res
426            .content
427            .items
428            .into_iter()
429            .map(playlist_item_convert)
430            .collect())
431    }
432}