use crate::api_schema::{
self, AccentPhrase, AccentPhrasesResponse, EngineManifestRaw, HttpValidationError,
ParseKanaBadRequest, WordType,
};
use base64::{engine, Engine};
use once_cell::race::OnceBox;
use serde::Serialize;
use std::{collections::HashMap, convert::TryInto, io::ErrorKind};
use surf::{Error, StatusCode};
pub type CoreVersion = Option<String>;
static CLIENT: OnceBox<surf::Client> = once_cell::race::OnceBox::new();
fn client() -> &'static surf::Client {
CLIENT.get_or_init(|| Box::new(surf::Client::new()))
}
#[derive(Debug, Clone, Serialize)]
pub struct AudioQuery {
pub text: String,
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl AudioQuery {
pub async fn call(self, server: &str) -> Result<crate::api_schema::AudioQuery, APIError> {
let request = client()
.post(format!("http://{}/audio_query", server))
.query(&self)?
.build();
let mut res = client().send(request).await?;
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AudioQueryFromPreset {
pub text: String,
pub preset_id: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl AudioQueryFromPreset {
pub async fn call(self, server: &str) -> Result<crate::api_schema::AudioQuery, APIError> {
let request = client()
.post(format!("http://{}/audio_query_from_preset", server))
.query(&self)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AccentPhrases {
pub text: String,
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_kana: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
#[derive(Debug)]
pub enum AccentPhrasesErrors {
KanaParseError(ParseKanaBadRequest),
ApiError(APIError),
}
impl From<surf::Error> for AccentPhrasesErrors {
fn from(e: Error) -> Self {
AccentPhrasesErrors::ApiError(e.into())
}
}
impl From<surf::StatusCode> for AccentPhrasesErrors {
fn from(e: surf::StatusCode) -> Self {
AccentPhrasesErrors::ApiError(e.into())
}
}
impl AccentPhrases {
pub async fn call(self, server: &str) -> Result<AccentPhrasesResponse, AccentPhrasesErrors> {
let request = client()
.post(format!("http://{}/accent_phrases", server))
.query(&self)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::BadRequest => Err(AccentPhrasesErrors::KanaParseError(
res.body_json::<_>().await?,
)),
StatusCode::UnprocessableEntity => Err(AccentPhrasesErrors::ApiError(
APIError::Validation(res.body_json::<_>().await?),
)),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct MoraData {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub accent_phrases: Vec<AccentPhrase>,
}
impl MoraData {
pub async fn call(self, server: &str) -> Result<Vec<AccentPhrase>, APIError> {
let request = client()
.post(format!("http://{}/mora_data", server))
.query(&self)?
.body_json(&self.accent_phrases)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct MoraLength {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub accent_phrases: Vec<AccentPhrase>,
}
impl MoraLength {
pub async fn call(self, server: &str) -> Result<Vec<AccentPhrase>, APIError> {
let request = client()
.post(format!("http://{}/mora_length", server))
.query(&self)?
.body_json(&self.accent_phrases)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct MoraPitch {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub accent_phrases: Vec<AccentPhrase>,
}
impl MoraPitch {
pub async fn call(self, server: &str) -> Result<Vec<AccentPhrase>, APIError> {
let request = client()
.post(format!("http://{}/mora_pitch", server))
.query(&self)?
.body_json(&self.accent_phrases)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<_>().await?),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Synthesis {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_interrogative_upspeak: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub audio_query: crate::api_schema::AudioQuery,
}
impl Synthesis {
pub async fn call(self, server: &str) -> Result<Vec<u8>, APIError> {
let request = client()
.post(format!("http://{}/synthesis", server))
.query(&self)?
.body_json(&self.audio_query)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_bytes().await.unwrap_or_default().to_vec()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CancellableSynthesis {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub audio_query: crate::api_schema::AudioQuery,
}
impl CancellableSynthesis {
pub async fn call(self, server: &str) -> Result<Vec<u8>, APIError> {
let request = client()
.post(format!("http://{}/cancellable_synthesis", server))
.query(&self)?
.body_json(&self.audio_query)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_bytes().await.unwrap_or_default().to_vec()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct MultiSynthesis {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub audio_query: Vec<crate::api_schema::AudioQuery>,
}
impl MultiSynthesis {
pub async fn call(self, server: &str) -> Result<Vec<u8>, APIError> {
let request = client()
.post(format!("http://{}/multi_synthesis", server))
.query(&self)?
.body_json(&self.audio_query)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_bytes().await.unwrap_or_default().to_vec()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SynthesisMorphing {
pub base_speaker: i32,
pub target_speaker: i32,
pub morph_rate: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
#[serde(skip_serializing)]
pub audio_query: crate::api_schema::AudioQuery,
}
impl SynthesisMorphing {
pub async fn call(self, server: &str) -> Result<Vec<u8>, APIError> {
let request = client()
.post(format!("http://{}/synthesis_morphing", server))
.query(&self)?
.body_json(&self.audio_query)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_bytes().await.unwrap_or_default().to_vec()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct ConnectWaves {
pub waves: Vec<Vec<u8>>,
}
impl ConnectWaves {
pub async fn call(self, server: &str) -> Result<Vec<u8>, APIError> {
let mut buffer = Vec::new();
for wave in self.waves {
buffer.push(engine::general_purpose::STANDARD.encode(wave));
}
let request = client()
.post(format!("http://{}/connect_waves", server))
.body_json(&buffer)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(engine::general_purpose::STANDARD
.decode(res.body_string().await?.as_bytes())
.unwrap_or_default()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct Presets;
impl Presets {
pub async fn call(self, server: &str) -> Result<Vec<crate::api_schema::Preset>, APIError> {
let request = client().get(format!("http://{}/presets", server)).build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<Vec<crate::api_schema::Preset>>().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct Version;
impl Version {
pub async fn call(self, server: &str) -> Result<Option<String>, APIError> {
let request = client().get(format!("http://{}/version", server)).build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<Option<String>>().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct CoreVersions;
impl CoreVersions {
pub async fn call(self, server: &str) -> Result<Vec<String>, APIError> {
let request = client()
.get(format!("http://{}/core_versions", server))
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res.body_json::<Vec<String>>().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Speakers {
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl Speakers {
pub async fn call(self, server: &str) -> Result<Vec<crate::api_schema::Speaker>, APIError> {
let request = client()
.get(format!("http://{}/speakers", server))
.query(&self)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => Ok(res.body_json::<Vec<crate::api_schema::Speaker>>().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SpeakerInfo {
pub speaker_uuid: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl SpeakerInfo {
pub async fn call(self, server: &str) -> Result<crate::api_schema::SpeakerInfo, APIError> {
let req = client()
.get(format!("http://{}/speaker_info", server))
.query(&self)?
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => res
.body_json::<crate::api_schema::SpeakerInfoRaw>()
.await?
.try_into()
.map_err(|_| APIError::Io(std::io::Error::from(ErrorKind::InvalidData))),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SupportedDevices {
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl SupportedDevices {
pub async fn call(self, server: &str) -> Result<crate::api_schema::SupportedDevices, APIError> {
let request = client()
.get(format!("http://{}/supported_devices", server))
.query(&self)?
.build();
let mut res = client().send(request).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => Ok(res
.body_json::<crate::api_schema::SupportedDevices>()
.await?),
x => Err(x.into()),
}
}
}
#[derive(Debug)]
pub enum APIError {
Validation(HttpValidationError),
Io(std::io::Error),
Surf(surf::Error),
Unknown,
}
impl Clone for APIError {
fn clone(&self) -> Self {
match self {
Self::Validation(arg0) => Self::Validation(arg0.clone()),
Self::Io(_) => Self::Unknown,
Self::Surf(_) => Self::Unknown,
Self::Unknown => Self::Unknown,
}
}
}
impl From<surf::Error> for APIError {
fn from(e: Error) -> Self {
APIError::Surf(e)
}
}
impl Into<APIError> for std::io::Error {
fn into(self) -> APIError {
APIError::Io(self)
}
}
impl From<StatusCode> for APIError {
fn from(_: StatusCode) -> Self {
APIError::Unknown
}
}
#[derive(Debug, Clone)]
pub struct DownloadableLibraries;
impl DownloadableLibraries {
pub async fn call(
self,
server: &str,
) -> Result<crate::api_schema::DownloadableLibraries, APIError> {
let req = client()
.get(format!("http://{}/downloadble_libraries", server))
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => res
.body_json::<crate::api_schema::DownloadableLibrariesRaw>()
.await?
.try_into()
.map_err(|_| APIError::Io(std::io::Error::from(ErrorKind::InvalidData))),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct InitializeSpeaker {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl InitializeSpeaker {
pub async fn call(self, server: &str) -> Result<(), APIError> {
let req = client()
.post(format!("http://{}/initialize_speaker", server))
.query(&self)?
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::NoContent => Ok(()),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct IsInitializedSpeaker {
pub speaker: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_version: CoreVersion,
}
impl IsInitializedSpeaker {
pub async fn call(self, server: &str) -> Result<bool, APIError> {
let req = client()
.get(format!("http://{}/is_initialized_speaker", server))
.query(&self)?
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => Ok(res.body_json::<bool>().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct EngineManifest;
impl EngineManifest {
pub async fn call(self, server: &str) -> Result<crate::api_schema::EngineManifest, APIError> {
let req = client()
.get(format!("http://{}/engine_manifest", server))
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => res
.body_json::<EngineManifestRaw>()
.await?
.try_into()
.map_err(|_| APIError::Io(std::io::Error::from(ErrorKind::InvalidData))),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct UserDict;
impl UserDict {
pub async fn call(
self,
server: &str,
) -> Result<HashMap<String, crate::api_schema::UserDictWord>, APIError> {
let req = client().get(format!("http://{}/user_dict", server)).build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::Ok => Ok(res
.body_json::<HashMap<String, crate::api_schema::UserDictWord>>()
.await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UserDictWord {
pub surface: String,
pub pronunciation: String,
pub accent_type: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub word_type: Option<WordType>,
pub priority: Option<i32>,
}
impl UserDictWord {
pub async fn call(self, server: &str) -> Result<String, APIError> {
let req = client()
.post(format!("http://{}/user_dict_word", server))
.query(&self)?
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::Ok => Ok(res.body_string().await?),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RewriteUserDictWord {
pub uuid: String,
pub surface: String,
pub pronunciation: String,
pub accent_type: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub word_type: Option<WordType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub priority: Option<i32>,
}
impl RewriteUserDictWord {
pub async fn call(self, server: &str) -> Result<(), APIError> {
let req = client()
.put(format!("http://{}/user_dict_word/{}", server, self.uuid))
.query(&self)?
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::NoContent => Ok(()),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct DeleteUserDictWord {
pub uuid: String,
}
impl DeleteUserDictWord {
pub async fn call(self, server: &str) -> Result<(), APIError> {
let req = client()
.delete(format!("http://{}/user_dict_word/{}", server, self.uuid))
.build();
let mut res = client().send(req).await.unwrap();
match res.status() {
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
StatusCode::NoContent => Ok(()),
x => Err(x.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct ImportUserDict {
pub over_ride: bool,
pub dictionary: HashMap<String, api_schema::UserDictWord>,
}
impl ImportUserDict {
pub async fn call(self, server: &str) -> Result<(), APIError> {
let req = client()
.post(format!("http://{}/import_user_dict", server))
.body_json(&self.dictionary)?
.build();
let mut res = client().send(req).await?;
match res.status() {
StatusCode::NoContent => Ok(()),
StatusCode::UnprocessableEntity => {
Err(APIError::Validation(res.body_json::<_>().await?))
}
x => Err(x.into()),
}
}
}