src/global/structs/rustypipe.rs

432 lines · 14466 bytes

  1use invidious::{
  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    invidious::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    invidious::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    invidious::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(&self, id: &str) -> Result<invidious::video::Video, Box<dyn std::error::Error>> {
137        let query = self.0.query();
138        let (player, details) = RUNTIME
139            .get()
140            .unwrap()
141            .block_on(async { futures::join!(query.player(id), query.video_details(id)) });
142
143        let player = player?;
144        let details = details?;
145
146        Ok(Video {
147            r#type: "video".to_string(),
148            title: player
149                .details
150                .name
151                .unwrap_or("<Unable to fetch video name>".to_string()),
152            id: player.details.id,
153            thumbnails: player
154                .details
155                .thumbnail
156                .iter()
157                .cloned()
158                .map(thumbnail_convert)
159                .collect(),
160            storyboards: Vec::new(),
161            description: details.description.to_plaintext(),
162            description_html: details.description.to_html(),
163            published: details
164                .publish_date
165                .map(|time| time.to_utc().unix_timestamp() as u64)
166                .unwrap_or_default(),
167            published_text: details
168                .publish_date_txt
169                .unwrap_or("Unknown publish date".to_string()),
170            keywords: player.details.keywords,
171            views: details.view_count,
172            likes: details.like_count.unwrap_or_default(),
173            dislikes: 0, // TODO
174            paid: false,
175            premium: false,
176            family_friendly: false,
177            allowed_regions: Vec::new(),
178            genre: String::from("Unknown genre"),
179            genre_url: None,
180            author: details.channel.name,
181            author_id: details.channel.id.clone(),
182            author_url: format!("https://www.youtube.com/channel/{}", details.channel.id),
183            author_thumbnails: details
184                .channel
185                .avatar
186                .iter()
187                .cloned()
188                .map(image_convert)
189                .collect(),
190            sub_count_text: viewcount_text(details.channel.subscriber_count.unwrap_or(0)),
191            length: player.details.duration,
192            allow_ratings: true,
193            rating: 0_f32,
194            listed: true,
195            live: player.details.is_live,
196            upcoming: false,
197            premiere_timestamp: 0,
198            dash: "No dash".to_string(),
199            adaptive_formats: Vec::new(),   // TODO
200            format_streams: Vec::new(),     // TODO
201            captions: Vec::new(),           // TODO
202            recommended_videos: Vec::new(), // TODO
203        })
204    }
205
206    fn supports_search(&self) -> bool {
207        true
208    }
209
210    fn search(
211        &self,
212        filters: &crate::config::Search,
213    ) -> Result<Vec<invidious::hidden::SearchItem>, Box<dyn std::error::Error>> {
214        let date = match filters.filters.date {
215            SearchFilterDate::None => None,
216            SearchFilterDate::Hour => Some(UploadDate::Hour),
217            SearchFilterDate::Day => Some(UploadDate::Day),
218            SearchFilterDate::Week => Some(UploadDate::Week),
219            SearchFilterDate::Month => Some(UploadDate::Month),
220            SearchFilterDate::Year => Some(UploadDate::Year),
221        };
222
223        let sort = match filters.filters.sort {
224            SearchFilterSort::Relevance => None,
225            SearchFilterSort::Date => Some(Order::Date),
226            SearchFilterSort::Views => Some(Order::Views),
227            SearchFilterSort::Rating => Some(Order::Rating),
228        };
229
230        let duration = match filters.filters.duration {
231            SearchFilterDuration::None => None,
232            SearchFilterDuration::Long => Some(Length::Long),
233            SearchFilterDuration::Short => Some(Length::Short),
234            SearchFilterDuration::Medium => Some(Length::Medium),
235        };
236
237        let r#type = match filters.filters.r#type {
238            SearchFilterType::All => None,
239            SearchFilterType::Video => Some(ItemType::Video),
240            SearchFilterType::Playlist => Some(ItemType::Playlist),
241            SearchFilterType::Channel => Some(ItemType::Channel),
242        };
243
244        let res = RUNTIME.get().unwrap().block_on(
245            self.0.query().search_filter(
246                filters.query.clone(),
247                &SearchFilter::new()
248                    .date_opt(date)
249                    .sort_opt(sort)
250                    .length_opt(duration)
251                    .item_type_opt(r#type),
252            ),
253        )?;
254
255        Ok(res
256            .items
257            .items
258            .into_iter()
259            .map(|item: YouTubeItem| match item {
260                YouTubeItem::Video(video) => SearchItem::Video(video_item_convert(video)),
261                YouTubeItem::Playlist(playlist) => {
262                    SearchItem::Playlist(playlist_item_convert(playlist))
263                }
264                YouTubeItem::Channel(channel) => SearchItem::Channel(channel_item_convert(channel)),
265            })
266            .collect())
267    }
268
269    fn supports_channel(&self) -> bool {
270        true
271    }
272
273    fn channel(&self, id: &str) -> Result<invidious::channel::Channel, Box<dyn std::error::Error>> {
274        let q = self.0.query();
275        let (info, artist) = RUNTIME
276            .get()
277            .unwrap()
278            .block_on(async { futures::join!(q.channel_info(id), q.music_artist(id, false)) });
279
280        let info = info?;
281        let artist = artist?;
282
283        Ok(Channel {
284            name: artist.name,
285            id: info.id,
286            url: info.url,
287            banners: Vec::new(), // TODO?
288            thumbnails: artist.header_image.into_iter().map(image_convert).collect(),
289            subscribers: info.subscriber_count.unwrap_or_default() as u32,
290            total_views: info.view_count.unwrap_or_default(),
291            joined: info
292                .create_date
293                .map(|d| d.with_hms(0, 0, 0).unwrap().as_utc().unix_timestamp())
294                .unwrap_or_default() as u64,
295            auto_generated: false,
296            family_friendly: false,
297            description: info.description.clone(),
298            description_html: info.description,
299            allowed_regions: Vec::new(), // TODO
300            lastest_videos: Vec::new(),
301            related_channels: Vec::new(),
302        })
303    }
304
305    fn supports_popular(&self) -> bool {
306        false
307    }
308
309    fn popular(&self) -> Result<Vec<invidious::hidden::PopularItem>, Box<dyn std::error::Error>> {
310        unimplemented!("not supported")
311    }
312
313    fn supports_trending(&self) -> bool {
314        true
315    }
316
317    fn trending(&self) -> Result<Vec<invidious::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<invidious::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| invidious::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}