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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Video types.
//!
//! # Example
//!
//! ```rust
//! # #[async_std::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = ytextract::Client::new().await?;
//!
//! let video = client.video("nI2e-J6fsuk".parse()?).await?;
//!
//! println!("Title: {}", video.title());
//! # Ok(())
//! # }
//! ```

pub use crate::youtube::player_response::PlayabilityErrorCode;

use crate::{
    youtube::player_response::{Microformat, StreamingData, VideoDetails},
    Client, Stream, Thumbnail,
};

use serde_json::Value;

use std::{sync::Arc, time::Duration};

/// A Error that occurs when querying a [`Video`](crate::Video).
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A [`Video`] is unplayable due to a YouTube error
    #[error("{code:?}: '{reason:?}'")]
    Unplayable {
        /// The [`PlayabilityErrorCode`] returned by YouTube for processing
        code: PlayabilityErrorCode,
        /// The optional Human-readable reason for the error
        reason: Option<String>,
    },
}

/// A Video found on YouTube
///
/// # Example
///
/// ```rust
/// # #[async_std::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ytextract::Client::new().await?;
///
/// let video = client.video("nI2e-J6fsuk".parse()?).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Video {
    initial_data: Value,
    video_details: VideoDetails,
    microformat: Microformat,
    streaming_data: Option<StreamingData>,
    client: Arc<Client>,
}

impl Video {
    pub(crate) async fn get(client: Arc<Client>, id: Id) -> crate::Result<Self> {
        let player_response = client.api.player(id).await?;

        if player_response.playability_status.status.is_recoverable() {
            Ok(Self {
                initial_data: client.api.next(id).await?,
                video_details: player_response
                    .video_details
                    .expect("Recoverable error did not contain video_details"),
                microformat: player_response
                    .microformat
                    .expect("Recoverable error did not contain microformat"),
                client,
                streaming_data: player_response.streaming_data,
            })
        } else {
            Err(Error::Unplayable {
                code: player_response.playability_status.status,
                reason: player_response.playability_status.reason,
            }
            .into())
        }
    }

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

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

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

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

    /// The [`ChannelId`](crate::channel::Id) of a [`Video`]
    pub fn channel_id(&self) -> crate::channel::Id {
        self.video_details.channel_id
    }

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

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

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

    /// The [`Ratings`] of a [`Video`]
    pub fn ratings(&self) -> Ratings {
        if self.video_details.allow_ratings {
            let fixed_tooltip = self.initial_data["contents"]["twoColumnWatchNextResults"]
                ["results"]["results"]["contents"]
                .as_array()
                .expect("InitialData contents was not an array")
                .iter()
                .find_map(|v| v.get("videoPrimaryInfoRenderer"))
                .expect("InitialData contents did not have a videoPrimaryInfoRenderer")
                ["sentimentBar"]["sentimentBarRenderer"]["tooltip"]
                .as_str()
                .expect("sentimentBar tooltip was not a string")
                .replace(',', "");
            let (likes, dislikes) = fixed_tooltip
                .split_once(" / ")
                .expect("sentimentBar tooltip did not have a '/'");

            let likes = likes
                .parse()
                .expect("Likes we not parsable as a unsigned integer");
            let dislikes = dislikes
                .parse()
                .expect("Dislikes we not parsable as a unsigned integer");

            Ratings::Allowed { likes, dislikes }
        } else {
            Ratings::NotAllowed
        }
    }

    /// If a [`Video`] is private
    pub fn private(&self) -> bool {
        self.video_details.is_private
    }

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

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

    /// If a [`Video`] is age-restricted. This is the opposite of
    /// [`Video::family_safe`].
    pub fn age_restricted(&self) -> bool {
        !self.family_safe()
    }

    fn microformat(&self) -> &crate::youtube::player_response::PlayerMicroformatRenderer {
        &self.microformat.player_microformat_renderer
    }

    /// If a [`Video`] is family safe
    pub fn family_safe(&self) -> bool {
        self.microformat().is_family_safe
    }

    /// If a [`Video`] is unlisted
    pub fn unlisted(&self) -> bool {
        self.microformat().is_unlisted
    }

    /// The category a [`Video`] belongs in
    pub fn category(&self) -> &str {
        &self.microformat().category
    }

    /// The publish date of a [`Video`]
    pub fn publish_date(&self) -> chrono::NaiveDate {
        self.microformat().publish_date
    }

    /// The upload date of a [`Video`]
    pub fn upload_date(&self) -> chrono::NaiveDate {
        self.microformat().upload_date
    }

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

/// Ratings on a video
#[derive(Debug)]
pub enum Ratings {
    /// Rating is allowed
    Allowed {
        /// The amount of likes a [`Video`] received
        likes: u64,
        /// The amount of dislikes a [`Video`] received
        dislikes: u64,
    },

    /// Rating is not allowed
    NotAllowed,
}

/// A [`Id`](crate::Id) describing a Video.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Id(crate::Id<11>);

/// The [`Error`](std::error::Error) produced when a invalid [`Id`] is
/// encountered
#[derive(Debug, thiserror::Error)]
pub enum IdError {
    /// A invalid [`Id`] was found.
    ///
    /// A [`Id`] is only valid when all characters are on of:
    ///
    /// - `0..=9`
    /// - `a..=z`
    /// - `A..=Z`
    /// - `_`
    /// - `-`
    #[error("Found invalid id: '{0}'")]
    InvalidId(String),

    /// A [`Id`] had an invalid length. All [`Id`]s have to be 11 characters
    /// long
    #[error("A VideoId has to be 11 characters long but was {0} long")]
    InvalidLength(usize),
}

impl From<crate::id::Error> for IdError {
    fn from(val: crate::id::Error) -> Self {
        let crate::id::Error { expected: _, found } = val;
        IdError::InvalidLength(found)
    }
}

impl std::str::FromStr for Id {
    type Err = IdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const PREFIXES: [&str; 3] = [
            "https://www.youtube.com/watch?v=",
            "https://youtu.be/",
            "https://www.youtube.com/embed/",
        ];

        let id = PREFIXES
            .iter()
            .find_map(|prefix| s.strip_prefix(prefix))
            // No Prefix matched. Possibly naked id (OLWUqW4BRl4). Length and
            // correctness will be checked later.
            .unwrap_or(s);

        if id.chars().all(crate::id::validate_char) {
            Ok(Self(id.parse()?))
        } else {
            Err(IdError::InvalidId(s.to_string()))
        }
    }
}

impl std::fmt::Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(test)]
mod test {
    use crate::video::Ratings;

    #[async_std::test]
    async fn get() -> Result<(), Box<dyn std::error::Error>> {
        let client = crate::client::Client::new().await?;

        let video = client
            .video("https://www.youtube.com/watch?v=7B2PIVSWtJA".parse()?)
            .await?;

        assert_eq!(
            video.title(),
            "I Sent Corridor Digital the WORST VFX Workstation"
        );

        assert_eq!(video.id(), "7B2PIVSWtJA".parse()?);
        assert_eq!(video.duration(), std::time::Duration::from_secs(1358));
        assert_eq!(
            video.keywords(),
            &vec![
                "photoshop",
                "adobe",
                "1.0",
                "macintosh",
                "apple",
                "lc",
                "475",
                "quadra",
                "performa",
                "classic",
                "system 7.5",
                "macos",
                "ossc",
                "vga",
                "vfx",
                "editing",
                "challenge",
                "corridor digital",
                "collab",
                "ftp",
                "fetch",
                "icab",
                "marathon",
                "oregon trail",
                "nightmare fuel",
                "scsi2sd"
            ]
        );
        assert_eq!(video.channel_id(), "UCXuqSBlHAE6Xw-yeJA0Tunw".parse()?);
        assert_eq!(video.author(), "Linus Tech Tips");
        assert!(!video.description().is_empty());
        assert!(video.views() >= 1_068_917);

        let ratings = video.ratings();
        if let Ratings::Allowed { likes, dislikes } = ratings {
            assert!(likes >= 51_745);
            assert!(dislikes >= 622);
        } else {
            unreachable!();
        }

        assert!(!video.private());
        assert!(!video.live());
        assert!(!video.thumbnails().is_empty());
        assert!(!video.age_restricted());
        assert!(!video.unlisted());
        assert!(video.family_safe());
        assert_eq!(video.category(), "Science & Technology");
        assert_eq!(
            video.publish_date(),
            chrono::NaiveDate::from_ymd(2021, 4, 14)
        );
        assert_eq!(
            video.upload_date(),
            chrono::NaiveDate::from_ymd(2021, 4, 14)
        );

        Ok(())
    }

    #[async_std::test]
    async fn unlisted() -> Result<(), Box<dyn std::error::Error>> {
        let client = crate::client::Client::new().await?;

        let video = client
            .video("https://www.youtube.com/watch?v=9Jg_Fwc0QOY".parse()?)
            .await?;

        assert_eq!(video.title(), "youtube_explode_dart test");

        assert_eq!(video.id(), "9Jg_Fwc0QOY".parse()?);
        assert_eq!(video.duration(), std::time::Duration::from_secs(10));
        assert_eq!(video.keywords(), &Vec::<String>::new());
        assert_eq!(video.channel_id(), "UCZqdX9k5eyv1aO7i2746bXg".parse()?);
        assert_eq!(video.author(), "ATiltedTree");
        assert!(!video.description().is_empty());
        assert!(video.views() >= 6);

        let ratings = video.ratings();
        if let Ratings::Allowed { likes, dislikes } = ratings {
            assert!(likes == 0);
            assert!(dislikes == 0);
        } else {
            unreachable!();
        }

        assert!(!video.private());
        assert!(!video.live());
        assert!(!video.thumbnails().is_empty());
        assert!(!video.age_restricted());
        assert!(video.unlisted());
        assert!(video.family_safe());
        assert_eq!(video.category(), "Science & Technology");
        assert_eq!(
            video.publish_date(),
            chrono::NaiveDate::from_ymd(2021, 3, 14)
        );
        assert_eq!(
            video.upload_date(),
            chrono::NaiveDate::from_ymd(2021, 3, 14)
        );

        Ok(())
    }

    #[async_std::test]
    async fn age_restricted() -> Result<(), Box<dyn std::error::Error>> {
        let client = crate::client::Client::new().await?;

        let video = client
            .video("https://www.youtube.com/watch?v=uc8BltmHWww".parse()?)
            .await?;

        assert_eq!(video.title(), "LoL emoticonos version nopor");

        assert_eq!(video.id(), "uc8BltmHWww".parse()?);
        assert_eq!(video.duration(), std::time::Duration::from_secs(110));
        assert_eq!(video.keywords(), &Vec::<String>::new());
        assert_eq!(video.channel_id(), "UCNsCnSYsc6RT9LNxysuEwNg".parse()?);
        assert_eq!(video.author(), "lol mas18");
        assert!(!video.description().is_empty());
        assert!(video.views() >= 245_175);

        let ratings = video.ratings();
        if let Ratings::Allowed { likes, dislikes } = ratings {
            assert!(likes >= 2_724);
            assert!(dislikes >= 164);
        } else {
            unreachable!();
        }

        assert!(!video.private());
        assert!(!video.live());
        assert!(!video.thumbnails().is_empty());
        assert!(video.age_restricted());
        assert!(!video.unlisted());
        assert!(!video.family_safe());
        assert_eq!(video.category(), "People & Blogs");
        assert_eq!(
            video.publish_date(),
            chrono::NaiveDate::from_ymd(2019, 10, 8)
        );
        assert_eq!(
            video.upload_date(),
            chrono::NaiveDate::from_ymd(2019, 10, 8)
        );

        Ok(())
    }
}