Browse Source

more structure

main
Georg Hopp 11 months ago
parent
commit
68ca3e1e97
Signed by: ghopp GPG Key ID: 4C5D226768784538
  1. 2
      Cargo.toml
  2. 319
      src/client.rs
  3. 31
      src/client/data.rs
  4. 127
      src/client/download.rs
  5. 10
      src/client/error.rs
  6. 69
      src/client/message.rs
  7. 56
      src/client/util.rs
  8. 18
      src/main.rs

2
Cargo.toml

@ -15,7 +15,7 @@ m3u8-rs = "6.0"
reqwest = "0.12"
shellwords = "1.1"
tokio = { version = "1.42", features = [ "macros", "rt", "rt-multi-thread" ] }
tower = { version = "0.5", features = [ "limit", "timeout" ] }
tower = { version = "0.5", features = [ "buffer", "limit", "timeout" ] }
tower-http = { version = "0.6", features = [
"decompression-br",
"decompression-deflate",

319
src/client.rs

@ -1,88 +1,62 @@
use std::{collections::HashMap, io::ErrorKind, path::{Path, PathBuf}, time::Duration};
mod download;
mod data;
mod util;
mod error;
mod message;
use anyhow::anyhow;
use futures_util::StreamExt as _;
use std::{collections::HashMap, path::Path, time::Duration};
use error::ClientError;
use http::{
header::{CONTENT_LENGTH, CONTENT_TYPE, RANGE},
request::Builder as RequestBuilder,
HeaderMap,
HeaderValue,
Request,
Response,
StatusCode,
Uri
};
use http_body_util::BodyDataStream;
use message::{ClientActorMessage, ClientActorMessageHandle};
use reqwest::{redirect::Policy, Body};
use tokio::{
fs::{symlink_metadata, File},
io::AsyncWriteExt as _,
select,
sync::{mpsc, oneshot},
task::JoinSet,
time::timeout
};
use tower::{util::BoxCloneService, ServiceBuilder, ServiceExt as _};
use tower_http::decompression::{DecompressionBody, DecompressionLayer};
use tower_http_client::{client::BodyReader, ServiceExt as _};
use tower_reqwest::HttpClientLayer;
use crate::download_error::DownloadError;
use log::{debug, error, info};
macro_rules! dlerror {
#[macro_export]
macro_rules! mk_dlerror {
($message:ident, $($err:tt)*) => {{
DownloadError::new( $message.clone()
, Some(anyhow!($($err)*) ))
use $crate::client::error;
error::ClientError::new( $message.clone()
, Some(anyhow::anyhow!($($err)*) ))
}};
}
#[derive(Debug)]
pub(super) enum ClientActorMessage {
Download {
filename: PathBuf,
uri: Uri,
respond_to: oneshot::Sender<DownloadResult>,
},
GetData {
uri: Uri,
respond_to: oneshot::Sender<Option<Vec<u8>>>,
},
#[macro_export]
macro_rules! map_dlerror {
($message:ident) => {{
use $crate::client::error;
|e| error::ClientError::new( $message.clone()
, Some(anyhow::anyhow!(e) ))
}};
}
#[derive(Clone, Debug)]
pub(super) enum ClientActorMessageHandle {
Download {
filename: PathBuf,
uri: Uri,
state: Option<DownloadState>,
message: ActionIndex,
},
GetData {
uri: Uri,
buffer: Option<Vec<u8>>,
message: ActionIndex,
},
}
#[derive(Clone, Debug)]
pub enum DownloadState {
#[allow(dead_code)]
GotHead { content_type: Option<String> },
#[allow(dead_code)]
Responded { content_type: Option<String> },
GotHead,
#[allow(dead_code)]
Partial { content_type: Option<String> },
Done { content_type: Option<String> },
}
pub(super) type ActionIndex = u64;
type DownloadResult = Result<Option<DownloadState>, DownloadError>;
type JoinSetResult = Result<Option<ClientActorMessageHandle>, DownloadError>;
type ActionIndex = u64;
type DownloadResult = Result<Option<DownloadState>, ClientError>;
type JoinSetResult = Result<Option<ClientActorMessageHandle>, ClientError>;
type HttpClient = BoxCloneService<Request<Body>, Response<DecompressionBody<Body>>, anyhow::Error>;
@ -107,6 +81,8 @@ async fn run_client(mut actor: ClientActor) {
loop {
select! {
Some(join) = actor.tasks.join_next() => {
use ClientActorMessageHandle::{Download, GetData};
match join {
Err(e) => {
error!("FATAL Join failed: {}", e);
@ -119,21 +95,25 @@ async fn run_client(mut actor: ClientActor) {
// with something that in turn would be used to retry...
let client = actor.client.clone();
actor.tasks.spawn(async move {
download(client, e.action, actor.timeout).await
match e.action {
Download { .. } =>
download::download(client, e.action, actor.timeout).await,
GetData { .. } =>
data::data(client, e.action).await,
}
});
},
// when the task finishes
Ok(Ok(Some(action))) => {
use ClientActorMessageHandle::{Download, GetData};
match action {
Download { filename: _, ref uri, state, ref message } => {
info!("Done download: {:?}", uri);
if let Some((_, message)) = actor.actions.remove_entry(message) {
use ClientActorMessage::Download;
match message {
Download { filename: _, uri: _, respond_to } => {
Download { respond_to, .. } => {
let _ = respond_to.send(Ok(state));
},
_ => panic!("Wrong variant ... this should never happen"),
@ -148,7 +128,7 @@ async fn run_client(mut actor: ClientActor) {
if let Some((_, message)) = actor.actions.remove_entry(message) {
use ClientActorMessage::GetData;
match message {
GetData { uri: _, respond_to } => {
GetData { respond_to, .. } => {
let _ = respond_to.send(buffer);
},
_ => panic!("Wrong variant ... this should never happen"),
@ -175,223 +155,19 @@ async fn run_client(mut actor: ClientActor) {
}
}
async fn file_size(filename: &Path) -> u64 {
// - get all informations to eventually existing file
let metadata = match symlink_metadata(filename).await {
Ok(metadata) => Some(metadata),
Err(error) => match error.kind() {
// If we can't write to a file we need to ... well theres nothing we can do
ErrorKind::PermissionDenied => panic!("Permission denied on: {:?}", filename),
_ => None,
}
};
metadata.map_or(0, |m| m.len())
}
async fn request( client: &mut HttpClient
, method: &str
, uri: &Uri
, headers: HeaderMap ) -> anyhow::Result<Response<DecompressionBody<Body>>> {
let mut request = RequestBuilder::new()
. method(method)
. uri(uri)
. body(Body::default())?;
request.headers_mut().extend(headers);
debug!("Request: {:?}", request);
let response = client.execute(request).await?;
debug!("Response: {:?}", response.headers());
anyhow::ensure!( response.status().is_success()
, "resonse status failed: {}"
, response.status() );
Ok(response)
}
async fn content_info( client: &mut HttpClient
, uri: &Uri ) -> anyhow::Result<(Option<u64>, Option<String>)> {
let head = request(client, "HEAD", uri, HeaderMap::new()).await?;
let content_length = head
. headers()
. get(CONTENT_LENGTH)
. map(|v| v . to_str()
. expect("unable to get CONTENT-LENGTH value")
. parse::<u64>()
. expect("unable to parse CONTENT-LENGTH value"));
let content_type = head
. headers()
. get(CONTENT_TYPE)
. map(|v| v . to_str()
. expect("unable to get CONTENT-LENGTH value")
. to_string());
Ok((content_length, content_type))
}
async fn open_outfile(status: &StatusCode, filename: &Path) -> File {
match status {
&StatusCode::PARTIAL_CONTENT =>
// Here we assume that this response only comes if the requested
// range was fullfillable and thus is the data range in the
// response. Thats why I do not check the content-range header.
// If that assumption does not hold this needs to be fixec.
File::options() . create(true)
. append(true)
. open(filename)
. await
. expect("can not create file for writing"),
_ =>
File::create(filename) . await
. expect("can not create file for writing"),
}
}
async fn store_body( file: &mut File
, body: &mut DecompressionBody<Body>
, io_timeout: Duration ) -> anyhow::Result<()> {
let mut body = BodyDataStream::new(body);
loop {
// give timeout somehow... probably from client.
let data = timeout(io_timeout, body.next()).await?;
match data {
None => break,
Some(Err(e)) => {
return Err(anyhow!(e.to_string()));
}
Some(Ok(data)) => {
file . write_all(data.as_ref()).await?;
file . flush().await?;
},
}
};
Ok(())
}
async fn download( mut client: HttpClient
, mut message: ClientActorMessageHandle
, io_timeout: Duration ) -> JoinSetResult {
use ClientActorMessageHandle::Download;
let (filename, uri) =
if let Download { ref filename, ref uri, state: _, message: _ } = message {
(filename, uri)
} else {
Err(dlerror!(message, "Called with invalid variant"))?
};
// - get all informations to eventually existing file
let mut from = file_size(filename).await;
// - get infos to uri
let ( content_length
, content_type ) = content_info(&mut client, uri).await
. map_err(|e| dlerror!(message, e))?;
if let Download { filename: _, uri: _, ref mut state, message: _ } = message {
let content_type = content_type.clone();
*state = Some(DownloadState::GotHead { content_type });
} else {
Err(dlerror!(message, "Called with invalid variant"))?;
}
if let Some(content_length) = content_length {
if from != 0 && content_length - 1 <= from {
return Ok(None);
}
} else {
from = 0;
}
// - do the neccessry request.
let range_value: HeaderValue = format!("bytes={}-", from)
. parse()
. expect("Error creating range header value");
let mut headers = HeaderMap::new();
headers.insert(RANGE, range_value);
let mut response = request(&mut client, "GET", uri, headers).await
. map_err(|e| dlerror!(message, e))?;
if let Download { filename: _, uri: _, ref mut state, message: _ } = message {
let content_type = content_type.clone();
*state = Some(DownloadState::Responded { content_type });
} else {
Err(dlerror!(message, "Called with invalid variant"))?;
}
// - open or create file
// - download Data
store_body( &mut open_outfile(&response.status(), filename).await
, response.body_mut()
, io_timeout )
. await
. map_err(|e| dlerror!(message, e))?;
if let Download { filename: _, uri: _, ref mut state, message: _ } = message {
let content_type = content_type.clone();
*state = Some(DownloadState::Done { content_type });
} else {
Err(dlerror!(message, "Called with invalid variant"))?;
}
Ok(Some(message))
}
pub(super) async fn body_bytes( mut client: HttpClient
, mut message: ClientActorMessageHandle ) -> JoinSetResult {
use ClientActorMessageHandle::GetData;
let uri = if let GetData { ref uri, buffer: _, message: _ } = message {
uri
} else {
Err(dlerror!(message, "Called with invalid variant"))?
};
let mut response = request( &mut client
, "GET"
, uri
, HeaderMap::new() )
. await
. map_err(|e| dlerror!(message, e))?;
// read body into Vec<u8>
let body: Vec<u8> = BodyReader::new(response.body_mut())
. bytes()
. await
. map_err(|e| dlerror!(message, e))?
. to_vec();
let buffer =
if let GetData { uri: _, ref mut buffer, message: _ } = message {
buffer
} else {
Err(dlerror!(message, "Called with invalid variant"))?
};
*buffer = Some(body);
Ok(Some(message))
}
impl ClientActor {
pub(super) fn new( concurrency_limit: usize
pub(super) fn new( buffer: usize
, rate_limit: u64
, concurrency_limit: usize
, timeout: Duration
, receiver: mpsc::Receiver<ClientActorMessage>
, abort_rx: oneshot::Receiver<JoinSetResult> ) -> anyhow::Result<Self> {
let client = ServiceBuilder::new()
// Add some layers.
. buffer(buffer)
. rate_limit(rate_limit, Duration::from_secs(1))
. concurrency_limit(concurrency_limit)
. timeout(timeout)
. layer(DecompressionLayer::new())
@ -437,7 +213,7 @@ impl ClientActor {
};
self.tasks.spawn(async move {
download(client, handle, timeout).await
download::download(client, handle, timeout).await
});
self.actions_idx += 1;
@ -454,7 +230,7 @@ impl ClientActor {
};
self.tasks.spawn(async move {
body_bytes(client, handle).await
data::data(client, handle).await
});
self.actions_idx += 1;
@ -466,10 +242,15 @@ impl ClientActor {
}
impl ClientActorHandle {
pub(super) fn new(concurrency: usize, timeout: Duration) -> Self {
pub(super) fn new( buffer: usize
, rate_limit: u64
, concurrency_limit: usize
, timeout: Duration ) -> Self {
let (sender, receiver) = mpsc::channel(1);
let (abort, abort_rx) = oneshot::channel::<JoinSetResult>();
let actor = ClientActor::new( concurrency
let actor = ClientActor::new( buffer
, rate_limit
, concurrency_limit
, timeout
, receiver
, abort_rx )

31
src/client/data.rs

@ -0,0 +1,31 @@
use http::HeaderMap;
use tower_http_client::client::BodyReader;
use crate::map_dlerror;
use super::{util, ClientActorMessageHandle, HttpClient, JoinSetResult};
pub(super) async fn data( mut client: HttpClient
, mut message: ClientActorMessageHandle ) -> JoinSetResult {
let uri = message.uri();
let mut response = util::request( &mut client
, "GET"
, &uri
, HeaderMap::new() )
. await
. map_err(map_dlerror!(message))?;
// read body into Vec<u8>
let body: Vec<u8> = BodyReader::new(response.body_mut())
. bytes()
. await
. map_err(map_dlerror!(message))?
. to_vec();
let buffer = message.buffer_mut();
*buffer = Some(body);
Ok(Some(message))
}

127
src/client/download.rs

@ -0,0 +1,127 @@
use std::{io::ErrorKind, path::Path, time::Duration};
use anyhow::anyhow;
use futures_util::StreamExt as _;
use http::{header::RANGE, HeaderMap, StatusCode};
use http_body_util::BodyDataStream;
use reqwest::Body;
use tokio::{
fs::{symlink_metadata, File},
io::AsyncWriteExt as _,
time::timeout
};
use tower_http::decompression::DecompressionBody;
use crate::map_dlerror;
use super::{
util,
ClientActorMessageHandle,
DownloadState,
HttpClient,
JoinSetResult,
};
pub(super) async fn download( mut client: HttpClient
, mut message: ClientActorMessageHandle
, io_timeout: Duration ) -> JoinSetResult {
let filename = message.filename();
let uri = message.uri();
// - get all informations to eventually existing file
let mut from = file_size(&filename).await;
// - get infos to uri
let headers = util::head(&mut client, &uri).await
. map_err(map_dlerror!(message))?;
let content_length = util::content_length(&headers).ok();
let content_type = util::content_type(&headers).ok();
message.set_state(DownloadState::GotHead);
if let Some(content_length) = content_length {
if from != 0 && content_length - 1 <= from {
return Ok(None);
}
} else {
from = 0;
}
// - do the neccessry request.
let mut headers = HeaderMap::new();
headers.insert(RANGE, format!("bytes={}-", from).parse().unwrap());
let mut response = util::request(&mut client, "GET", &uri, headers).await
. map_err(map_dlerror!(message))?;
// - open or create file
// - download Data
store_body( &mut open_outfile(&response.status(), &filename).await
, response.body_mut()
, io_timeout )
. await
. map_err(map_dlerror!(message))?;
message.set_state(DownloadState::Done { content_type });
Ok(Some(message))
}
async fn file_size(filename: &Path) -> u64 {
// - get all informations to eventually existing file
let metadata = match symlink_metadata(filename).await {
Ok(metadata) => Some(metadata),
Err(error) => match error.kind() {
// If we can't write to a file we need to ... well theres nothing we can do
ErrorKind::PermissionDenied => panic!("Permission denied on: {:?}", filename),
_ => None,
}
};
metadata.map_or(0, |m| m.len())
}
async fn open_outfile(status: &StatusCode, filename: &Path) -> File {
match status {
&StatusCode::PARTIAL_CONTENT =>
// Here we assume that this response only comes if the requested
// range can be fullfilled and thus is the data range in the
// response. Thats why I do not check the content-range header.
// If that assumption does not hold this needs to be fixed.
File::options() . create(true)
. append(true)
. open(filename)
. await
. expect("can not create file for writing"),
_ =>
File::create(filename) . await
. expect("can not create file for writing"),
}
}
async fn store_body( file: &mut File
, body: &mut DecompressionBody<Body>
, io_timeout: Duration ) -> anyhow::Result<()> {
let mut body = BodyDataStream::new(body);
loop {
// give timeout somehow... probably from client.
let data = timeout(io_timeout, body.next()).await?;
match data {
None => break,
Some(Err(e)) => {
return Err(anyhow!(e));
}
Some(Ok(data)) => {
file . write_all(data.as_ref()).await?;
file . flush().await?;
},
}
};
Ok(())
}

10
src/download_error.rs → src/client/error.rs

@ -1,16 +1,16 @@
use std::{error, fmt};
use crate::client::ClientActorMessageHandle;
use super::ClientActorMessageHandle;
#[derive(Debug)]
pub(super) struct DownloadError {
pub(crate) struct ClientError {
pub(super) action: ClientActorMessageHandle,
pub(super) source: Option<anyhow::Error>,
}
impl DownloadError {
impl ClientError {
pub(super) fn new( action: ClientActorMessageHandle
, source: Option<anyhow::Error> ) -> Self {
let action = action.to_owned();
@ -18,7 +18,7 @@ impl DownloadError {
}
}
impl error::Error for DownloadError {
impl error::Error for ClientError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.source {
None => None,
@ -27,7 +27,7 @@ impl error::Error for DownloadError {
}
}
impl fmt::Display for DownloadError {
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
None => write!(f, "download error: {:?}", self.action),

69
src/client/message.rs

@ -0,0 +1,69 @@
use std::path::PathBuf;
use http::Uri;
use tokio::sync::oneshot;
use super::{ActionIndex, DownloadResult, DownloadState};
#[derive(Debug)]
pub(super) enum ClientActorMessage {
Download {
filename: PathBuf,
uri: Uri,
respond_to: oneshot::Sender<DownloadResult>,
},
GetData {
uri: Uri,
respond_to: oneshot::Sender<Option<Vec<u8>>>,
},
}
#[derive(Clone, Debug)]
pub(super) enum ClientActorMessageHandle {
Download {
filename: PathBuf,
uri: Uri,
state: Option<DownloadState>,
message: ActionIndex,
},
GetData {
uri: Uri,
buffer: Option<Vec<u8>>,
message: ActionIndex,
},
}
impl ClientActorMessageHandle {
pub(super) fn set_state(&mut self, new_state: DownloadState) {
if let Self::Download { ref mut state, .. } = self {
*state = Some(new_state);
} else {
panic!("Called with invalid variant");
}
}
pub(super) fn filename(&self) -> PathBuf {
if let Self::Download { ref filename, .. } = self {
filename.clone()
} else {
panic!("called with invalid variant");
}
}
pub(super) fn uri(&self) -> Uri {
match self {
Self::Download { ref uri, .. } => uri.clone(),
Self::GetData { ref uri, .. } => uri.clone(),
}
}
pub(super) fn buffer_mut(&mut self) -> &mut Option<Vec<u8>> {
if let Self::GetData { ref mut buffer, .. } = self {
buffer
} else {
panic!("called with invalid variant");
}
}
}

56
src/client/util.rs

@ -0,0 +1,56 @@
use anyhow::anyhow;
use http::{header::{CONTENT_LENGTH, CONTENT_TYPE}, request::Builder as RequestBuilder, HeaderMap, Response, Uri};
use reqwest::Body;
use tower_http::decompression::DecompressionBody;
use tower_http_client::ServiceExt as _;
use super::HttpClient;
use log::debug;
pub(super) async fn request( client: &mut HttpClient
, method: &str
, uri: &Uri
, headers: HeaderMap ) -> anyhow::Result<Response<DecompressionBody<Body>>> {
let mut request = RequestBuilder::new()
. method(method)
. uri(uri)
. body(Body::default())?;
request.headers_mut().extend(headers);
debug!("Request: {:?}", request);
let response = client.execute(request).await?;
debug!("Response: {:?}", response.headers());
anyhow::ensure!( response.status().is_success()
, "resonse status failed: {}"
, response.status() );
Ok(response)
}
pub(super) async fn head( client: &mut HttpClient
, uri: &Uri ) -> anyhow::Result<HeaderMap> {
Ok( request( client
, "HEAD"
, uri
, HeaderMap::new() ).await?.headers().clone() )
}
pub(super) fn content_length(headers: &HeaderMap) -> anyhow::Result<u64> {
Ok( headers . get(CONTENT_LENGTH)
. ok_or(anyhow!("unable to get CONTENT-LENGTH value"))?
. to_str()?
. parse()? )
}
pub(super) fn content_type(headers: &HeaderMap) -> anyhow::Result<String> {
Ok( headers . get(CONTENT_TYPE)
. ok_or(anyhow!("unable to get CONTENT-TYPE value"))?
. to_str()?
. to_string() )
}

18
src/main.rs

@ -1,4 +1,3 @@
mod download_error;
mod client;
mod process;
mod m3u8_download;
@ -28,9 +27,13 @@ struct Args {
#[arg(short, long)]
url: String,
#[arg(short, long)]
timeout: Option<u64>,
buffer: Option<usize>,
#[arg(short, long)]
rate: Option<u64>,
#[arg(short, long)]
concurrency: Option<usize>,
#[arg(short, long)]
timeout: Option<u64>,
}
@ -56,8 +59,10 @@ async fn main() -> anyhow::Result<()> {
Err(anyhow!("Only filenames with .mp4 extension are allowed"))?
}
let concurrency = args.concurrency.unwrap_or(10);
let timeout = args.timeout.unwrap_or(10);
let buffer = args.buffer.unwrap_or(1000);
let rate_limit = args.rate.unwrap_or(100);
let concurrency_limit = args.concurrency.unwrap_or(20);
let timeout = args.timeout.unwrap_or(15);
let timeout = Duration::from_secs(timeout);
let m3u8_uri = Uri::try_from(&args.url)?;
@ -68,7 +73,10 @@ async fn main() -> anyhow::Result<()> {
info!("Creating an HTTP client with Tower layers...");
let client = ClientActorHandle::new(concurrency, timeout);
let client = ClientActorHandle::new( buffer
, rate_limit
, concurrency_limit
, timeout );
info!("Get segments...");

Loading…
Cancel
Save