aboutsummaryrefslogtreecommitdiff
path: root/import/src/trakt.rs
blob: f37eb748203c750cb5d9cf44d25d78764233549a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use bincode::{Decode, Encode};
use jellybase::cache::async_cache_memory;
use jellycommon::{Appearance, ObjectIds, PeopleGroup, Person, TraktKind};
use reqwest::{
    header::{HeaderMap, HeaderName, HeaderValue},
    Client, ClientBuilder,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt::Display, sync::Arc};

pub struct Trakt {
    client: Client,
}

impl Trakt {
    pub fn new(api_key: &str) -> Self {
        let client = ClientBuilder::new()
            .default_headers(HeaderMap::from_iter([
                (
                    HeaderName::from_static("trakt-api-key"),
                    HeaderValue::from_str(api_key).unwrap(),
                ),
                (
                    HeaderName::from_static("trakt-api-version"),
                    HeaderValue::from_static("2"),
                ),
                (
                    HeaderName::from_static("content-type"),
                    HeaderValue::from_static("application/json"),
                ),
            ]))
            .build()
            .unwrap();
        Self { client }
    }

    pub async fn search(
        &self,
        kinds: &[TraktKind],
        query: &str,
        extended: bool,
    ) -> anyhow::Result<Arc<Vec<TraktSearchResult>>> {
        async_cache_memory(
            &["api-trakt-lookup", query, if extended { "a" } else { "b" }],
            || async move {
                let url = format!(
                    "https://api.trakt.tv/search/{}?query={}{}",
                    kinds
                        .iter()
                        .map(|t| t.singular())
                        .collect::<Vec<_>>()
                        .join(","),
                    urlencoding::encode(query),
                    optext(extended)
                );
                let res = self.client.get(url).send().await?.error_for_status()?;
                Ok(res.json().await?)
            },
        )
        .await
    }

    pub async fn lookup(
        &self,
        kind: TraktKind,
        id: u64,
        extended: bool,
    ) -> anyhow::Result<Arc<TraktMediaObject>> {
        async_cache_memory(
            &["api-trakt-lookup", &format!("{id} {extended}")],
            || async move {
                let url = format!(
                    "https://api.trakt.tv/{}/{}{}",
                    kind.plural(),
                    id,
                    optext2(extended)
                );
                let res = self.client.get(url).send().await?.error_for_status()?;
                Ok(res.json().await?)
            },
        )
        .await
    }

    pub async fn people(
        &self,
        kind: TraktKind,
        id: u64,
        extended: bool,
    ) -> anyhow::Result<Arc<TraktPeople>> {
        async_cache_memory(
            &["api-trakt-people", &format!("{id} {extended}")],
            || async move {
                let url = format!(
                    "https://api.trakt.tv/{}/{}/people{}",
                    kind.plural(),
                    id,
                    optext2(extended)
                );
                let res = self.client.get(url).send().await?.error_for_status()?;
                Ok(res.json().await?)
            },
        )
        .await
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, Default, Encode, Decode)]
pub struct TraktPeople {
    #[serde(default)]
    pub cast: Vec<TraktAppearance>,
    #[serde(default)]
    pub crew: BTreeMap<TraktPeopleGroup, Vec<TraktAppearance>>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default, Encode, Decode)]
pub struct TraktAppearance {
    #[serde(default)]
    pub jobs: Vec<String>,
    #[serde(default)]
    pub characters: Vec<String>,
    pub person: TraktPerson,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default, Encode, Decode)]
pub struct TraktPerson {
    pub name: String,
    pub ids: ObjectIds,
}

fn optext(extended: bool) -> &'static str {
    if extended {
        "&extended=full"
    } else {
        ""
    }
}
fn optext2(extended: bool) -> &'static str {
    if extended {
        "?extended=full"
    } else {
        ""
    }
}

#[derive(Debug, Serialize, Deserialize, Encode, Decode)]
pub struct TraktSearchResult {
    pub r#type: TraktKind,
    pub score: f64,
    #[serde(flatten)]
    pub inner: TraktKindObject,
}

#[derive(Debug, Serialize, Deserialize, Encode, Decode)]
#[serde(rename_all = "snake_case")]
pub enum TraktKindObject {
    Movie(TraktMediaObject),
    Show(TraktMediaObject),
    Season(TraktMediaObject),
    Episode(TraktMediaObject),
    Person(TraktMediaObject),
    User(TraktMediaObject),
}

impl TraktKindObject {
    pub fn inner(&self) -> &TraktMediaObject {
        match self {
            TraktKindObject::Movie(x)
            | TraktKindObject::Show(x)
            | TraktKindObject::Season(x)
            | TraktKindObject::Episode(x)
            | TraktKindObject::Person(x)
            | TraktKindObject::User(x) => x,
        }
    }
}

#[derive(
    Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Encode, Decode, Clone, Copy,
)]
pub enum TraktPeopleGroup {
    #[serde(rename = "production")]
    Production,
    #[serde(rename = "art")]
    Art,
    #[serde(rename = "crew")]
    Crew,
    #[serde(rename = "costume & make-up")] //? they really use that in as a key?!
    CostumeMakeup,
    #[serde(rename = "directing")]
    Directing,
    #[serde(rename = "writing")]
    Writing,
    #[serde(rename = "sound")]
    Sound,
    #[serde(rename = "camera")]
    Camera,
    #[serde(rename = "visual effects")]
    VisualEffects,
    #[serde(rename = "lighting")]
    Lighting,
    #[serde(rename = "editing")]
    Editing,
    #[serde(rename = "created by")]
    CreatedBy,
}
impl TraktPeopleGroup {
    pub fn a(self) -> PeopleGroup {
        match self {
            TraktPeopleGroup::Production => PeopleGroup::Production,
            TraktPeopleGroup::Art => PeopleGroup::Art,
            TraktPeopleGroup::Crew => PeopleGroup::Crew,
            TraktPeopleGroup::CostumeMakeup => PeopleGroup::CostumeMakeup,
            TraktPeopleGroup::Directing => PeopleGroup::Directing,
            TraktPeopleGroup::Writing => PeopleGroup::Writing,
            TraktPeopleGroup::Sound => PeopleGroup::Sound,
            TraktPeopleGroup::Camera => PeopleGroup::Camera,
            TraktPeopleGroup::VisualEffects => PeopleGroup::Vfx,
            TraktPeopleGroup::Lighting => PeopleGroup::Lighting,
            TraktPeopleGroup::Editing => PeopleGroup::Editing,
            TraktPeopleGroup::CreatedBy => PeopleGroup::CreatedBy,
        }
    }
}
impl TraktAppearance {
    pub fn a(&self) -> Appearance {
        Appearance {
            jobs: self.jobs.to_owned(),
            characters: self.characters.to_owned(),
            person: Person {
                name: self.person.name.to_owned(),
                headshot: None,
                ids: self.person.ids.to_owned(),
            },
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Encode, Decode, Clone)]
pub struct TraktMediaObject {
    pub title: String,
    pub year: Option<u32>,
    pub ids: ObjectIds,

    pub tagline: Option<String>,
    pub overview: Option<String>,
    pub released: Option<String>,
    pub runtime: Option<usize>,
    pub country: Option<String>,
    pub trailer: Option<String>,
    pub homepage: Option<String>,
    pub status: Option<String>,
    pub rating: Option<f64>,
    pub votes: Option<usize>,
    pub comment_count: Option<usize>,
    pub language: Option<String>,
    pub available_translations: Option<Vec<String>>,
    pub genres: Option<Vec<String>>,
}

impl Display for TraktSearchResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{} ({}) \x1b[2m{} [{}]\x1b[0m",
            self.inner.inner().title,
            self.inner.inner().year.unwrap_or(0),
            self.r#type,
            self.inner.inner().ids
        ))
    }
}