feat: add register command

This commit is contained in:
VC
2023-10-14 19:12:36 +02:00
parent 6867882ca0
commit 568ca00d98
3 changed files with 65 additions and 2 deletions

View File

@@ -1,9 +1,9 @@
use crate::{config::YoutubeConfig, error::TootubeError, peertube::PeerTubeVideo};
use bytes::Bytes;
use futures_core::stream::Stream;
use reqwest::{Body, Client};
use reqwest::{multipart::Form, Body, Client};
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::{error::Error, io::stdin};
use tokio::sync::OnceCell;
static ACCESS_TOKEN: OnceCell<String> = OnceCell::const_new();
@@ -34,6 +34,11 @@ struct AccessTokenResponse {
access_token: String,
}
#[derive(Deserialize, Debug)]
struct RegistrationAccessTokenResponse {
refresh_token: String,
}
#[derive(Serialize, Debug)]
struct YoutubeUploadParams {
snippet: YoutubeUploadParamsSnippet,
@@ -82,6 +87,41 @@ impl Default for YoutubeUploadParamsStatus {
}
}
/// This function makes the registration process a little bit easier
#[tokio::main]
pub async fn register(config: &YoutubeConfig) -> Result<(), Box<dyn Error>> {
println!("Click on the link below to authorize {} to upload to YouTube and deal with your playlists:", env!("CARGO_PKG_NAME"));
println!("https://accounts.google.com/o/oauth2/v2/auth?client_id={}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/youtube%20https://www.googleapis.com/auth/youtube.upload&response_type=code", config.client_id);
println!("Paste the returned authorization code:");
let mut input = String::new();
stdin()
.read_line(&mut input)
.expect("Unable to read back the authorization code!");
let form = Form::new()
.text("code", input)
.text("client_id", config.client_id.clone())
.text("client_secret", config.client_secret.clone())
.text("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
.text("grant_type", "authorization_code");
let client = Client::new();
let res = client
.post("https://accounts.google.com/o/oauth2/token")
.multipart(form)
.send()
.await?;
let refresh_token: RegistrationAccessTokenResponse = res.json().await?;
println!("You can now paste the following line inside the `youtube` section of your tootube.toml file:");
println!("refresh_token=\"{}\"", refresh_token.refresh_token);
Ok(())
}
/// Ensures that Token has been refreshed and that it is unique
async fn refresh_token(config: &YoutubeConfig) -> Result<String, reqwest::Error> {
ACCESS_TOKEN