Files
tootube/src/peertube.rs

113 lines
3.5 KiB
Rust

use serde::Deserialize;
use std::{boxed::Box, cmp::Ordering, error::Error};
#[derive(Debug, Deserialize)]
pub struct PeerTubeVideos {
pub total: u64,
pub data: Vec<PeerTubeVideo>,
}
#[derive(Debug, Deserialize)]
pub struct PeerTubeVideo {
pub name: String,
pub uuid: String,
pub description: String,
#[serde(rename = "streamingPlaylists")]
pub streaming_playlists: Option<Vec<PeerTubeVideoStreamingPlaylists>>,
pub tags: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
pub struct PeerTubeVideoStreamingPlaylists {
pub files: Vec<PeerTubeVideoStreamingPlaylistsFiles>,
}
#[derive(Eq, Debug, Deserialize)]
pub struct PeerTubeVideoStreamingPlaylistsFiles {
pub id: u64,
pub resolution: PeerTubeVideoStreamingPlaylistsFilesResolution,
#[serde(rename = "fileDownloadUrl")]
pub file_download_url: String,
}
impl Ord for PeerTubeVideoStreamingPlaylistsFiles {
fn cmp(&self, other: &Self) -> Ordering {
self.resolution.id.cmp(&other.resolution.id)
}
}
impl PartialOrd for PeerTubeVideoStreamingPlaylistsFiles {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for PeerTubeVideoStreamingPlaylistsFiles {
fn eq(&self, other: &Self) -> bool {
self.resolution.id == other.resolution.id
}
}
#[derive(Eq, Debug, Deserialize, PartialEq)]
pub struct PeerTubeVideoStreamingPlaylistsFilesResolution {
pub id: u16,
}
/// This gets the last video uploaded to the PeerTube server
pub async fn get_latest_video(u: &str) -> Result<PeerTubeVideo, Box<dyn Error>> {
let body = reqwest::get(format!("{}/api/v1/videos?count=1&sort=-publishedAt", u))
.await?
.json::<PeerTubeVideos>()
.await?;
let vid = get_video_detail(u, &body.data[0].uuid).await?;
Ok(vid)
}
/// This returns the direct download URL for with the maximum resolution
pub fn get_max_resolution_dl(p: &[PeerTubeVideoStreamingPlaylists]) -> String {
p[0].files.iter().max().unwrap().file_download_url.clone()
}
/// This gets all the crispy details about one particular video
async fn get_video_detail(u: &str, v: &str) -> Result<PeerTubeVideo, Box<dyn Error>> {
let body = reqwest::get(format!("{}/api/v1/videos/{}", u, v))
.await?
.json::<PeerTubeVideo>()
.await?;
Ok(body)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_max_resolution_dl() {
let str_plist: Vec<PeerTubeVideoStreamingPlaylists> =
vec![PeerTubeVideoStreamingPlaylists {
files: vec![
PeerTubeVideoStreamingPlaylistsFiles {
id: 1025,
resolution: PeerTubeVideoStreamingPlaylistsFilesResolution { id: 990 },
file_download_url: "meh!".to_string(),
},
PeerTubeVideoStreamingPlaylistsFiles {
id: 1027,
resolution: PeerTubeVideoStreamingPlaylistsFilesResolution { id: 1720 },
file_download_url: "blah".to_string(),
},
PeerTubeVideoStreamingPlaylistsFiles {
id: 1026,
resolution: PeerTubeVideoStreamingPlaylistsFilesResolution { id: 360 },
file_download_url: "nope".to_string(),
},
],
}];
assert_eq!("blah".to_string(), get_max_resolution_dl(&str_plist));
}
}