dicom_web/
qido.rs

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
//! Module for QIDO-RS requests
use dicom_core::Tag;
use dicom_json::DicomJson;
use dicom_object::InMemDicomObject;

use snafu::ResultExt;

use crate::{DeserializationFailedSnafu, DicomWebClient, DicomWebError, RequestFailedSnafu};

/// A builder type for QIDO-RS requests
/// By default, the request is built with no filters, no limit, and no offset.
#[derive(Debug, Clone)]
pub struct QidoRequest {
    client: DicomWebClient,
    url: String,

    limit: Option<u32>,
    offset: Option<u32>,
    includefields: Vec<Tag>,
    fuzzymatching: Option<bool>,
    filters: Vec<(Tag, String)>,
}

impl QidoRequest {
    pub fn new(client: DicomWebClient, url: String) -> Self {
        QidoRequest {
            client,
            url,
            limit: None,
            offset: None,
            includefields: vec![],
            fuzzymatching: None,
            filters: vec![],
        }
    }

    /// Execute the QIDO-RS request
    pub async fn run(&self) -> Result<Vec<InMemDicomObject>, DicomWebError> {
        let mut query: Vec<(String, String)> = vec![];
        if let Some(limit) = self.limit {
            query.push((String::from("limit"), limit.to_string()));
        }
        if let Some(offset) = self.offset {
            query.push((String::from("offset"), offset.to_string()));
        }
        for include_field in self.includefields.iter() {
            // Convert the tag to a radix string
            let radix_string = format!(
                "{:04x}{:04x}",
                include_field.group(),
                include_field.element()
            );

            query.push((String::from("includefield"), radix_string));
        }
        for filter in self.filters.iter() {
            query.push((filter.0.to_string(), filter.1.clone()));
        }

        let mut request = self.client.client.get(&self.url).query(&query);

        // Basic authentication
        if let Some(username) = &self.client.username {
            request = request.basic_auth(username, self.client.password.as_ref());
        }
        // Bearer token
        else if let Some(bearer_token) = &self.client.bearer_token {
            request = request.bearer_auth(bearer_token);
        }

        let response = request
            .send()
            .await
            .context(RequestFailedSnafu { url: &self.url })?;

        if !response.status().is_success() {
            return Err(DicomWebError::HttpStatusFailure {
                status_code: response.status(),
            });
        }

        // Check if the response is a DICOM-JSON
        if let Some(ct) = response.headers().get("Content-Type") {
            if ct != "application/dicom+json" && ct != "application/json" {
                return Err(DicomWebError::UnexpectedContentType {
                    content_type: ct.to_str().unwrap_or_default().to_string(),
                });
            }
        } else {
            return Err(DicomWebError::MissingContentTypeHeader);
        }

        Ok(response
            .json::<Vec<DicomJson<InMemDicomObject>>>()
            .await
            .context(DeserializationFailedSnafu {})?
            .into_iter()
            .map(|dj| dj.into_inner())
            .collect())
    }

    /// Set the maximum number of results to return. Will be passed as a query parameter.
    /// This is useful for pagination.
    pub fn with_limit(&mut self, limit: u32) -> &mut Self {
        self.limit = Some(limit);
        self
    }

    /// Set the offset of the results to return. Will be passed as a query parameter.
    /// This is useful for pagination.
    pub fn with_offset(&mut self, offset: u32) -> &mut Self {
        self.offset = Some(offset);
        self
    }

    /// Set the tags that should be queried. Will be passed as a query parameter.
    pub fn with_includefields(&mut self, includefields: Vec<Tag>) -> &mut Self {
        self.includefields = includefields;
        self
    }

    /// Set whether fuzzy matching should be used. Will be passed as a query parameter.
    pub fn with_fuzzymatching(&mut self, fuzzymatching: bool) -> &mut Self {
        self.fuzzymatching = Some(fuzzymatching);
        self
    }

    /// Add a filter to the query. Will be passed as a query parameter.
    pub fn with_filter(&mut self, tag: Tag, value: String) -> &mut Self {
        self.filters.push((tag, value));
        self
    }
}

impl DicomWebClient {
    /// Create a QIDO-RS request to query all studies
    pub fn query_studies(&self) -> QidoRequest {
        let base_url = &self.qido_url;
        let url = format!("{base_url}/studies");

        QidoRequest::new(self.clone(), url)
    }

    /// Create a QIDO-RS request to query all series
    pub fn query_series(&self) -> QidoRequest {
        let base_url = &self.qido_url;
        let url = format!("{base_url}/series");

        QidoRequest::new(self.clone(), url)
    }

    /// Create a QIDO-RS request to query all series in a specific study
    pub fn query_series_in_study(&self, study_instance_uid: &str) -> QidoRequest {
        let base_url = &self.qido_url;
        let url = format!("{base_url}/studies/{study_instance_uid}/series");

        QidoRequest::new(self.clone(), url)
    }

    /// Create a QIDO-RS request to query all instances
    pub fn query_instances(&self) -> QidoRequest {
        let base_url = &self.qido_url;
        let url = format!("{base_url}/instances");

        QidoRequest::new(self.clone(), url)
    }

    /// Create a QIDO-RS request to query all instances in a specific series
    pub fn query_instances_in_series(
        &self,
        study_instance_uid: &str,
        series_instance_uid: &str,
    ) -> QidoRequest {
        let base_url = &self.qido_url;
        let url = format!(
            "{base_url}/studies/{study_instance_uid}/series/{series_instance_uid}/instances",
        );

        QidoRequest::new(self.clone(), url)
    }
}