aboutsummaryrefslogtreecommitdiff
path: root/import/src/plugins/tmdb.rs
blob: 39f8115077c91002305b984b115caffd123aaaae (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
    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) 2026 metamuffin <metamuffin.org>
*/
use crate::{
    USER_AGENT,
    plugins::{ImportPlugin, PluginContext, PluginInfo},
    source_rank::ObjectImportSourceExt,
};
use anyhow::{Context, Result, anyhow, bail};
use chrono::{Utc, format::Parsed};
use jellycache::{Cache, EscapeKey, HashKey};
use jellycommon::*;
use jellydb::RowNum;
use log::info;
use reqwest::{
    Client, ClientBuilder,
    header::{HeaderMap, HeaderName, HeaderValue},
};
use serde::{Deserialize, Serialize};
use std::{fmt::Display, sync::Arc};
use tokio::runtime::Handle;

pub struct Tmdb {
    client: Client,
    image_client: Client,
    key: String,
}

impl Tmdb {
    pub fn new(api_key: &str) -> Self {
        let client = ClientBuilder::new()
            .default_headers(HeaderMap::from_iter([
                (
                    HeaderName::from_static("accept"),
                    HeaderValue::from_static("application/json"),
                ),
                (
                    HeaderName::from_static("user-agent"),
                    HeaderValue::from_static(USER_AGENT),
                ),
            ]))
            .build()
            .unwrap();
        let image_client = ClientBuilder::new().build().unwrap();
        Self {
            client,
            image_client,
            key: api_key.to_owned(),
        }
    }
    pub fn search(
        &self,
        cache: &Cache,
        kind: TmdbKind,
        query: &str,
        rt: &Handle,
    ) -> Result<Arc<TmdbQuery>> {
        cache
            .cache_memory(
                &format!("ext/tmdb/search/{kind}-{}.json", HashKey(query)),
                move || {
                    rt.block_on(async {
                        info!("searching tmdb: {query:?}");
                        Ok(self
                            .client
                            .get(format!(
                                "https://api.themoviedb.org/3/search/{kind}?query={}?api_key={}",
                                query.replace(" ", "+"),
                                self.key
                            ))
                            .send()
                            .await?
                            .error_for_status()?
                            .json::<TmdbQuery>()
                            .await?)
                    })
                },
            )
            .context("tmdb search")
    }
    pub fn details(
        &self,
        cache: &Cache,
        kind: TmdbKind,
        id: u64,
        rt: &Handle,
    ) -> Result<Arc<TmdbDetails>> {
        cache
            .cache_memory(&format!("ext/tmdb/details/{kind}-{id}.json"), move || {
                rt.block_on(async {
                    info!("fetching details: {id:?}");
                    Ok(self
                        .client
                        .get(format!(
                            "https://api.themoviedb.org/3/{kind}/{id}?api_key={}",
                            self.key,
                        ))
                        .send()
                        .await?
                        .error_for_status()?
                        .json()
                        .await?)
                })
            })
            .context("tmdb details")
    }
    pub fn person_image(
        &self,
        cache: &Cache,
        id: u64,
        rt: &Handle,
    ) -> Result<Arc<TmdbPersonImage>> {
        cache
            .cache_memory(&format!("ext/tmdb/person/images/{id}.json"), move || {
                rt.block_on(async {
                    Ok(self
                        .client
                        .get(format!(
                            "https://api.themoviedb.org/3/person/{id}/images?api_key={}",
                            self.key,
                        ))
                        .send()
                        .await?
                        .error_for_status()?
                        .json()
                        .await?)
                })
            })
            .context("tmdb person images")
    }
    pub fn image(&self, cache: &Cache, path: &str, rt: &Handle) -> Result<String> {
        cache
            .store(
                format!("ext/tmdb/image/{}.image", EscapeKey(path)),
                move || {
                    rt.block_on(async {
                        info!("downloading image {path:?}");
                        Ok(self
                            .image_client
                            .get(format!("https://image.tmdb.org/t/p/original{path}"))
                            .send()
                            .await?
                            .error_for_status()?
                            .bytes()
                            .await?
                            .to_vec())
                    })
                },
            )
            .context("tmdb image download")
    }

    pub fn episode_details(
        &self,
        cache: &Cache,
        series_id: u64,
        season: u64,
        episode: u64,
        rt: &Handle,
    ) -> Result<Arc<TmdbEpisode>> {
        cache.cache_memory(&format!("ext/tmdb/episode-details/{series_id}-S{season}-E{episode}.json"), move || {
            rt.block_on(async {
                info!("tmdb episode details {series_id} S={season} E={episode}");
                Ok(self
                    .image_client
                    .get(format!("https://api.themoviedb.org/3/tv/{series_id}/season/{season}/episode/{episode}?api_key={}", self.key))
                    .send()
                    .await?
                    .error_for_status()?
                    .json()
                    .await?)
            })
        })
        .context("tmdb episode details")
    }
}

impl ImportPlugin for Tmdb {
    fn info(&self) -> PluginInfo {
        PluginInfo {
            name: "tmdb",
            tag: MSOURCE_TMDB,
            handle_process: true,
            ..Default::default()
        }
    }
    fn process(&self, ct: &PluginContext, node: RowNum) -> Result<()> {
        self.process_primary(ct, node)?;
        self.process_episode(ct, node)?;
        self.process_person(ct, node)?;
        Ok(())
    }
}
impl Tmdb {
    fn process_primary(&self, ct: &PluginContext, node: RowNum) -> Result<()> {
        let data = ct.ic.get_node(node)?.unwrap();
        let data = data.as_object();

        let (tmdb_kind, tmdb_id): (_, u64) = if let Some(id) = data
            .get(NO_IDENTIFIERS)
            .unwrap_or_default()
            .get(IDENT_TMDB_SERIES)
        {
            (TmdbKind::Tv, id.parse()?)
        } else if let Some(id) = data
            .get(NO_IDENTIFIERS)
            .unwrap_or_default()
            .get(IDENT_TMDB_MOVIE)
        {
            (TmdbKind::Movie, id.parse()?)
        } else {
            return Ok(());
        };

        let details = self.details(&ct.ic.cache, tmdb_kind, tmdb_id, ct.rt)?;
        let backdrop = details
            .backdrop_path
            .as_ref()
            .map(|path| self.image(&ct.ic.cache, &path, ct.rt))
            .transpose()
            .context("backdrop image")?;
        let poster = details
            .poster_path
            .as_ref()
            .map(|path| self.image(&ct.ic.cache, &path, ct.rt))
            .transpose()
            .context("poster image")?;

        let release_date = details
            .release_date
            .as_ref()
            .map(|s| parse_release_date(s))
            .transpose()?
            .flatten();

        ct.ic.update_node(node, |mut node| {
            if let Some(title) = &details.title {
                node = node.as_object().insert_s(ct.is, NO_TITLE, &title);
            }
            if let Some(tagline) = &details.tagline {
                node = node.as_object().insert_s(ct.is, NO_TAGLINE, &tagline);
            }
            node = node
                .as_object()
                .insert_s(ct.is, NO_DESCRIPTION, &details.overview);
            node = node.as_object().update(NO_RATINGS, |rat| {
                rat.insert_s(ct.is, RTYP_TMDB, details.vote_average)
            });
            if let Some(poster) = &poster {
                node = node
                    .as_object()
                    .update(NO_PICTURES, |rat| rat.insert_s(ct.is, PICT_COVER, &poster));
            }
            if let Some(backdrop) = &backdrop {
                node = node.as_object().update(NO_PICTURES, |rat| {
                    rat.insert_s(ct.is, PICT_BACKDROP, &backdrop)
                });
            }
            if let Some(releasedate) = release_date {
                node = node
                    .as_object()
                    .insert_s(ct.is, NO_RELEASEDATE, releasedate);
            }
            node
        })?;
        Ok(())
    }
    fn process_episode(&self, ct: &PluginContext, node: RowNum) -> Result<()> {
        let data = ct.ic.get_node(node)?.unwrap();
        let data = data.as_object();

        let (Some(episode), Some(season)) = (data.get(NO_INDEX), data.get(NO_SEASON_INDEX)) else {
            return Ok(());
        };
        let mut series_id = None;
        ct.ic.db.transaction(&mut |txn| {
            for parent in data.iter(NO_PARENT) {
                let parent_data = txn.get(parent)?.ok_or(anyhow!("parent missing"))?;
                if let Some(id) = parent_data
                    .as_object()
                    .get(NO_IDENTIFIERS)
                    .unwrap_or_default()
                    .get(IDENT_TMDB_SERIES)
                {
                    series_id = Some(id.parse::<u64>()?);
                    break;
                }
            }
            Ok(())
        })?;
        let Some(series_id) = series_id else {
            return Ok(());
        };
        let details = self.episode_details(&ct.ic.cache, series_id, season, episode, ct.rt)?;
        let cover = details
            .still_path
            .as_ref()
            .map(|path| self.image(&ct.ic.cache, &path, ct.rt))
            .transpose()
            .context("still image download")?;
        let release_date = parse_release_date(&details.air_date)?;
        ct.ic.update_node(node, |mut node| {
            node = node.as_object().insert_s(ct.is, NO_TITLE, &details.name);
            node = node
                .as_object()
                .insert_s(ct.is, NO_DESCRIPTION, &details.overview);
            if let Some(release_date) = release_date {
                node = node
                    .as_object()
                    .insert_s(ct.is, NO_RELEASEDATE, release_date)
            }
            node = node.as_object().update(NO_RATINGS, |rat| {
                rat.insert_s(ct.is, RTYP_TMDB, details.vote_average)
            });
            if let Some(cover) = &cover {
                node = node.as_object().update(NO_PICTURES, |picts| {
                    picts.insert_s(ct.is, PICT_COVER, &cover)
                });
            }
            node
        })
    }

    fn process_person(&self, ct: &PluginContext, node: RowNum) -> Result<()> {
        let data = ct.ic.get_node(node)?.unwrap();
        let data = data.as_object();

        let Some(id) = data
            .get(NO_IDENTIFIERS)
            .unwrap_or_default()
            .get(IDENT_TMDB_PERSON)
        else {
            return Ok(());
        };
        let id = id.parse()?;

        let images = self.person_image(&ct.ic.cache, id, ct.rt)?;
        let Some(prof) = images.profiles.first() else {
            return Ok(());
        };

        let image = self.image(&ct.ic.cache, &prof.file_path, ct.rt)?;

        ct.ic.update_node(node, |node| {
            node.as_object()
                .update(NO_PICTURES, |pict| pict.insert_s(ct.is, PICT_COVER, &image))
        })?;

        Ok(())
    }
}

pub fn parse_release_date(d: &str) -> Result<Option<i64>> {
    if d.is_empty() {
        return Ok(None);
    } else if d.len() < 10 {
        bail!(anyhow!("date string too short"))
    }
    let (year, month, day) = (&d[0..4], &d[5..7], &d[8..10]);
    let (year, month, day) = (
        year.parse().context("parsing year")?,
        month.parse().context("parsing month")?,
        day.parse().context("parsing day")?,
    );

    let mut p = Parsed::new();
    p.year = Some(year);
    p.month = Some(month);
    p.day = Some(day);
    p.hour_div_12 = Some(0);
    p.hour_mod_12 = Some(0);
    p.minute = Some(0);
    p.second = Some(0);
    Ok(Some(p.to_datetime_with_timezone(&Utc)?.timestamp_millis()))
}

impl Display for TmdbKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            TmdbKind::Tv => "tv",
            TmdbKind::Movie => "movie",
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbEpisode {
    pub air_date: String,
    pub overview: String,
    pub name: String,
    pub id: u64,
    pub runtime: f64,
    pub still_path: Option<String>,
    pub vote_average: f64,
    pub vote_count: usize,
}

#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize)]
pub enum TmdbKind {
    Tv,
    Movie,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbPersonImage {
    pub id: u64,
    pub profiles: Vec<TmdbPersonImageProfile>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbPersonImageProfile {
    pub aspect_ratio: f64,
    pub height: u32,
    pub width: u32,
    pub file_path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbQuery {
    pub page: usize,
    pub results: Vec<TmdbQueryResult>,
    pub total_pages: usize,
    pub total_results: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbQueryResult {
    pub adult: bool,
    pub backdrop_path: Option<String>,
    pub genre_ids: Vec<u64>,
    pub id: u64,
    pub original_language: Option<String>,
    pub original_title: Option<String>,
    pub overview: String,
    pub popularity: f64,
    pub poster_path: Option<String>,
    pub release_date: Option<String>,
    pub title: Option<String>,
    pub name: Option<String>,
    pub vote_average: f64,
    pub vote_count: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbDetails {
    pub adult: bool,
    pub backdrop_path: Option<String>,
    pub genres: Vec<TmdbGenre>,
    pub id: u64,
    pub original_language: Option<String>,
    pub original_title: Option<String>,
    pub overview: String,
    pub popularity: f64,
    pub poster_path: Option<String>,
    pub release_date: Option<String>,
    pub title: Option<String>,
    pub name: Option<String>,
    pub vote_average: f64,
    pub vote_count: usize,
    pub budget: Option<usize>,
    pub homepage: Option<String>,
    pub imdb_id: Option<String>,
    pub production_companies: Vec<TmdbProductionCompany>,
    pub revenue: Option<usize>,
    pub tagline: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbGenre {
    pub id: u64,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmdbProductionCompany {
    pub id: u64,
    pub name: String,
    pub logo_path: Option<String>,
}