about summary refs log tree commit diff stats
path: root/crates/yt_dlp/src/options.rs
blob: dedb03c11302d9b77da8cb5c2c6a937a2977dddd (plain) (blame)
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::sync;

use pyo3::{
    Bound, IntoPyObjectExt, PyAny, PyResult, Python, intern,
    types::{PyAnyMethods, PyCFunction, PyDict, PyTuple},
};
use pyo3_pylogger::setup_logging;

use crate::{
    YoutubeDL, json_loads, post_processors, py_kw_args,
    python_error::{IntoPythonError, PythonError},
};

pub type ProgressHookFunction = fn(py: Python<'_>) -> PyResult<Bound<'_, PyCFunction>>;
pub type PostProcessorFunction = fn(py: Python<'_>) -> PyResult<Bound<'_, PyAny>>;

/// Options, that are used to customize the download behaviour.
///
/// In the future, this might get a Builder api.
///
/// See `help(yt_dlp.YoutubeDL())` from python for a full list of available options.
#[derive(Default, Debug)]
pub struct YoutubeDLOptions {
    options: serde_json::Map<String, serde_json::Value>,
    progress_hook: Option<ProgressHookFunction>,
    post_processors: Vec<PostProcessorFunction>,
}

impl YoutubeDLOptions {
    #[must_use]
    pub fn new() -> Self {
        let me = Self {
            options: serde_json::Map::new(),
            progress_hook: None,
            post_processors: vec![],
        };

        me.with_post_processor(post_processors::dearrow::process)
    }

    #[must_use]
    pub fn set(self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
        let mut options = self.options;
        options.insert(key.into(), value.into());

        Self { options, ..self }
    }

    #[must_use]
    pub fn with_progress_hook(self, progress_hook: ProgressHookFunction) -> Self {
        if let Some(_previous_hook) = self.progress_hook {
            todo!()
        } else {
            Self {
                progress_hook: Some(progress_hook),
                ..self
            }
        }
    }

    #[must_use]
    pub fn with_post_processor(mut self, pp: PostProcessorFunction) -> Self {
        self.post_processors.push(pp);
        self
    }

    /// # Errors
    /// If the underlying [`YoutubeDL::from_options`] errors.
    pub fn build(self) -> Result<YoutubeDL, build::Error> {
        YoutubeDL::from_options(self)
    }

    #[must_use]
    pub fn from_json_options(options: serde_json::Map<String, serde_json::Value>) -> Self {
        Self {
            options,
            ..Self::new()
        }
    }

    #[must_use]
    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.options.get(key)
    }
}

impl YoutubeDL {
    /// Construct this instance from options.
    ///
    /// # Panics
    /// If `yt_dlp` changed their interface.
    ///
    /// # Errors
    /// If a python call fails.
    #[allow(clippy::too_many_lines)]
    pub fn from_options(options: YoutubeDLOptions) -> Result<Self, build::Error> {
        pyo3::prepare_freethreaded_python();

        let output_options = options.options.clone();

        let yt_dlp_module = Python::with_gil(|py| {
            let opts = json_loads(options.options, py);

            {
                static CALL_ONCE: sync::Once = sync::Once::new();

                CALL_ONCE.call_once(|| {
                    py.run(
                        c"
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
              ",
                        None,
                        None,
                    )
                    .unwrap_or_else(|err| {
                        panic!("Failed to disable python signal handling: {err}")
                    });
                });
            }

            {
                // Setup the progress hook
                if let Some(ph) = options.progress_hook {
                    opts.set_item(intern!(py, "progress_hooks"), vec![ph(py).wrap_exc(py)?])
                        .wrap_exc(py)?;
                }
            }

            {
                // Unconditionally set a logger.
                // Otherwise, yt_dlp will log to stderr.

                let ytdl_logger = setup_logging(py, "yt_dlp").wrap_exc(py)?;

                opts.set_item(intern!(py, "logger"), ytdl_logger)
                    .wrap_exc(py)?;
            }

            let inner = {
                let p_params = opts.into_bound_py_any(py).wrap_exc(py)?;
                let p_auto_init = true.into_bound_py_any(py).wrap_exc(py)?;

                py.import(intern!(py, "yt_dlp.YoutubeDL"))
                    .wrap_exc(py)?
                    .getattr(intern!(py, "YoutubeDL"))
                    .wrap_exc(py)?
                    .call1(
                        PyTuple::new(
                            py,
                            [
                                p_params.into_bound_py_any(py).wrap_exc(py)?,
                                p_auto_init.into_bound_py_any(py).wrap_exc(py)?,
                            ],
                        )
                        .wrap_exc(py)?,
                    )
                    .wrap_exc(py)?
            };

            {
                // Setup the post processors
                let add_post_processor_fun = inner.getattr(intern!(py, "add_post_processor")).wrap_exc(py)?;

                for pp in options.post_processors {
                    add_post_processor_fun
                        .call(
                            (pp(py).wrap_exc(py)?.into_bound_py_any(py).wrap_exc(py)?,),
                            // "when" can take any value in yt_dlp.utils.POSTPROCESS_WHEN
                            py_kw_args!(py => when = "pre_process"),
                        )
                        .wrap_exc(py)?;
                }
            }

            Ok::<_, PythonError>(inner.unbind())
        })?;

        Ok(Self {
            inner: yt_dlp_module,
            options: output_options,
        })
    }
}

#[allow(missing_docs)]
pub mod build {
    use crate::python_error::PythonError;

    #[derive(Debug, thiserror::Error)]
    pub enum Error {
        #[error(transparent)]
        Python(#[from] PythonError),
    }
}