autorip 0.1.1

Composes other programs to automatically rip optical media
Documentation
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
#![allow(dead_code)]
use std::{
    env, fmt,
    fs::{self, File},
    io::{Read, Write},
    path::{Path, PathBuf},
    process::{Command, Output},
    thread,
};

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Deserializer};
use uuid::Uuid;

#[derive(Default, Debug)]
pub(crate) struct MetaData {
    pub(crate) title: String,
    pub(crate) year: u32,
    pub(crate) description: Option<String>,
    pub(crate) genre: Option<String>,
    pub(crate) rating: Option<String>,
    pub(crate) runtime: u32,
    pub(crate) cast: Vec<CastMember>,
    pub(crate) artwork: Option<PathBuf>,
    pub(crate) tmdb_id: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct Genre {
    name: String,
}

#[derive(Debug, Deserialize)]
struct Credits {
    cast: Vec<CastMember>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct CastMember {
    pub(crate) name: String,
}

#[derive(Debug, Deserialize)]
struct TMDBMovie {
    // adult,
    // backdrop_path,
    // belongs_to_collection,
    // budget,
    credits: Credits,
    genres: Vec<Genre>,
    // homepage,
    id: u32,
    // images:,
    // imdb_id:,
    // original_language:,
    // original_title:,
    overview: String,
    popularity: f32,
    poster_path: Option<String>,
    // production_companies: ,
    // production_countries: ,
    #[serde(rename = "release_date")]
    #[serde(deserialize_with = "year_from_release_date")]
    year: u32,
    releases: Releases,
    // revenue: ,
    runtime: u32,
    // spoken_languages: Vec<String>,
    // status: ,
    // tagline: ,
    title: String,
    // video: bool,
    // vote_average: ,
    // vote_count: ,
    downloaded_artwork: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
struct Releases {
    countries: Vec<Country>,
}

#[derive(Debug, Deserialize)]
struct Country {
    certification: String,
    iso_3166_1: String,
}

#[derive(Debug, Deserialize)]
struct TMDBMovieSearchResponse {
    results: Vec<TMDBMovieSearchResult>,
}

#[derive(Debug, Deserialize, PartialEq)]
struct TMDBMovieSearchResult {
    id: u32,
    overview: String,
    popularity: f32,
    // poster_path: Option<String>,
    release_date: String,
    title: String,
}

fn year_from_release_date<'de, D>(
    deserializer: D,
) -> std::result::Result<u32, D::Error>
where
    D: Deserializer<'de>,
{
    let input: String = Deserialize::deserialize(deserializer)?;
    if let Some(first) = input.split('-').next() {
        first.parse::<u32>().map_err(serde::de::Error::custom)
    } else {
        Err(serde::de::Error::custom(format!(
            "unrecognized release_date format: {input}",
        )))
    }
}

impl PartialOrd for TMDBMovieSearchResult {
    // Reverse sort by popularity
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for TMDBMovieSearchResult {}

impl Ord for TMDBMovieSearchResult {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other
            .popularity
            .partial_cmp(&self.popularity)
            .unwrap_or_else(|| panic!("Comparison failed for {:?}", self))
    }
}

#[derive(Clone)]
struct QueryBuilder {
    api_key: String,
    base_url: &'static str,
}

impl QueryBuilder {
    fn new() -> Result<Self> {
        const ENVVAR: &str = "TMDB_API_KEY";
        let api_key = std::env::var(ENVVAR)?;

        Ok(Self {
            api_key,
            base_url: "https://api.themoviedb.org/3",
        })
    }

    fn search_tmdb(
        &self,
        title: impl AsRef<str>,
    ) -> Result<Vec<TMDBMovieSearchResult>> {
        // curl --silent --get --data api_key=$API_KEY --data-urlencode query=$title 'https://api.themoviedb.org/3/search/movie' | jq '.results | sort_by(-.popularity)'
        let req = self
            .make_request("/search/movie")
            .query("query", title.as_ref());
        let resp = req.call()?;
        let json: TMDBMovieSearchResponse = resp.into_json()?;
        let mut results = json.results;
        results.sort();

        Ok(results)
    }

    fn fetch_from_tmdb(&self, id: u32) -> Result<TMDBMovie> {
        // API_KEY
        // base_url=$(curl --silent --get --data api_key=$API_KEY 'https://api.themoviedb.org/3/configuration' | jq --raw-output '.images.secure_base_url')
        // curl -s ${base_url}/original/${filename} --output
        // ${tmpdir}/${filename}

        // curl --silent --get --data api_key=$API_KEY --data-urlencode query=$title 'https://api.themoviedb.org/3/search/movie' | jq '.results | sort_by(-.popularity)'
        // curl --silent --get --data api_key=$API_KEY -d 'append_to_response=credits,images,releases' 'https://api.themoviedb.org/3/movie/'$id

        let body_handle = thread::spawn({
            let qb = self.clone();
            move || {
                qb.make_request(format!("/movie/{id}"))
                    .query("append_to_response", "credits,images,releases")
                    .call()
            }
        });

        let images_base_handle = thread::spawn({
            let qb = self.clone();
            move || qb.fetch_tmdb_images_base()
        });

        let mut tmdbmovie: TMDBMovie = body_handle
            .join()
            .expect("Unable to join json thread")?
            .into_json()?;
        let poster_path = &tmdbmovie.poster_path;

        if let Some(pp) = poster_path {
            let images_base = images_base_handle
                .join()
                .expect("Unable to join images_base thread")?;
            let image_url = images_base + "original" + pp;
            let image = ureq::get(&image_url).call()?;
            let len = image
                .header("Content-Length")
                .ok_or_else(|| anyhow!("No content length"))
                .and_then(|s| Ok(s.parse::<usize>()?))?;

            let mut bytes: Vec<u8> = Vec::with_capacity(len);
            image
                .into_reader()
                .take(10_000_000)
                .read_to_end(&mut bytes)?;

            if !bytes.is_empty() {
                let uuid = Uuid::new_v4().to_string();
                let dest = env::temp_dir().join("autorip").join(uuid);
                fs::create_dir_all(&dest)?;
                let imagefile = dest.join(pp.trim_start_matches('/'));
                let mut buf = File::create(&imagefile)?;
                buf.write_all(&bytes)?;
                tmdbmovie.downloaded_artwork = Some(imagefile);
            }
        }
        Ok(tmdbmovie)
    }

    fn make_request(&self, path: impl AsRef<str>) -> ureq::Request {
        let url = self.base_url.to_owned() + path.as_ref();
        ureq::get(url.as_ref()).query("api_key", &self.api_key)
    }

    fn fetch_tmdb_images_base(&self) -> Result<String> {
        Ok(self
            .make_request("/configuration")
            .call()
            .with_context(|| "failed to request tmdb configuration")?
            .into_json::<serde_json::Value>()?
            .get("images")
            .and_then(|v| v.get("secure_base_url"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                anyhow!("Could not get secure_base_url from TMDB API")
            })?
            .into())
    }
}

impl From<TMDBMovie> for MetaData {
    fn from(movie: TMDBMovie) -> Self {
        Self {
            title: movie.title,
            year: movie.year,
            description: Some(movie.overview),
            genre: movie.genres.first().map(|g| g.name.clone()),
            runtime: movie.runtime,
            rating: movie.releases.countries.iter().find_map(|release| {
                if release.iso_3166_1 == "US" {
                    Some(release.certification.clone())
                } else {
                    None
                }
            }),
            cast: movie.credits.cast,
            artwork: movie.downloaded_artwork,
            tmdb_id: Some(movie.id),
        }
    }
}

impl MetaData {
    /// Returns Self for the most popular TMDB search result
    pub(crate) fn guess_from_title(title: impl AsRef<str>) -> Result<Self> {
        let qb = QueryBuilder::new()?;
        let id = if let Some(result) = qb.search_tmdb(title.as_ref())?.first()
        {
            result.id
        } else {
            bail!(
                "Could not find a suitable movie ID. Please specify one \
                 manually."
            )
        };
        Ok(qb.fetch_from_tmdb(id)?.into())
    }

    pub(crate) fn from_id(id: u32) -> Result<Self> {
        Ok(QueryBuilder::new()?.fetch_from_tmdb(id)?.into())
    }

    /// Returns a `TMDBMovie` for the the top `n` search results
    pub fn search_by_title(
        title: impl AsRef<str>,
        count: usize,
    ) -> Result<impl Iterator<Item = impl fmt::Display>> {
        let qb = QueryBuilder::new()?;
        let results = qb.search_tmdb(title.as_ref())?;
        Ok(results.into_iter().take(count))
    }
}

pub(crate) fn set_metadata(
    file: impl AsRef<Path>,
    md: &MetaData,
) -> Result<Output> {
    log::info!("Setting metadata on {:?}: {:?}", file.as_ref(), &md);
    let desc = md.description.as_deref().unwrap_or_default();

    let ap = || {
        let mut cmd = Command::new("atomicparsley");
        cmd.arg(file.as_ref());
        cmd
    };

    ap().arg(file.as_ref())
        .args("--metaEnema --overWrite".split_whitespace())
        .status()?;
    ap().arg(file.as_ref())
        .args("--artwork REMOVE_ALL --overWrite".split_whitespace())
        .status()?;

    let mut cmd = ap();
    cmd.arg("--description")
        .arg(desc)
        .arg("--title")
        .arg(&md.title)
        .arg("--year")
        .arg(md.year.to_string())
        .arg("--genre")
        .arg(md.genre.as_deref().unwrap_or_default())
        .arg("--longdesc")
        .arg(desc)
        .arg("--stik=Movie")
        .arg("--Rating")
        .arg("--artist")
        .arg(
            md.cast
                .iter()
                .map(|c| c.name.clone())
                .collect::<Vec<_>>()
                .join(", "),
        );
    if let Some(artwork_path) = &md.artwork {
        cmd.arg("--artwork").arg(artwork_path);
    };
    Ok(cmd.arg("--overWrite").output()?)
}

impl fmt::Display for MetaData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "tmdb id {}: {}", self.tmdb_id.unwrap(), self.title)?;
        writeln!(f, "year: {}", self.year)?;

        if let Some(ref g) = self.genre {
            writeln!(f, "genre: {g}")?;
        };
        if let Some(ref r) = self.rating {
            writeln!(f, "rating: {r}")?;
        };
        if let Some(ref d) = self.description {
            writeln!(f, "description: {d}")?;
        }
        if !self.cast.is_empty() {
            writeln!(
                f,
                "cast: {}",
                self.cast
                    .iter()
                    .map(|c| c.name.clone())
                    .collect::<Vec<_>>()
                    .join(", ")
            )?;
        }
        Ok(())
    }
}

impl fmt::Display for TMDBMovieSearchResult {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "tmdb id {}: {}", self.id, self.title)?;
        writeln!(f, "release_date: {}", self.release_date)?;
        writeln!(f, "overview: {}", self.overview)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::{env, fs, path::PathBuf};

    use uuid::Uuid;

    use super::*;
    use crate::get_stdout;

    fn read_metadata(file: impl AsRef<Path>) -> Result<String> {
        get_stdout(
            Command::new("atomicparsley")
                .arg(file.as_ref())
                .arg("--textdata")
                .output()?,
        )
    }

    #[test]
    fn sets_metadata() -> Result<()> {
        let md = MetaData::from_id(218)?;
        let testfile: PathBuf = "tests/files/video1.mp4".into();

        let uuid = Uuid::new_v4().to_string();
        let destdir = env::temp_dir().join("autorip").join(uuid);
        fs::create_dir_all(&destdir)?;
        let dest = destdir.join("video.mp4");

        fs::copy(testfile, &dest)?;
        let before = read_metadata(&dest)?;
        set_metadata(&dest, &md)?;
        let after = read_metadata(&dest)?;

        assert_ne!(before, after);
        Ok(())
    }
}