refactor: regroup now_kiss and get_dl_video_stream functions

This commit is contained in:
VC
2023-10-17 13:55:03 +02:00
parent 1db91ec3dc
commit eb398a880a
4 changed files with 20 additions and 39 deletions

View File

@@ -1,17 +1,11 @@
use crate::{config::YoutubeConfig, error::TootubeError, peertube::PeerTubeVideo};
use async_stream::stream;
use bytes::Bytes;
use futures_util::{Stream, StreamExt};
use futures_util::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use log::debug;
use reqwest::{multipart::Form, Body, Client};
use serde::{Deserialize, Serialize};
use std::{
cmp::min,
error::Error,
io::stdin,
marker::{Send, Sync, Unpin},
};
use std::{cmp::min, error::Error, io::stdin};
use tokio::sync::OnceCell;
static ACCESS_TOKEN: OnceCell<String> = OnceCell::const_new();
@@ -347,30 +341,37 @@ 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>(
size: u64,
mut stream: impl Stream<Item = Result<Bytes, reqwest::Error>> + Send + Sync + Unpin + 'a + 'static,
r_url: &'a str,
config: &'a YoutubeConfig,
pub async fn now_kiss(
dl_url: &str,
r_url: &str,
config: &YoutubeConfig,
) -> 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(size);
let pb = ProgressBar::new(content_lengh);
pb.set_style(ProgressStyle::default_bar()
.template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")?
.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), size);
let new = min(transferring + (chunk.len() as u64), content_lengh);
transferring = new;
pb.set_position(new);
if transferring >= size {
if transferring >= content_lengh {
pb.finish();
}
}