#![forbid(unsafe_code)]
#![warn(missing_debug_implementations, missing_docs, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]
use std::io;
use reqwest::{
header::{HeaderMap, HeaderValue},
RequestBuilder,
};
use serde::de::DeserializeOwned;
use thiserror::Error;
pub mod billing;
pub mod invitations;
pub mod keys;
pub mod members;
pub mod projects;
pub mod scopes;
pub mod transcription;
pub mod usage;
mod response;
#[derive(Debug, Clone)]
pub struct Deepgram<K>
where
K: AsRef<str>,
{
api_key: K,
client: reqwest::Client,
}
#[derive(Debug, Error)]
pub enum DeepgramError {
#[error("No source was provided to the request builder.")]
NoSource,
#[error("The Deepgram API returned an error.")]
DeepgramApiError {
body: String,
err: reqwest::Error,
},
#[error("Something went wrong when generating the http request: {0}")]
HttpError(#[from] http::Error),
#[error("Something went wrong when making the HTTP request: {0}")]
ReqwestError(#[from] reqwest::Error),
#[error("Something went wrong during I/O: {0}")]
IoError(#[from] io::Error),
#[error("Something went wrong with WS: {0}")]
WsError(#[from] tungstenite::Error),
#[error("Something went wrong during serialization/deserialization: {0}")]
SerdeError(#[from] serde_json::Error),
}
type Result<T> = std::result::Result<T, DeepgramError>;
impl<K> Deepgram<K>
where
K: AsRef<str>,
{
pub fn new(api_key: K) -> Self {
static USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" rust",
);
let authorization_header = {
let mut header = HeaderMap::new();
header.insert(
"Authorization",
HeaderValue::from_str(&format!("Token {}", api_key.as_ref()))
.expect("Invalid API key"),
);
header
};
Deepgram {
api_key,
client: reqwest::Client::builder()
.user_agent(USER_AGENT)
.default_headers(authorization_header)
.build()
.expect("See reqwest::Client::new docs for cause of panic"),
}
}
}
async fn send_and_translate_response<R: DeserializeOwned>(
request_builder: RequestBuilder,
) -> crate::Result<R> {
let response = request_builder.send().await?;
match response.error_for_status_ref() {
Ok(_) => Ok(response.json().await?),
Err(err) => Err(DeepgramError::DeepgramApiError {
body: response.text().await?,
err,
}),
}
}