Debian Codegraph @

python/src/nanopub.rs

raw
1 use nanopub::{get_np_server as get_server, profile::gen_keys, Nanopub, NpProfile, ProfileBuilder};
2 use pyo3::{exceptions::PyException, prelude::*, pymethods};
3 use pythonize::pythonize;
4 // use pyo3::types::IntoPyDict;
5 // use pyo3_asyncio::generic::future_into_py;
6 use tokio::runtime::Runtime;
7
8 #[pyclass(name = "Nanopub", module = "nanopub_sign")]
9 #[derive(Clone)]
10 pub struct NanopubPy {
11 np: Nanopub,
12 }
13
14 #[pymethods]
15 impl NanopubPy {
16 #[new]
17 #[pyo3(signature = (rdf))]
18 fn new(rdf: &str) -> PyResult<Self> {
19 Nanopub::new(rdf)
20 .map(|np| Self { np })
21 .map_err(|e| PyErr::new::<PyException, _>(format!("{e}")))
22 }
23
24 // NOTE: we need to use staticmethod because we can't access self.np otherwise
25
26 // #[staticmethod]
27 // #[pyo3(text_signature = "(rdf)")]
28 // fn check(rdf: &str) -> PyResult<Self> {
29 // Nanopub::new(rdf)
30 // .map_err(|e| PyErr::new::<PyException, _>(format!("Error Checking: {e}")))?
31 // .check()
32 // .map(|np| Self { np })
33 // .map_err(|e| PyErr::new::<PyException, _>(format!("Error Checking: {e}")))
34 // }
35
36 // NOTE: should we make check a class method (instead of static)?
37 // But error with IRI in sophia dataset when cloning
38 #[pyo3()]
39 fn check(&self) -> PyResult<Self> {
40 self.np
41 .clone()
42 .check()
43 .map(|np| Self { np })
44 .map_err(|e| PyErr::new::<PyException, _>(format!("Error checking: {e}")))
45 }
46
47 #[pyo3(signature = (profile))]
48 fn sign(&self, profile: &NpProfilePy) -> PyResult<Self> {
49 self.np
50 .clone()
51 .sign(&profile.profile)
52 .map(|np| Self { np })
53 .map_err(|e| PyErr::new::<PyException, _>(format!("Error signing: {e}")))
54 }
55
56 #[pyo3(signature = (profile, server_url=None))]
57 fn publish(&self, profile: &NpProfilePy, server_url: Option<&str>) -> PyResult<Self> {
58 let server_url = server_url.map(str::to_string);
59 // Use a tokio runtime to wait on the async operation
60 let rt = Runtime::new()
61 .map_err(|e| PyErr::new::<PyException, _>(format!("Runtime failed: {e}")))?;
62 let result: Result<Nanopub, PyErr> = rt.block_on(async move {
63 self.np
64 .clone()
65 .publish(Some(&profile.profile.clone()), server_url.as_deref())
66 .await
67 .map_err(|e| PyErr::new::<PyException, _>(format!("Error publishing: {e}")))
68 });
69 result.map(|np| Self { np })
70 }
71
72 #[staticmethod]
73 #[pyo3(signature = (profile, server_url=None))]
74 fn publish_intro(profile: &NpProfilePy, server_url: Option<&str>) -> PyResult<Self> {
75 let server_url = server_url.map(str::to_string);
76 // Use a tokio runtime to wait on the async operation
77 let rt = Runtime::new()
78 .map_err(|e| PyErr::new::<PyException, _>(format!("Runtime failed: {e}")))?;
79 let result = rt.block_on(async move {
80 // let np = Nanopub::new_intro(&profile.profile)
81 // .map(|np| Self { np })
82 // .map_err(|e| PyErr::new::<PyException, _>(format!("{e}")));
83 let np = match Nanopub::new_intro(&profile.profile) {
84 Ok(np) => np,
85 Err(e) => {
86 return Err(PyErr::new::<PyException, _>(format!(
87 "Failed to create nanopub introduction: {e}"
88 )))
89 }
90 };
91 // match np.publish(Some(&profile), Some(&server_url)).await {
92 // Ok(np) => Ok(JsValue::from(Nanopub { np })),
93 // Err(e) => Err(JsValue::from_str(&format!(
94 // "Error publishing Nanopub Introduction: {e}"
95 // ))),
96 // }
97 np.publish(Some(&profile.profile), server_url.as_deref())
98 .await
99 .map_err(|e| PyErr::new::<PyException, _>(format!("Error publishing: {e}")))
100 });
101 result.map(|np| Self { np })
102 }
103
104 #[staticmethod]
105 #[pyo3(signature = (uri))]
106 fn fetch(uri: &str) -> PyResult<Self> {
107 let rt = Runtime::new()
108 .map_err(|e| PyErr::new::<PyException, _>(format!("Runtime failed: {e}")))?;
109 let result = rt.block_on(async move {
110 Nanopub::fetch(uri)
111 .await
112 .map_err(|e| PyErr::new::<PyException, _>(format!("Error fetching: {e}")))
113 });
114 result.map(|np| Self { np })
115 }
116
117 #[pyo3()]
118 fn rdf(&self, _py: Python<'_>) -> PyResult<String> {
119 // py.allow_threads(|| Ok(self.np.rdf()))
120 self.np
121 .rdf()
122 .map_err(|e| PyErr::new::<PyException, _>(format!("Error getting RDF: {e}")))
123 }
124
125 #[pyo3()]
126 fn info(&self, py: Python<'_>) -> PyResult<PyObject> {
127 pythonize(py, &self.np.info)
128 .map(|bound| bound.into())
129 .map_err(|e| {
130 PyErr::new::<PyException, _>(format!("Error converting struct info to dict: {e}"))
131 })
132 }
133
134 // TODO: use pyo3-asyncio https://pyo3.rs/v0.21.1/ecosystem/async-await
135 // ASYNC WITH TOKIO
136 // #[staticmethod]
137 // #[pyo3(text_signature = "(rdf, profile, server_url)")]
138 // fn apublish(py: Python<'_>, rdf: &str, profile: &NpProfilePy, server_url: Option<&str>) -> PyResult<PyObject> {
139 // let rdf = rdf.to_string();
140 // let profile = profile.profile.clone();
141 // let server_url = server_url.map(str::to_string);
142
143 // let future = async move {
144 // let np = Nanopub::publish(&rdf, &profile, server_url.as_deref()).await.unwrap();
145 // Ok(NanopubPy { np })
146 // };
147 // Ok(future_into_py(py, future)?.into())
148 // }
149
150 // SYNC WITH FUTURES
151 // #[staticmethod]
152 // #[pyo3(text_signature = "(rdf, private_key, server_url=None)")]
153 // fn publish(
154 // rdf: &str,
155 // profile: &NpProfilePy,
156 // server_url: Option<&str>,
157 // // py: Python<'_>,
158 // ) -> PyResult<Self> {
159 // // py.allow_threads(|| { // Put code in this block to enable true parallel https://pyo3.rs/v0.20.0/parallelism
160 // let rdf = rdf.to_string();
161 // let profile = profile.profile.clone();
162 // let server_url = server_url.map(str::to_string);
163
164 // let future = async move {
165 // Self {
166 // np: Nanopub::publish(&rdf, &profile, server_url.as_deref()).await.unwrap()
167 // // .map_err(|e| PyErr::new::<pyo3::exceptions::PyException, _>(format!("Error: {}", e)))
168 // }
169 // };
170 // Ok(block_on(future))
171 // }
172
173 // ASYNC WITH FUTURES
174 // #[staticmethod]
175 // #[pyo3(text_signature = "(rdf, profile, server_url)")]
176 // fn apublish(py: Python<'_>, rdf: &str, profile: &NpProfilePy, server_url: Option<&str>) -> PyResult<PyObject> {
177 // let rdf = rdf.to_string();
178 // let profile = profile.profile.clone();
179 // let server_url = server_url.map(str::to_string);
180
181 // let future = async move {
182 // let np = Nanopub::publish(&rdf, &profile, server_url.as_deref()).await.unwrap();
183 // Ok(NanopubPy { np })
184 // };
185
186 // // Use FutureExt to convert the future into a Python-compatible future
187 // let py_future = future.boxed().into_py(py);
188
189 // // Return the Python future object
190 // Ok(py_future)
191 // }
192 }
193
194 #[pyclass(name = "NpProfile", module = "nanopub_sign")]
195 #[derive(Clone)]
196 pub struct NpProfilePy {
197 profile: NpProfile,
198 }
199
200 #[pymethods]
201 impl NpProfilePy {
202 #[new]
203 // #[args(orcid_id = "None", name = "None", introduction_nanopub_uri = "None")]
204 #[pyo3(signature = (private_key, orcid_id=None, name=None, introduction_nanopub_uri=None))]
205 // #[pyo3(text_signature = "(private_key, orcid_id=None, name=None, introduction_nanopub_uri=None)")]
206 fn new(
207 private_key: String,
208 orcid_id: Option<String>,
209 name: Option<String>,
210 introduction_nanopub_uri: Option<String>,
211 ) -> PyResult<Self> {
212 let mut profile = ProfileBuilder::new(private_key);
213 if let Some(orcid_id) = orcid_id {
214 profile = profile.with_orcid(orcid_id);
215 };
216 if let Some(name) = name {
217 profile = profile.with_name(name);
218 };
219 if let Some(intro_np_uri) = introduction_nanopub_uri {
220 profile = profile.with_intro_nanopub(intro_np_uri);
221 };
222 Ok(Self {
223 profile: profile
224 .build()
225 .map_err(|e| PyErr::new::<PyException, _>(format!("Error getting profile: {e}")))?,
226 })
227 }
228 }
229
230 #[pyclass(name = "KeyPair", module = "nanopub_sign")]
231 #[derive(Clone)]
232 pub struct KeyPair {
233 #[pyo3(get)]
234 pub private: String,
235 #[pyo3(get)]
236 pub public: String,
237 }
238
239 #[pymethods]
240 impl KeyPair {
241 #[new]
242 #[pyo3(signature = ())]
243 fn new() -> PyResult<Self> {
244 gen_keys()
245 .map(|(private, public)| Self { private, public })
246 .map_err(|e| PyErr::new::<PyException, _>(format!("Error generating key pair: {e}")))
247 }
248 }
249
250 /// Return a random server
251 #[pyfunction]
252 #[pyo3(signature = (random=true))]
253 pub fn get_np_server(random: Option<bool>) -> PyResult<String> {
254 Ok(get_server(random.unwrap_or(true)).to_string())
255 }