Skip to main content

typecast_rust/
client.rs

1//! Typecast API client
2//!
3//! This module contains the main client for interacting with the Typecast API.
4
5use crate::composer::SpeechComposer;
6use crate::errors::{Result, TypecastError};
7use crate::models::{
8    Age, AudioFormat, CustomVoice, ErrorResponse, Gender, GenerateToFileRequest,
9    SubscriptionResponse, TTSModel, TTSRequest, TTSRequestStream, TTSResponse, UseCase, VoiceV2,
10    VoicesV2Filter, CLONING_MAX_FILE_SIZE, NAME_MAX_LENGTH, NAME_MIN_LENGTH,
11};
12use bytes::Bytes;
13use futures_util::stream::{Stream, StreamExt};
14use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE, USER_AGENT};
15use std::env;
16use std::fs;
17use std::path::Path;
18use std::pin::Pin;
19use std::time::Duration;
20
21/// Boxed asynchronous stream of audio chunks returned by the streaming TTS endpoint.
22pub type AudioByteStream = Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>;
23
24/// Convert a [`TTSModel`] into the wire format string used in query parameters.
25fn model_query_value(model: TTSModel) -> &'static str {
26    match model {
27        TTSModel::SsfmV30 => "ssfm-v30",
28        TTSModel::SsfmV21 => "ssfm-v21",
29    }
30}
31
32/// Convert a [`Gender`] into the wire format string used in query parameters.
33fn gender_query_value(gender: Gender) -> &'static str {
34    match gender {
35        Gender::Male => "male",
36        Gender::Female => "female",
37    }
38}
39
40/// Convert an [`Age`] into the wire format string used in query parameters.
41fn age_query_value(age: Age) -> &'static str {
42    match age {
43        Age::Child => "child",
44        Age::Teenager => "teenager",
45        Age::YoungAdult => "young_adult",
46        Age::MiddleAge => "middle_age",
47        Age::Elder => "elder",
48    }
49}
50
51/// Convert a [`UseCase`] into the wire format string used in query parameters.
52fn use_case_query_value(use_case: UseCase) -> &'static str {
53    match use_case {
54        UseCase::Announcer => "Announcer",
55        UseCase::Anime => "Anime",
56        UseCase::Audiobook => "Audiobook",
57        UseCase::Conversational => "Conversational",
58        UseCase::Documentary => "Documentary",
59        UseCase::ELearning => "E-learning",
60        UseCase::Rapper => "Rapper",
61        UseCase::Game => "Game",
62        UseCase::TikTokReels => "Tiktok/Reels",
63        UseCase::News => "News",
64        UseCase::Podcast => "Podcast",
65        UseCase::Voicemail => "Voicemail",
66        UseCase::Ads => "Ads",
67    }
68}
69
70fn infer_audio_format_from_path(path: &Path) -> Option<AudioFormat> {
71    match path.extension().and_then(|extension| extension.to_str()) {
72        Some(extension) if extension.eq_ignore_ascii_case("mp3") => Some(AudioFormat::Mp3),
73        Some(extension) if extension.eq_ignore_ascii_case("wav") => Some(AudioFormat::Wav),
74        _ => None,
75    }
76}
77
78/// Default API base URL
79pub const DEFAULT_BASE_URL: &str = "https://api.typecast.ai";
80
81/// Default request timeout in seconds
82pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
83
84/// Configuration for the Typecast client
85#[derive(Debug, Clone)]
86pub struct ClientConfig {
87    /// API key for authentication. Optional when using a proxy base URL.
88    pub api_key: String,
89    /// Base URL for the API (defaults to <https://api.typecast.ai>)
90    pub base_url: String,
91    /// Request timeout duration
92    pub timeout: Duration,
93}
94
95impl Default for ClientConfig {
96    fn default() -> Self {
97        Self {
98            api_key: env::var("TYPECAST_API_KEY").unwrap_or_default(),
99            base_url: env::var("TYPECAST_API_HOST")
100                .unwrap_or_else(|_| DEFAULT_BASE_URL.to_string()),
101            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
102        }
103    }
104}
105
106impl ClientConfig {
107    /// Create a new configuration with an API key
108    pub fn new(api_key: impl Into<String>) -> Self {
109        Self {
110            api_key: api_key.into(),
111            ..Default::default()
112        }
113    }
114
115    /// Set a custom base URL
116    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
117        self.base_url = base_url.into();
118        self
119    }
120
121    /// Set a custom timeout
122    pub fn timeout(mut self, timeout: Duration) -> Self {
123        self.timeout = timeout;
124        self
125    }
126}
127
128/// The main Typecast API client
129#[derive(Debug, Clone)]
130pub struct TypecastClient {
131    client: reqwest::Client,
132    base_url: String,
133    api_key: String,
134}
135
136impl TypecastClient {
137    /// Create a new TypecastClient with the given configuration
138    pub fn new(config: ClientConfig) -> Result<Self> {
139        let api_key = config.api_key.trim().to_string();
140        let base_url = config.base_url.trim().trim_end_matches('/').to_string();
141        if api_key.is_empty() && is_default_base_url(&base_url) {
142            return Err(TypecastError::Unauthorized {
143                detail: "API key is required for the default Typecast API host".to_string(),
144            });
145        }
146
147        let mut headers = HeaderMap::new();
148        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
149        headers.insert(
150            USER_AGENT,
151            HeaderValue::from_str(&build_user_agent(&base_url, config.timeout))
152                .expect("SDK-generated User-Agent is valid ASCII"),
153        );
154        if !api_key.is_empty() {
155            headers.insert(
156                "X-API-KEY",
157                HeaderValue::from_str(&api_key).map_err(|_| TypecastError::BadRequest {
158                    detail: "Invalid API key format".to_string(),
159                })?,
160            );
161        }
162
163        // `reqwest::Client::builder().build()` only fails if TLS init fails,
164        // which is not something we can usefully recover from at this layer.
165        let client = reqwest::Client::builder()
166            .default_headers(headers)
167            .timeout(config.timeout)
168            .build()
169            .expect("reqwest client builder should not fail");
170
171        Ok(Self {
172            client,
173            base_url,
174            api_key,
175        })
176    }
177
178    /// Create a new TypecastClient from environment variables
179    ///
180    /// Reads TYPECAST_API_KEY and optionally TYPECAST_API_HOST
181    pub fn from_env() -> Result<Self> {
182        Self::new(ClientConfig::default())
183    }
184
185    /// Create a new TypecastClient with just an API key
186    pub fn with_api_key(api_key: impl Into<String>) -> Result<Self> {
187        Self::new(ClientConfig::new(api_key))
188    }
189
190    /// Get the base URL
191    pub fn base_url(&self) -> &str {
192        &self.base_url
193    }
194
195    /// Get the API key (masked)
196    pub fn api_key_masked(&self) -> String {
197        if self.api_key.len() > 8 {
198            format!(
199                "{}...{}",
200                &self.api_key[..4],
201                &self.api_key[self.api_key.len() - 4..]
202            )
203        } else {
204            "****".to_string()
205        }
206    }
207
208    /// Create a builder for composed speech with multiple speech segments and pauses.
209    pub fn compose_speech(&self) -> SpeechComposer<'_> {
210        SpeechComposer::new(self)
211    }
212
213    fn with_auth_header(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
214        if self.api_key.is_empty() {
215            request
216        } else {
217            request.header("X-API-KEY", &self.api_key)
218        }
219    }
220
221    /// Build a URL with optional query parameters.
222    ///
223    /// Callers must pass `None` when there are no query parameters; passing
224    /// `Some(vec![])` is not supported and will produce a trailing `?`.
225    fn build_url(&self, path: &str, params: Option<Vec<(&str, String)>>) -> String {
226        let base = format!("{}{}", self.base_url, path);
227        match params {
228            Some(params) => {
229                let query: Vec<String> = params
230                    .into_iter()
231                    .map(|(k, v)| format!("{}={}", k, urlencoding::encode(&v)))
232                    .collect();
233                format!("{}?{}", base, query.join("&"))
234            }
235            None => base,
236        }
237    }
238
239    /// Handle an error response
240    async fn handle_error_response(&self, response: reqwest::Response) -> TypecastError {
241        let status_code = response.status().as_u16();
242        let error_response: Option<ErrorResponse> = response.json().await.ok();
243        TypecastError::from_response(status_code, error_response)
244    }
245
246    /// Convert text to speech
247    ///
248    /// # Arguments
249    ///
250    /// * `request` - The TTS request containing text, voice_id, model, and optional settings
251    ///
252    /// # Returns
253    ///
254    /// Returns a `TTSResponse` containing the audio data, duration, and format
255    ///
256    /// # Example
257    ///
258    /// ```no_run
259    /// use typecast_rust::{TypecastClient, TTSRequest, TTSModel, ClientConfig};
260    ///
261    /// # async fn example() -> typecast_rust::Result<()> {
262    /// let client = TypecastClient::from_env()?;
263    /// let request = TTSRequest::new(
264    ///     "tc_60e5426de8b95f1d3000d7b5",
265    ///     "Hello, world!",
266    ///     TTSModel::SsfmV30,
267    /// );
268    /// let response = client.text_to_speech(&request).await?;
269    /// println!("Audio duration: {} seconds", response.duration);
270    /// # Ok(())
271    /// # }
272    /// ```
273    pub async fn text_to_speech(&self, request: &TTSRequest) -> Result<TTSResponse> {
274        let url = self.build_url("/v1/text-to-speech", None);
275
276        let response = self.client.post(&url).json(request).send().await?;
277
278        if !response.status().is_success() {
279            return Err(self.handle_error_response(response).await);
280        }
281
282        // Parse content type for format
283        let content_type = response
284            .headers()
285            .get(CONTENT_TYPE)
286            .and_then(|v| v.to_str().ok())
287            .unwrap_or("audio/wav");
288
289        let format = if content_type.contains("mp3") || content_type.contains("mpeg") {
290            AudioFormat::Mp3
291        } else {
292            AudioFormat::Wav
293        };
294
295        // Parse duration from header
296        let duration = response
297            .headers()
298            .get("X-Audio-Duration")
299            .and_then(|v| v.to_str().ok())
300            .and_then(|v| v.parse::<f64>().ok())
301            .unwrap_or(0.0);
302
303        let audio_data = response.bytes().await?.to_vec();
304
305        Ok(TTSResponse {
306            audio_data,
307            duration,
308            format,
309        })
310    }
311
312    /// Convert text to speech and write the audio bytes to a file.
313    ///
314    /// If `request.output.audio_format` is omitted, the format is inferred from
315    /// a `.mp3` or `.wav` file extension.
316    pub async fn generate_to_file(
317        &self,
318        path: impl AsRef<Path>,
319        request: GenerateToFileRequest,
320    ) -> Result<TTSResponse> {
321        let path_ref = path.as_ref();
322        let mut tts_request = request.into_tts_request();
323        let inferred = infer_audio_format_from_path(path_ref);
324        match tts_request.output.as_mut() {
325            Some(output) => {
326                if output.audio_format.is_none() {
327                    output.audio_format = inferred;
328                }
329            }
330            None => {
331                if let Some(format) = inferred {
332                    tts_request.output = Some(crate::models::Output::new().audio_format(format));
333                }
334            }
335        }
336
337        let response = self.text_to_speech(&tts_request).await?;
338        fs::write(path_ref, &response.audio_data)
339            .map_err(|e| TypecastError::IoError(e.to_string()))?;
340        Ok(response)
341    }
342
343    /// Convert text to speech as a streaming response
344    ///
345    /// Returns a stream of audio byte chunks. For `wav` output the first chunk
346    /// contains the WAV header followed by PCM samples; for `mp3` output each
347    /// chunk is independently decodable.
348    ///
349    /// # Arguments
350    ///
351    /// * `request` - The streaming TTS request
352    ///
353    /// # Returns
354    ///
355    /// A pinned boxed [`Stream`] yielding [`Result<Bytes>`] chunks.
356    ///
357    /// # Example
358    ///
359    /// ```no_run
360    /// use futures_util::StreamExt;
361    /// use typecast_rust::{TypecastClient, TTSRequestStream, TTSModel};
362    ///
363    /// # async fn example() -> typecast_rust::Result<()> {
364    /// let client = TypecastClient::from_env()?;
365    /// let request = TTSRequestStream::new(
366    ///     "tc_60e5426de8b95f1d3000d7b5",
367    ///     "Hello, world!",
368    ///     TTSModel::SsfmV30,
369    /// );
370    /// let mut stream = client.text_to_speech_stream(&request).await?;
371    /// while let Some(chunk) = stream.next().await {
372    ///     let bytes = chunk?;
373    ///     // write bytes to file or audio sink
374    ///     let _ = bytes;
375    /// }
376    /// # Ok(())
377    /// # }
378    /// ```
379    pub async fn text_to_speech_stream(
380        &self,
381        request: &TTSRequestStream,
382    ) -> Result<AudioByteStream> {
383        let url = self.build_url("/v1/text-to-speech/stream", None);
384
385        let response = self.client.post(&url).json(request).send().await?;
386
387        if !response.status().is_success() {
388            return Err(self.handle_error_response(response).await);
389        }
390
391        let stream = response
392            .bytes_stream()
393            .map(|item| item.map_err(TypecastError::from));
394        Ok(Box::pin(stream))
395    }
396
397    /// Get voices with enhanced metadata (V2 API)
398    ///
399    /// # Arguments
400    ///
401    /// * `filter` - Optional filter for voices (model, gender, age, use_cases)
402    ///
403    /// # Returns
404    ///
405    /// Returns a list of `VoiceV2` with enhanced metadata
406    ///
407    /// # Example
408    ///
409    /// ```no_run
410    /// use typecast_rust::{TypecastClient, VoicesV2Filter, TTSModel, Gender, ClientConfig};
411    ///
412    /// # async fn example() -> typecast_rust::Result<()> {
413    /// let client = TypecastClient::from_env()?;
414    ///
415    /// // Get all voices
416    /// let voices = client.get_voices_v2(None).await?;
417    ///
418    /// // Get filtered voices
419    /// let filter = VoicesV2Filter::new()
420    ///     .model(TTSModel::SsfmV30)
421    ///     .gender(Gender::Female);
422    /// let filtered_voices = client.get_voices_v2(Some(filter)).await?;
423    /// # Ok(())
424    /// # }
425    /// ```
426    pub async fn get_voices_v2(&self, filter: Option<VoicesV2Filter>) -> Result<Vec<VoiceV2>> {
427        let mut params = Vec::new();
428
429        if let Some(f) = filter {
430            if let Some(model) = f.model {
431                params.push(("model", model_query_value(model).to_string()));
432            }
433            if let Some(gender) = f.gender {
434                params.push(("gender", gender_query_value(gender).to_string()));
435            }
436            if let Some(age) = f.age {
437                params.push(("age", age_query_value(age).to_string()));
438            }
439            if let Some(use_cases) = f.use_cases {
440                params.push(("use_cases", use_case_query_value(use_cases).to_string()));
441            }
442        }
443
444        let url = self.build_url(
445            "/v2/voices",
446            if params.is_empty() {
447                None
448            } else {
449                Some(params)
450            },
451        );
452
453        let response = self.client.get(&url).send().await?;
454
455        if !response.status().is_success() {
456            return Err(self.handle_error_response(response).await);
457        }
458
459        let voices: Vec<VoiceV2> = response.json().await?;
460        Ok(voices)
461    }
462
463    /// Get a specific voice by ID with enhanced metadata (V2 API)
464    ///
465    /// # Arguments
466    ///
467    /// * `voice_id` - The voice ID (e.g., 'tc_60e5426de8b95f1d3000d7b5')
468    ///
469    /// # Returns
470    ///
471    /// Returns a `VoiceV2` with enhanced metadata
472    ///
473    /// # Example
474    ///
475    /// ```no_run
476    /// use typecast_rust::{TypecastClient, ClientConfig};
477    ///
478    /// # async fn example() -> typecast_rust::Result<()> {
479    /// let client = TypecastClient::from_env()?;
480    /// let voice = client.get_voice_v2("tc_60e5426de8b95f1d3000d7b5").await?;
481    /// println!("Voice: {} ({})", voice.voice_name, voice.voice_id);
482    /// # Ok(())
483    /// # }
484    /// ```
485    pub async fn get_voice_v2(&self, voice_id: &str) -> Result<VoiceV2> {
486        let url = self.build_url(&format!("/v2/voices/{}", voice_id), None);
487
488        let response = self.client.get(&url).send().await?;
489
490        if !response.status().is_success() {
491            return Err(self.handle_error_response(response).await);
492        }
493
494        let voice: VoiceV2 = response.json().await?;
495        Ok(voice)
496    }
497
498    /// Convert text to speech with word- and/or character-level timestamps.
499    ///
500    /// # Arguments
501    ///
502    /// * `request` - The TTS request with timestamps parameters.
503    /// * `granularity` - Optional granularity: `None` (both), `"word"`, or `"char"`.
504    ///
505    /// # Returns
506    ///
507    /// A [`crate::timestamps::TTSWithTimestampsResponse`] containing the Base64-encoded audio
508    /// and alignment segment arrays.  Use the response's `.to_srt()` / `.to_vtt()` methods to
509    /// generate subtitle files.
510    ///
511    /// # Example
512    ///
513    /// ```no_run
514    /// use typecast_rust::{TypecastClient, TTSModel};
515    /// use typecast_rust::timestamps::TTSRequestWithTimestamps;
516    ///
517    /// # async fn example() -> typecast_rust::Result<()> {
518    /// let client = TypecastClient::from_env()?;
519    /// let request = TTSRequestWithTimestamps::new(
520    ///     "tc_60e5426de8b95f1d3000d7b5",
521    ///     "Hello, world!",
522    ///     TTSModel::SsfmV30,
523    /// );
524    /// let response = client.text_to_speech_with_timestamps(&request, None).await?;
525    /// let srt = response.to_srt()?;
526    /// println!("{}", srt);
527    /// # Ok(())
528    /// # }
529    /// ```
530    pub async fn text_to_speech_with_timestamps(
531        &self,
532        request: &crate::timestamps::TTSRequestWithTimestamps,
533        granularity: Option<&str>,
534    ) -> Result<crate::timestamps::TTSWithTimestampsResponse> {
535        if let Some(g) = granularity {
536            if g != "word" && g != "char" {
537                return Err(TypecastError::ValidationError {
538                    detail: format!(
539                        "granularity must be None, \"word\", or \"char\"; got {:?}",
540                        g
541                    ),
542                });
543            }
544        }
545
546        let url = match granularity {
547            Some(g) => self.build_url(
548                "/v1/text-to-speech/with-timestamps",
549                Some(vec![("granularity", g.to_string())]),
550            ),
551            None => self.build_url("/v1/text-to-speech/with-timestamps", None),
552        };
553
554        let response = self.client.post(&url).json(request).send().await?;
555
556        if !response.status().is_success() {
557            return Err(self.handle_error_response(response).await);
558        }
559
560        let parsed: crate::timestamps::TTSWithTimestampsResponse = response
561            .json()
562            .await
563            .map_err(|e| TypecastError::DecodeError(e.to_string()))?;
564        Ok(parsed)
565    }
566
567    /// Get the authenticated user's subscription
568    ///
569    /// # Returns
570    ///
571    /// Returns a `SubscriptionResponse` containing the user's plan, credits,
572    /// and usage limits.
573    ///
574    /// # Example
575    ///
576    /// ```no_run
577    /// use typecast_rust::TypecastClient;
578    ///
579    /// # async fn example() -> typecast_rust::Result<()> {
580    /// let client = TypecastClient::from_env()?;
581    /// let subscription = client.get_my_subscription().await?;
582    /// println!("Plan: {:?}", subscription.plan);
583    /// println!(
584    ///     "Credits: {}/{}",
585    ///     subscription.credits.used_credits, subscription.credits.plan_credits
586    /// );
587    /// # Ok(())
588    /// # }
589    /// ```
590    pub async fn get_my_subscription(&self) -> Result<SubscriptionResponse> {
591        let url = self.build_url("/v1/users/me/subscription", None);
592
593        let response = self.client.get(&url).send().await?;
594
595        if !response.status().is_success() {
596            return Err(self.handle_error_response(response).await);
597        }
598
599        let subscription: SubscriptionResponse = response.json().await?;
600        Ok(subscription)
601    }
602
603    /// Clone a voice from an audio recording.
604    ///
605    /// Uploads the audio file as `multipart/form-data` to `POST /v1/voices/clone`
606    /// and returns a [`CustomVoice`] representing the newly created voice.
607    ///
608    /// # Arguments
609    ///
610    /// * `audio` - Raw audio bytes (WAV or MP3). Must not exceed 25 MB.
611    /// * `filename` - File name used in the multipart part (e.g. `"sample.wav"`).
612    ///   The extension determines the MIME type sent to the API.
613    /// * `name` - Display name for the custom voice (1–30 characters).
614    /// * `model` - TTS model to use for cloning (e.g. `"ssfm-v30"`).
615    ///
616    /// # Errors
617    ///
618    /// Returns [`TypecastError::ValidationError`] if `name` is outside 1–30 characters
619    /// or if `audio` exceeds the 25 MB limit before any network call is made.
620    ///
621    /// # Example
622    ///
623    /// ```no_run
624    /// use typecast_rust::TypecastClient;
625    ///
626    /// # async fn example() -> typecast_rust::Result<()> {
627    /// let client = TypecastClient::from_env()?;
628    /// let audio = std::fs::read("sample.wav").unwrap();
629    /// let voice = client.clone_voice(audio, "sample.wav", "My Voice", "ssfm-v30").await?;
630    /// println!("Cloned voice ID: {}", voice.voice_id);
631    /// # Ok(())
632    /// # }
633    /// ```
634    pub async fn clone_voice(
635        &self,
636        audio: Vec<u8>,
637        filename: &str,
638        name: &str,
639        model: &str,
640    ) -> Result<CustomVoice> {
641        let name_len = name.chars().count();
642        if !(NAME_MIN_LENGTH..=NAME_MAX_LENGTH).contains(&name_len) {
643            return Err(TypecastError::ValidationError {
644                detail: format!(
645                    "name must be {}-{} characters; got {}",
646                    NAME_MIN_LENGTH, NAME_MAX_LENGTH, name_len
647                ),
648            });
649        }
650        if audio.len() > CLONING_MAX_FILE_SIZE {
651            return Err(TypecastError::ValidationError {
652                detail: format!("audio file exceeds 25MB limit; got {} bytes", audio.len()),
653            });
654        }
655
656        let mime = guess_audio_mime(filename);
657        let part = reqwest::multipart::Part::bytes(audio)
658            .file_name(filename.to_string())
659            .mime_str(mime)
660            .expect("guess_audio_mime only returns valid MIME constants");
661        let form = reqwest::multipart::Form::new()
662            .text("name", name.to_string())
663            .text("model", model.to_string())
664            .part("file", part);
665
666        let url = self.build_url("/v1/voices/clone", None);
667        let response = self
668            .with_auth_header(self.client.post(&url))
669            .multipart(form)
670            .send()
671            .await?;
672
673        if !response.status().is_success() {
674            return Err(self.handle_error_response(response).await);
675        }
676
677        let voice: CustomVoice = response.json().await?;
678        Ok(voice)
679    }
680
681    /// Delete a custom (cloned) voice by its ID.
682    ///
683    /// Sends `DELETE /v1/voices/{voice_id}`. A 204 No Content response is
684    /// treated as success; any other non-2xx status is mapped to a
685    /// [`TypecastError`].
686    ///
687    /// # Arguments
688    ///
689    /// * `voice_id` - The voice ID returned by [`TypecastClient::clone_voice`].
690    ///
691    /// # Example
692    ///
693    /// ```no_run
694    /// use typecast_rust::TypecastClient;
695    ///
696    /// # async fn example() -> typecast_rust::Result<()> {
697    /// let client = TypecastClient::from_env()?;
698    /// client.delete_voice("cv_abc123").await?;
699    /// println!("Voice deleted.");
700    /// # Ok(())
701    /// # }
702    /// ```
703    pub async fn delete_voice(&self, voice_id: &str) -> Result<()> {
704        let url = self.build_url(&format!("/v1/voices/{}", voice_id), None);
705        let response = self
706            .with_auth_header(self.client.delete(&url))
707            .send()
708            .await?;
709
710        let status = response.status();
711        if !status.is_success() {
712            return Err(self.handle_error_response(response).await);
713        }
714        Ok(())
715    }
716}
717
718fn build_user_agent(base_url: &str, timeout: Duration) -> String {
719    let base = if is_default_base_url(base_url) {
720        "default"
721    } else {
722        "custom"
723    };
724    let timeout_value = if timeout == Duration::from_secs(DEFAULT_TIMEOUT_SECS) {
725        "default".to_string()
726    } else {
727        format!("{}ms", timeout.as_millis())
728    };
729    format!(
730        "typecast-rust/{} Rust/{} reqwest (base={}; timeout={}; os={}; arch={}; sdk_env=rust; platform=server)",
731        env!("CARGO_PKG_VERSION"),
732        rust_version(),
733        base,
734        timeout_value,
735        os_name(),
736        arch_name()
737    )
738}
739
740fn rust_version() -> &'static str {
741    "unknown"
742}
743
744fn os_name() -> &'static str {
745    normalize_os_name(env::consts::OS)
746}
747
748fn normalize_os_name(os: &str) -> &'static str {
749    match os {
750        "macos" => "macos",
751        "windows" => "windows",
752        "linux" => "linux",
753        "ios" => "ios",
754        "android" => "android",
755        _ => "unknown",
756    }
757}
758
759fn arch_name() -> &'static str {
760    normalize_arch_name(env::consts::ARCH)
761}
762
763fn normalize_arch_name(arch: &str) -> &'static str {
764    match arch {
765        "x86_64" => "x64",
766        "aarch64" => "arm64",
767        "x86" => "x86",
768        "arm" => "arm",
769        _ => "unknown",
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776
777    #[test]
778    fn user_agent_includes_sdk_metadata_and_base_timeout_context() {
779        let default_user_agent =
780            build_user_agent(DEFAULT_BASE_URL, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
781        assert!(default_user_agent.starts_with("typecast-rust/"));
782        assert!(default_user_agent.contains("base=default"));
783        assert!(default_user_agent.contains("timeout=default"));
784        assert!(default_user_agent.contains("sdk_env=rust; platform=server"));
785
786        let custom_user_agent = build_user_agent("https://proxy.example", Duration::from_secs(5));
787        assert!(custom_user_agent.contains("base=custom"));
788        assert!(custom_user_agent.contains("timeout=5000ms"));
789    }
790
791    #[test]
792    fn platform_metadata_normalizes_known_and_unknown_values() {
793        assert_eq!(normalize_os_name("macos"), "macos");
794        assert_eq!(normalize_os_name("windows"), "windows");
795        assert_eq!(normalize_os_name("linux"), "linux");
796        assert_eq!(normalize_os_name("ios"), "ios");
797        assert_eq!(normalize_os_name("android"), "android");
798        assert_eq!(normalize_os_name("solaris"), "unknown");
799
800        assert_eq!(normalize_arch_name("x86_64"), "x64");
801        assert_eq!(normalize_arch_name("aarch64"), "arm64");
802        assert_eq!(normalize_arch_name("x86"), "x86");
803        assert_eq!(normalize_arch_name("arm"), "arm");
804        assert_eq!(normalize_arch_name("mips"), "unknown");
805    }
806}
807
808/// Infer an audio MIME type from a filename extension.
809///
810/// Defaults to `application/octet-stream` for unrecognised extensions.
811fn guess_audio_mime(filename: &str) -> &'static str {
812    let lower = filename.to_lowercase();
813    if lower.ends_with(".wav") {
814        "audio/wav"
815    } else if lower.ends_with(".mp3") {
816        "audio/mpeg"
817    } else if lower.ends_with(".ogg") {
818        "audio/ogg"
819    } else if lower.ends_with(".flac") {
820        "audio/flac"
821    } else if lower.ends_with(".m4a") {
822        "audio/mp4"
823    } else {
824        "application/octet-stream"
825    }
826}
827
828fn is_default_base_url(base_url: &str) -> bool {
829    base_url.eq_ignore_ascii_case(DEFAULT_BASE_URL)
830}
831
832/// URL encoding helper
833mod urlencoding {
834    pub fn encode(s: &str) -> String {
835        url_encode(s)
836    }
837
838    fn url_encode(s: &str) -> String {
839        let mut result = String::new();
840        for c in s.chars() {
841            match c {
842                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => {
843                    result.push(c);
844                }
845                _ => {
846                    for b in c.to_string().as_bytes() {
847                        result.push_str(&format!("%{:02X}", b));
848                    }
849                }
850            }
851        }
852        result
853    }
854}