about summary refs log tree commit diff stats
path: root/crates/yt_dlp/src/info_json.rs
blob: 31f4a692fef71c2969e11fa2fb1b0fa2e94f9d88 (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
// 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 rustpython::vm::{
    PyRef, VirtualMachine,
    builtins::{PyDict, PyStr},
};

pub type InfoJson = serde_json::Map<String, serde_json::Value>;

pub fn json_loads(
    input: serde_json::Map<String, serde_json::Value>,
    vm: &VirtualMachine,
) -> PyRef<PyDict> {
    let json = vm.import("json", 0).expect("Module exists");
    let loads = json.get_attr("loads", vm).expect("Method exists");
    let self_str = serde_json::to_string(&serde_json::Value::Object(input)).expect("Vaild json");
    let dict = loads
        .call((self_str,), vm)
        .expect("Vaild json is always a valid dict");

    dict.downcast().expect("Should always be a dict")
}

/// # Panics
/// If expectation about python operations fail.
pub fn json_dumps(
    input: PyRef<PyDict>,
    vm: &VirtualMachine,
) -> serde_json::Map<String, serde_json::Value> {
    let json = vm.import("json", 0).expect("Module exists");
    let dumps = json.get_attr("dumps", vm).expect("Method exists");
    let dict = dumps
        .call((input,), vm)
        .map_err(|err| vm.print_exception(err))
        .expect("Might not always work, but for our dicts it works");

    let string: PyRef<PyStr> = dict.downcast().expect("Should always be a string");

    let real_string = string.to_str().expect("Should be valid utf8");

    // {
    //     let mut file = File::create("debug.dump.json").unwrap();
    //     write!(file, "{}", real_string).unwrap();
    // }

    let value: serde_json::Value = serde_json::from_str(real_string).expect("Should be valid json");

    match value {
        serde_json::Value::Object(map) => map,
        _ => unreachable!("These should not be json.dumps output"),
    }
}