1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//! Videos.
//!
//! Videos are identified by a unique [`Id`], and can be queried with a
//! [`Client`](crate::Client).
//!
//! Once you have a [`Video`] you can use [`Video::streams`] to get its
//! [`Streams`](crate::Stream). These contain URLs to download videos,
//! along with metadata about dimensions and fps.
//!
//! # Example
//!
//! ```rust
//! # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = ytextract::Client::new();
//!
//! let video = client.video("nI2e-J6fsuk".parse()?).await?;
//!
//! println!("Title: {}", video.title());
//! # Ok(())
//! # }
//! ```

pub mod related;

use crate::{
    youtube::{innertube::Next, next, player_response::PlayerResponse},
    Client, Stream, Thumbnail,
};

use std::time::Duration;

/// A Video.
///
/// For more information see the [crate level documentation](crate::video)
#[derive(Clone)]
pub struct Video {
    player_response: PlayerResponse,
    initial_data: next::Root,
    client: Client,
}

impl Video {
    pub(crate) async fn get(client: Client, id: Id) -> crate::Result<Self> {
        Ok(Self {
            player_response: client.api.player(id).await?.into_std()?,
            initial_data: client.api.next(Next::Video(id)).await?,
            client,
        })
    }

    /// The title of a [`Video`].
    pub fn title(&self) -> &str {
        &self.player_response.video_details.title
    }

    /// The [`Id`] of a [`Video`].
    pub fn id(&self) -> Id {
        self.player_response.video_details.video_id
    }

    /// The [`Duration`] of a [`Video`].
    pub fn duration(&self) -> Duration {
        self.player_response.video_details.length_seconds
    }

    /// The keyword/tags of a [`Video`].
    pub fn keywords(&self) -> &Vec<String> {
        &self.player_response.video_details.keywords
    }

    /// The [`Channel`] of a [`Video`].
    pub fn channel(&self) -> Channel<'_> {
        let owner = &self
            .initial_data
            .contents
            .two_column_watch_next_results
            .results
            .results
            .secondary()
            .owner
            .video_owner_renderer;
        Channel {
            client: &self.client,
            id: self.player_response.video_details.channel_id,
            name: &self.player_response.video_details.author,
            subscribers: owner.subscribers(),
            thumbnails: owner.thumbnails(),
        }
    }

    /// The description of a [`Video`].
    pub fn description(&self) -> &str {
        &self.player_response.video_details.short_description
    }

    /// The amount of views a [`Video`] received.
    pub fn views(&self) -> u64 {
        self.player_response.video_details.view_count
    }

    /// The amount of likes a [`Video`] received.
    pub fn likes(&self) -> Option<u64> {
        self.initial_data
            .contents
            .two_column_watch_next_results
            .results
            .results
            .primary()
            .likes()
    }

    /// The hashtags a [`Video`] is tagged with.
    pub fn hashtags(&self) -> impl Iterator<Item = &str> {
        self.initial_data
            .contents
            .two_column_watch_next_results
            .results
            .results
            .primary()
            .hashtags()
    }

    /// If a [`Video`] is live (e.g. a Livestream) or if it was live in the
    /// past.
    pub fn live(&self) -> bool {
        self.player_response.video_details.is_live_content
    }

    /// The [`Thumbnails`](Thumbnail) of a [`Video`]
    pub fn thumbnails(&self) -> &Vec<Thumbnail> {
        &self.player_response.video_details.thumbnail.thumbnails
    }

    /// The date a [`Video`] was published.
    pub fn date(&self) -> chrono::NaiveDate {
        self.initial_data
            .contents
            .two_column_watch_next_results
            .results
            .results
            .primary()
            .date()
    }

    /// The [`Items`](Related) related to a [`Video`].
    pub fn related(&self) -> Option<impl futures_core::Stream<Item = Related>> {
        let initial_items = self
            .initial_data
            .contents
            .two_column_watch_next_results
            .secondary_results
            .as_ref()?
            .secondary_results
            .items()?;
        let client = self.client.clone();

        Some(async_stream::stream! {
            let mut items: Box<dyn Iterator<Item = next::SectionItem> + Send + Sync> =
                Box::new(initial_items);

            while let Some(item) = items.next() {
                match item {
                    next::SectionItem::ContinuationItemRenderer(continuation) => {
                        assert!(
                            items.next().is_none(),
                            "Found a continuation in the middle of items!"
                        );
                        let response: next::Continuation = client
                            .api
                            .next(Next::Continuation(continuation.get()))
                            .await
                            .expect("Continuation request failed");

                        items = Box::new(response.into_videos());
                    }
                    next::SectionItem::CompactVideoRenderer(video) => {
                        yield Related::Video(related::Video(video, client.clone()));
                    }
                    next::SectionItem::CompactPlaylistRenderer(playlist) => {
                        yield Related::Playlist(related::Playlist(playlist, client.clone()));
                    }
                    next::SectionItem::CompactRadioRenderer(radio) => {
                        yield Related::Radio(related::Radio(radio, client.clone()));
                    }
                    next::SectionItem::CompactMovieRenderer(movie) => {
                        yield Related::Movie(related::Movie(movie, client.clone()));
                    },
                    // I don't know what this is - just skip it
                    next::SectionItem::Other => continue,
                }
            }
        })
    }

    /// The [`Streams`](Stream) of a [`Video`]
    pub async fn streams(&self) -> crate::Result<impl Iterator<Item = Stream>> {
        crate::stream::get(self.client.clone(), self.id()).await
    }
}

impl std::fmt::Debug for Video {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Video")
            .field("id", &self.id())
            .field("title", &self.title())
            .field("duration", &self.duration())
            .field("keywords", &self.keywords())
            .field("channel", &self.channel())
            .field("description", &self.description())
            .field("views", &self.views())
            .field("likes", &self.likes())
            .field("live", &self.live())
            .field("thumbnails", &self.thumbnails())
            .field("date", &self.date())
            .finish()
    }
}

impl PartialEq for Video {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl Eq for Video {}

/// The uploader of a video
pub struct Channel<'a> {
    client: &'a Client,
    id: crate::channel::Id,
    name: &'a str,
    subscribers: Option<u64>,
    thumbnails: &'a Vec<Thumbnail>,
}

impl<'a> Channel<'a> {
    /// The [`Id`](crate::channel::Id) of a [`Channel`]
    pub fn id(&self) -> crate::channel::Id {
        self.id
    }

    /// The name of a [`Channel`]
    pub fn name(&self) -> &str {
        self.name
    }

    /// The amount of subscribers a [`Channel`] has.
    pub fn subscribers(&self) -> Option<u64> {
        self.subscribers
    }

    /// The [`Thumbnails`](Thumbnail) of a [`Channel`]
    pub fn thumbnails(&self) -> impl Iterator<Item = &Thumbnail> {
        self.thumbnails.iter()
    }

    /// Refetch the channel to get more information
    pub async fn upgrade(&self) -> crate::Result<crate::Channel> {
        self.client.channel(self.id).await
    }
}

impl<'a> std::fmt::Debug for Channel<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Channel")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("subscribers", &self.subscribers)
            .field("thumbnails", &self.thumbnails)
            .finish()
    }
}

impl<'a> PartialEq for Channel<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl<'a> Eq for Channel<'a> {}

define_id! {
    11,
    "An Id describing a [`Video`]",
    [
        "watch?v=",
        "embed/",
    ]
}

/// A Item that is related to a [`Video`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Related {
    /// A Video
    Video(related::Video),

    /// A Playlist
    Playlist(related::Playlist),

    /// A Movie
    Movie(related::Movie),

    /// A Radio
    Radio(related::Radio),
}