17 Commits

Author SHA1 Message Date
VC
e2ab93c04e Merge branch 'fix_title_length' into 'master'
fix: truncate YT vid title to 100 chars

See merge request veretcle/tootube!17
2023-12-28 09:40:26 +00:00
VC
9e1c27be29 fix: truncate YT vid title to 100 chars 2023-12-28 10:37:23 +01:00
VC
ab9ea1a8ee Merge branch 'tamerelol' into 'master'
feat: add --vice option

See merge request veretcle/tootube!16
2023-10-26 09:06:47 +00:00
VC
66f288c069 feat: add --vice option 2023-10-25 15:33:10 +02:00
VC
b208daa0ea Merge branch 'feat/remove_max_dl' into 'master'
Refactor: remove get_max_resolution_dl

See merge request veretcle/tootube!15
2023-10-19 09:19:02 +00:00
VC
f3ad81716d refactor: remove get_max_resolution_dl (ord makes it redundant) 2023-10-19 11:12:16 +02:00
VC
f18ce899aa chore: bump version + update dep 2023-10-19 11:01:14 +02:00
VC
bf0b1c4e3f Merge branch 'refactor_dl_url' into 'master'
refactor: regroup now_kiss and get_dl_video_stream functions

See merge request veretcle/tootube!14
2023-10-17 11:57:48 +00:00
VC
eb398a880a refactor: regroup now_kiss and get_dl_video_stream functions 2023-10-17 13:55:03 +02:00
VC
1db91ec3dc Merge branch '3-progress-bar-on-the-upload-download-code-portion' into 'master'
Progress bar on the upload/download code portion

Closes #3

See merge request veretcle/tootube!13
2023-10-17 07:47:09 +00:00
VC
1d4ae8f152 feat: add progress bar to the transferring process 2023-10-17 09:33:38 +02:00
VC
58f36a56f7 chore: bump version + add indicatif/async-stream 2023-10-17 09:25:12 +02:00
VC
e17ba6cf7e Merge branch '2-tootube-should-log-moar' into 'master'
Resolve "Tootube should log moar"

Closes #2

See merge request veretcle/tootube!12
2023-10-16 19:39:00 +00:00
VC
3d53ad7bbd doc: update documentation 2023-10-16 21:36:41 +02:00
VC
3f482ff258 feat: add relevant debug bits 2023-10-16 21:23:29 +02:00
VC
ae3fa74d9b chore: bump version 2023-10-16 21:23:15 +02:00
VC
62641f526f refactor: add Ord/PartialOrd/PartialEq for PeerTubeVideoStreamingPlaylistsFiles struct 2023-10-16 21:22:47 +02:00
8 changed files with 571 additions and 305 deletions

597
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
[package]
name = "tootube"
authors = ["VC <veretcle+framagit@mateu.be>"]
version = "0.4.0"
version = "0.5.4"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -10,12 +10,13 @@ edition = "2021"
reqwest = { version = "^0.11", features = ["json", "stream", "multipart"] }
tokio = { version = "^1", features = ["full"] }
clap = "^4"
serde = { version = "1.0", features = ["derive"] }
serde = { version = "^1", features = ["derive"] }
toml = "^0.5"
log = "^0.4"
env_logger = "^0.10"
futures-core = "0.3.28"
bytes = "1.5.0"
indicatif = "^0.17"
async-stream = "^0.3"
futures-util = "^0.3"
[profile.release]
strip = true

View File

@@ -6,50 +6,57 @@ This program takes the very last video published on a PeerTube instance and push
This is an early prototype not really suited for production purposes for now:
* it still relies way too much on pre-determined value to upload the video to YouTube
* it cannot determine the playlists it needs to put them in
* it cannot determine the recording date (believe me, I tried!)
* there are still a lot of static values that I would rather not have static (like the cache directory…)
* it is 100% sync, meaning its clearly not optimal for now and probably wont be for the next releases
So consider this a work in progress that will slowly get better with time
So consider this a work in progress that will slowly get better with time.
# What does it do exactly?
* it downloads the latest PeerTube video from an instance
* stores it in cache directory
* uploads it to YouTube
* it retrieves the latest PeerTube video download URL from an instance
* it creates a resumable upload into the target YouTube account
* it downloads/uploads the latest PeerTube video to YouTube without using a cache (stream-to-stream)
# What doesnt it do exactly?
* it cannot register the original key (see below)
* it relies on a local cache despite the fact that it might well be possible to just download from PT/upload to YT at the same time (I dont see why not in fact)
* it doesnt retrieve ALL the original PeerTube video properties like licences, languages, categories, etc… again: early prototype
# Obtain Authorization Token from Google
# Howtos
## General usage
That the complicated part:
* create an OAuth2.0 application with authorization for Youtube DATA Api v3 Upload
Once you fill your `tootube.toml` config file (see below), you can run `tootube` like this:
```bash
tootube --config tootube.toml --playlist playlist_1 "Things You Might Like"
```
You can turn on debug using env var `RUST_LOG`.
## Obtain Authorization Token from Google
The complicated part:
* create an OAuth2.0 application with authorization for Youtube DATA Api v3 Upload and Youtube DATA Api v3 (generally referenced as `../auth/youtube.upload` and `../auth/youtube`)
* create a OAuth2.0 client with Desktop client
Youll need:
* the `client_id` from your OAuth2.0 client
* the `client_secret` from you OAuth2.0 client
Then enter in:
Create your `tootube.toml` config file:
```
https://accounts.google.com/o/oauth2/v2/auth?client_id=XXX.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/youtube.upload&response_type=code
```toml
[peertube]
base_url="https://p.nintendojo.fr"
[youtube]
refresh_token="" # leave empty for now
client_id="<YOUR CLIENT_ID>"
client_secret="<YOUR CLIENT_SECRET>"
```
And accept that your YouTube account might be modified. Youll get a code then; enter this `curl` post:
Then run:
```
curl -s \
--request POST \
--data "code=[THE_CODE]&client_id=XXX.apps.googleusercontent.com&client_secret=[THE_CLIENT_SECRET]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token
```bash
tootube register --config <PATH TO YOUR TOOTUBE.TOML FILE>
```
Youll get a Token. The only important part is the `refresh_token`
In your `tootube.toml` config file, put the `refresh_token`.
Youll be then prompted with all the necessary information to register `tootube`. Youll end with a `refresh_token` that you can now paste inside your tootube configuration.

View File

@@ -6,6 +6,8 @@ use std::fs::read_to_string;
pub struct Config {
pub peertube: PeertubeConfig,
pub youtube: YoutubeConfig,
#[serde(default)]
pub tootube: TootubeConfig,
}
#[derive(Debug, Deserialize)]
@@ -20,6 +22,21 @@ pub struct YoutubeConfig {
pub client_secret: String,
}
#[derive(Debug, Deserialize)]
pub struct TootubeConfig {
pub progress_bar: String,
pub progress_chars: String,
}
impl Default for TootubeConfig {
fn default() -> Self {
TootubeConfig {
progress_bar: "{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})".to_string(),
progress_chars: "#>-".to_string(),
}
}
}
/// Parses the TOML file into a Config struct
pub fn parse_toml(toml_file: &str) -> Config {
let toml_config =

View File

@@ -1,6 +1,4 @@
use bytes::Bytes;
use futures_core::stream::Stream;
use std::error::Error;
use log::debug;
mod error;
@@ -9,18 +7,12 @@ pub use config::parse_toml;
use config::Config;
mod peertube;
use peertube::{get_latest_video, get_max_resolution_dl};
use peertube::get_latest_video;
mod youtube;
pub use youtube::register;
use youtube::{add_video_to_playlists, create_resumable_upload, now_kiss};
async fn get_dl_video_stream(
u: &str,
) -> Result<impl Stream<Item = Result<Bytes, reqwest::Error>>, Box<dyn Error>> {
Ok(reqwest::get(u).await?.bytes_stream())
}
#[tokio::main]
pub async fn run(config: Config, pl: Vec<String>) {
// Get the latest video object
@@ -30,19 +22,29 @@ pub async fn run(config: Config, pl: Vec<String>) {
panic!("Cannot retrieve the latest video, something must have gone terribly wrong: {e}")
});
let dl_url = get_max_resolution_dl(latest_vid.streaming_playlists.as_ref().unwrap());
let pt_stream = get_dl_video_stream(&dl_url)
.await
.unwrap_or_else(|e| panic!("Cannot download video at URL {}: {}", dl_url, e));
let dl_url = latest_vid.streaming_playlists.as_ref().unwrap()[0]
.files
.iter()
.max()
.unwrap()
.file_download_url
.clone();
debug!("PT download URL: {}", &dl_url);
let resumable_upload_url = create_resumable_upload(&config.youtube, &latest_vid)
.await
.unwrap_or_else(|e| panic!("Cannot retrieve the uploads resumable id: {e}"));
debug!("YT upload URL: {}", &resumable_upload_url);
let yt_video_id = now_kiss(pt_stream, &resumable_upload_url, &config.youtube)
.await
.unwrap_or_else(|e| panic!("Cannot resume upload!: {e}"));
let yt_video_id = now_kiss(
&dl_url,
&resumable_upload_url,
&config.youtube,
&config.tootube,
)
.await
.unwrap_or_else(|e| panic!("Cannot resume upload!: {e}"));
debug!("YT video ID: {}", &yt_video_id);
if !pl.is_empty() {
add_video_to_playlists(&config.youtube, &yt_video_id, &pl)

View File

@@ -26,6 +26,14 @@ fn main() {
.num_args(0..)
.display_order(2),
)
.arg(
Arg::new("vice")
.long("vice")
.alias("chybrare")
.alias("coquinou")
.action(clap::ArgAction::SetTrue)
.display_order(3),
)
.subcommand(
Command::new("register")
.version(env!("CARGO_PKG_VERSION"))
@@ -50,7 +58,12 @@ fn main() {
return;
}
let config = parse_toml(matches.get_one::<String>("config").unwrap());
let mut config = parse_toml(matches.get_one::<String>("config").unwrap());
if matches.get_flag("vice") {
config.tootube.progress_bar = "{msg}\n[{elapsed_precise}] 8{wide_bar:.magenta}ᗺ {bytes}/{total_bytes} ({bytes_per_sec}, {eta})".to_string();
config.tootube.progress_chars = "=D ".to_string();
}
let playlists: Vec<String> = matches
.get_many::<String>("playlists")

View File

@@ -1,5 +1,5 @@
use serde::Deserialize;
use std::{boxed::Box, error::Error};
use std::{boxed::Box, cmp::Ordering, error::Error};
#[derive(Debug, Deserialize)]
pub struct PeerTubeVideos {
@@ -22,7 +22,7 @@ pub struct PeerTubeVideoStreamingPlaylists {
pub files: Vec<PeerTubeVideoStreamingPlaylistsFiles>,
}
#[derive(Debug, Deserialize)]
#[derive(Eq, Debug, Deserialize)]
pub struct PeerTubeVideoStreamingPlaylistsFiles {
pub id: u64,
pub resolution: PeerTubeVideoStreamingPlaylistsFilesResolution,
@@ -30,7 +30,25 @@ pub struct PeerTubeVideoStreamingPlaylistsFiles {
pub file_download_url: String,
}
#[derive(Debug, Deserialize)]
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,
}
@@ -47,21 +65,6 @@ pub async fn get_latest_video(u: &str) -> Result<PeerTubeVideo, Box<dyn Error>>
Ok(vid)
}
/// This returns the direct download URL for with the maximum resolution
pub fn get_max_resolution_dl(p: &[PeerTubeVideoStreamingPlaylists]) -> String {
let mut res = 0;
let mut dl_url = String::new();
for i in p[0].files.iter() {
if i.resolution.id > res {
res = i.resolution.id;
dl_url = i.file_download_url.clone();
}
}
dl_url
}
/// 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))
@@ -71,34 +74,3 @@ async fn get_video_detail(u: &str, v: &str) -> Result<PeerTubeVideo, Box<dyn Err
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));
}
}

View File

@@ -1,9 +1,15 @@
use crate::{config::YoutubeConfig, error::TootubeError, peertube::PeerTubeVideo};
use bytes::Bytes;
use futures_core::stream::Stream;
use crate::{
config::{TootubeConfig, YoutubeConfig},
error::TootubeError,
peertube::PeerTubeVideo,
};
use async_stream::stream;
use futures_util::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use log::{debug, warn};
use reqwest::{multipart::Form, Body, Client};
use serde::{Deserialize, Serialize};
use std::{error::Error, io::stdin};
use std::{cmp::min, error::Error, io::stdin};
use tokio::sync::OnceCell;
static ACCESS_TOKEN: OnceCell<String> = OnceCell::const_new();
@@ -207,6 +213,7 @@ async fn refresh_token(config: &YoutubeConfig) -> Result<String, reqwest::Error>
let access_token: AccessTokenResponse = res.json().await?;
debug!("YT Access Token: {}", &access_token.access_token);
Ok(access_token.access_token)
})
.await
@@ -250,6 +257,7 @@ async fn get_playlist_ids(
}
}
debug!("Playlists IDs: {:?}", &playlists);
Ok(playlists)
}
@@ -273,8 +281,8 @@ pub async fn add_video_to_playlists(
..Default::default()
},
};
let client = Client::new();
let client = Client::new();
let res = client
.post("https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet")
.header("Authorization", format!("Bearer {}", access_token))
@@ -301,10 +309,17 @@ pub async fn create_resumable_upload(
) -> Result<String, Box<dyn Error>> {
let access_token = refresh_token(config).await?;
if vid.name.chars().count() > 100 {
warn!(
"PT Video Title ({}) is too long, it will be truncated",
&vid.name
);
}
let upload_params = YoutubeUploadParams {
snippet: {
YoutubeUploadParamsSnippet {
title: vid.name.clone(),
title: vid.name.chars().take(100).collect::<String>(),
description: vid.description.clone(),
tags: vid.tags.clone(),
..Default::default()
@@ -316,6 +331,7 @@ pub async fn create_resumable_upload(
}
},
};
debug!("YT upload params: {:?}", &upload_params);
let client = Client::new();
let res = client.post("https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet%2Cstatus")
@@ -336,24 +352,53 @@ pub async fn create_resumable_upload(
}
/// This takes the PT stream for download, connects it to YT stream for upload
pub async fn now_kiss<'a>(
stream: impl Stream<Item = Result<Bytes, reqwest::Error>>
+ std::marker::Send
+ std::marker::Sync
+ 'a + 'static,
r_url: &'a str,
config: &'a YoutubeConfig,
pub async fn now_kiss(
dl_url: &str,
r_url: &str,
config: &YoutubeConfig,
pg_conf: &TootubeConfig,
) -> Result<String, Box<dyn Error>> {
// Get access token
let access_token = refresh_token(config).await?;
// Get the upstream bytes stream
let res = reqwest::get(dl_url).await?;
let content_lengh = res
.content_length()
.ok_or(format!("Cannot get content length from {}", dl_url))?;
let mut stream = res.bytes_stream();
// Create the progress bar
let pb = ProgressBar::new(content_lengh);
pb.set_style(
ProgressStyle::default_bar()
.template(&pg_conf.progress_bar)?
.progress_chars(&pg_conf.progress_chars),
);
pb.set_message("Transferring…");
let mut transferring: u64 = 0;
// yields the stream chunk by chunk, updating the progress bar at the same time
let async_stream = stream! {
while let Some(chunk) = stream.next().await {
if let Ok(chunk) = &chunk {
let new = min(transferring + (chunk.len() as u64), content_lengh);
transferring = new;
pb.set_position(new);
if transferring >= content_lengh {
pb.finish();
}
}
yield chunk;
}
};
// Create client
let client = Client::new();
let res = client
.put(r_url)
.header("Authorization", format!("Bearer {}", access_token))
.body(Body::wrap_stream(stream))
.body(Body::wrap_stream(async_stream))
.send()
.await?;