Skip to content

Commit 8c644aa

Browse files
committed
feat(http): add custom User-Agent header for HTTP requests
Add discrakt/VERSION as User-Agent header on all outgoing HTTP requests. This helps API providers identify the client making requests.
1 parent b077912 commit 8c644aa

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

src/trakt.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use serde::Deserialize;
22
use std::{collections::HashMap, time::Duration};
33
use ureq::{serde_json, Agent, AgentBuilder};
44

5-
use crate::utils::MediaType;
5+
use crate::utils::{user_agent, MediaType};
66

77
#[derive(Deserialize)]
88
pub struct TraktMovie {
@@ -71,6 +71,7 @@ impl Trakt {
7171
agent: AgentBuilder::new()
7272
.timeout_read(Duration::from_secs(5))
7373
.timeout_write(Duration::from_secs(5))
74+
.user_agent(user_agent())
7475
.build(),
7576
client_id,
7677
username,

src/utils.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
use chrono::{DateTime, FixedOffset, SecondsFormat, Utc};
22
use configparser::ini::Ini;
33
use serde::Deserialize;
4-
use std::{env, io, path::PathBuf, time::Duration};
4+
use std::{env, io, path::PathBuf, sync::OnceLock, time::Duration};
55
use ureq::AgentBuilder;
66

77
const REFRESH_TOKEN_TTL_SECS: u64 = 60 * 60 * 24 * 30 * 3; // 3 months
88

9+
static USER_AGENT: OnceLock<String> = OnceLock::new();
10+
11+
pub fn user_agent() -> &'static str {
12+
USER_AGENT
13+
.get_or_init(|| format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")))
14+
.as_str()
15+
}
16+
917
#[derive(Deserialize, Debug)]
1018
pub struct TraktAccessToken {
1119
pub access_token: String,
@@ -99,6 +107,7 @@ impl Env {
99107
let response = match agent
100108
.post("https://api.trakt.tv/oauth/token")
101109
.set("Content-Type", "application/json")
110+
.set("User-Agent", user_agent())
102111
.send_json(ureq::json!({
103112
"code": code,
104113
"client_id": self.trakt_client_id,
@@ -172,6 +181,7 @@ impl Env {
172181
let response = match agent
173182
.post("https://api.trakt.tv/oauth/token")
174183
.set("Content-Type", "application/json")
184+
.set("User-Agent", user_agent())
175185
.send_json(ureq::json!({
176186
"refresh_token": refresh_token,
177187
"client_id": self.trakt_client_id,

0 commit comments

Comments
 (0)