-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
3896 lines (3555 loc) · 135 KB
/
lib.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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![warn(missing_debug_implementations)]
//! **orthanc-rs** is a client for the [REST API](https://book.orthanc-server.com/users/rest.html)
//! of [Orthanc](https://book.orthanc-server.com/users/rest.html), an open-source, lightweight
//! DICOM server.
//!
//! To use the crate, add the dependency to your `Cargo.toml`:
//!
//! ```ini
//! [dependencies]
//! orthanc = "0.5.1"
//! ```
//!
//! ## Usage
//!
//! Create an API client instance:
//!
//! ```rust
//! use orthanc::Client;
//! let client = Client::new("http://localhost:8042".to_string());
//! ```
//!
//! If authentication is enabled on the Orthanc instance:
//!
//! ```rust
//! client.auth("username".to_string(), "password".to_string());
//! ```
//!
//! List patients:
//!
//! ```rust
//! client.patients();
//! ```
//!
//! Or in an expanded format:
//!
//! ```rust
//! client.patients_expanded();
//! ```
//!
//! Get all DICOM tags of an instance:
//!
//! ```rust
//! let instance_id = "0b62ebce-8ab7b938-e5ca1b05-04802ab3-42ee4307";
//! let tags = client.instance_tags(instance_id);
//! println!("{}", tags["PatientID"]);
//! ```
//!
//! Download a study:
//!
//! ```rust
//! let study_id = "9357491d-427a6c94-4080b6c8-1997f4aa-af658240";
//! let mut file = fs::File::create("/tmp/study.zip").unwrap();
//! client.study_dicom(study_id, &mut file).unwrap();
//! ```
//!
//! Even though the operation is not very efficient, Orthanc allows uploading DICOM files over
//! REST API:
//!
//! ```rust
//! let data = fs::read("/tmp/instance.dcm").unwrap();
//! client.upload(&data).unwrap();
//! ```
use bytes::Bytes;
use chrono::NaiveDateTime;
use reqwest;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::io::prelude::*;
use std::result;
use std::str;
use std::time;
/// Orthanc entity types.
///
/// Orthanc operates with 4 entity types, which correspond to the ones, available in DICOM.
/// In descending hierarchical order: Patient, Study, Series, Instance
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub enum Entity {
Patient,
Study,
Series,
Instance,
}
/// Modality
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Modality {
#[serde(rename = "AET")]
pub aet: String,
pub host: String,
pub port: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub manufacturer: Option<String>,
#[serde(rename = "AllowEcho")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_c_echo: Option<bool>,
#[serde(rename = "AllowFind")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_c_find: Option<bool>,
#[serde(rename = "AllowGet")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_c_get: Option<bool>,
#[serde(rename = "AllowMove")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_c_move: Option<bool>,
#[serde(rename = "AllowStore")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_c_store: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_n_action: Option<bool>,
#[serde(rename = "AllowEventReport")]
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_n_event_report: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_transcoding: Option<bool>,
}
/// Patient
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Patient {
#[serde(rename = "ID")]
pub id: String,
pub is_stable: bool,
#[serde(with = "datetime_format")]
pub last_update: NaiveDateTime,
pub main_dicom_tags: HashMap<String, String>,
pub studies: Vec<String>,
#[serde(rename = "Type")]
pub entity: Entity,
#[serde(skip_serializing_if = "Option::is_none")]
pub anonymized_from: Option<String>,
}
impl Patient {
/// Get the value of a DICOM tag from `main_dicom_tags`
pub fn main_dicom_tag(&self, tag: &str) -> Option<&str> {
self.main_dicom_tags.get(tag).map(AsRef::as_ref)
}
}
/// Study
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Study {
#[serde(rename = "ID")]
pub id: String,
pub is_stable: bool,
#[serde(with = "datetime_format")]
pub last_update: NaiveDateTime,
pub main_dicom_tags: HashMap<String, String>,
pub parent_patient: String,
pub patient_main_dicom_tags: HashMap<String, String>,
pub series: Vec<String>,
#[serde(rename = "Type")]
pub entity: Entity,
#[serde(skip_serializing_if = "Option::is_none")]
pub anonymized_from: Option<String>,
}
impl Study {
/// Get the value of a DICOM tag from `main_dicom_tags`, or if the tag is absent there, from
/// `patient_main_dicom_tags`.
pub fn main_dicom_tag(&self, tag: &str) -> Option<&str> {
match self.main_dicom_tags.get(tag).map(AsRef::as_ref) {
Some(v) => Some(v),
None => self.patient_main_dicom_tags.get(tag).map(AsRef::as_ref),
}
}
}
/// Series
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Series {
#[serde(rename = "ID")]
pub id: String,
pub status: String,
pub is_stable: bool,
#[serde(with = "datetime_format")]
pub last_update: NaiveDateTime,
pub main_dicom_tags: HashMap<String, String>,
pub parent_study: String,
pub expected_number_of_instances: Option<u32>,
pub instances: Vec<String>,
#[serde(rename = "Type")]
pub entity: Entity,
#[serde(skip_serializing_if = "Option::is_none")]
pub anonymized_from: Option<String>,
}
impl Series {
/// Get the value of a DICOM tag from `main_dicom_tags`
pub fn main_dicom_tag(&self, tag: &str) -> Option<&str> {
self.main_dicom_tags.get(tag).map(AsRef::as_ref)
}
}
/// Instance
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Instance {
#[serde(rename = "ID")]
pub id: String,
pub main_dicom_tags: HashMap<String, String>,
pub parent_series: String,
pub index_in_series: Option<u32>,
pub file_uuid: String,
pub file_size: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_from: Option<String>,
#[serde(rename = "Type")]
pub entity: Entity,
#[serde(skip_serializing_if = "Option::is_none")]
pub anonymized_from: Option<String>,
}
impl Instance {
/// Get the value of a DICOM tag from `main_dicom_tags`
pub fn main_dicom_tag(&self, tag: &str) -> Option<&str> {
self.main_dicom_tags.get(tag).map(AsRef::as_ref)
}
}
/// Anonymization request body
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Anonymization {
#[serde(rename(serialize = "Replace"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub replace: Option<HashMap<String, String>>,
#[serde(rename(serialize = "Keep"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub keep: Option<Vec<String>>,
#[serde(rename(serialize = "KeepPrivateTags"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_private_tags: Option<bool>,
#[serde(rename(serialize = "DicomVersion"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub dicom_version: Option<String>,
#[serde(rename(serialize = "Force"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub force: Option<bool>,
}
/// Modification request body
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Modification {
#[serde(rename(serialize = "Replace"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub replace: Option<HashMap<String, String>>,
#[serde(rename(serialize = "Remove"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub remove: Option<Vec<String>>,
#[serde(rename(serialize = "Force"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub force: Option<bool>,
}
/// Ancestor of an entity
///
/// Returned as response body in DELETE responses to indicate the remaining ancestor of the deleted
/// entity.
///
/// For example, an ancestor of a deleted Instance is a Series, an ancestor of a deleted Study is a
/// Patient. Patient does not have an ancestor.
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Ancestor {
#[serde(rename = "ID")]
pub id: String,
pub path: String,
#[serde(rename = "Type")]
pub entity: Entity,
}
/// Remaining ancestor response
///
/// Returned as response body in DELETE responses. See `Ancestor` for details.
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct RemainingAncestor {
pub remaining_ancestor: Option<Ancestor>,
}
/// Result of a DICOM upload request
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct UploadResult {
#[serde(rename = "ID")]
pub id: String,
pub status: String,
pub path: String,
pub parent_patient: String,
pub parent_study: String,
pub parent_series: String,
}
/// Result of a C-STORE request (sending entities to a modality)
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct StoreResult {
pub description: String,
pub local_aet: String,
pub remote_aet: String,
pub parent_resources: Vec<String>,
pub instances_count: u64,
pub failed_instances_count: u64,
}
/// Result of a modification or anonymization request
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ModificationResult {
#[serde(rename = "ID")]
pub id: String,
#[serde(rename = "PatientID")]
pub patient_id: String,
pub path: String,
#[serde(rename = "Type")]
pub entity: Entity,
}
/// Structure of Orthanc's API error
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ApiError {
pub method: String,
pub uri: String,
pub message: String,
pub details: Option<String>,
pub http_status: u16,
pub http_error: String,
pub orthanc_status: u16,
pub orthanc_error: String,
}
type Result<T> = result::Result<T, Error>;
/// Error type
#[derive(Debug, Eq, PartialEq)]
pub struct Error {
pub message: String,
// TODO: This is pretty ugly
pub details: Option<ApiError>,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {:#?}", self.message, self.details)
}
}
impl Error {
fn new(msg: &str, api_error: Option<ApiError>) -> Error {
Error {
message: msg.to_string(),
details: api_error,
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Error::new(&e.to_string(), None)
}
}
impl From<serde_json::error::Error> for Error {
fn from(e: serde_json::error::Error) -> Self {
Error::new(&e.to_string(), None)
}
}
impl From<str::Utf8Error> for Error {
fn from(e: str::Utf8Error) -> Self {
Error::new(&e.to_string(), None)
}
}
/// Client type
///
/// The client itself is fairly simple. There are only 3 fields that the end-user should care
/// about: `server` (the address of the Orthanc server, an HTTP(S) URL), `username` and `password`.
///
/// Creating a new client instance:
///
/// ```
/// let client = Client::new("http://localhost:8042".to_string());
/// ```
///
/// Authentication (setting `username`/`password`) can be done by calling the `auth` method:
///
/// ```
/// client.auth("username".to_string(), "password".to_string());
/// ```
///
/// Or combined:
///
/// ```
/// let client = Client::new("http://localhost:8042".to_string())
/// .auth("username".to_string(), "password".to_string());
/// ```
#[derive(Debug)]
pub struct Client {
server: String,
username: Option<String>,
password: Option<String>,
client: reqwest::blocking::Client,
}
impl Client {
/// Creates a new client instance
///
/// ```
/// let client = Client::new("http://localhost:8042".to_string());
/// ```
pub fn new(server: String) -> Client {
let client = reqwest::blocking::ClientBuilder::new()
.timeout(time::Duration::from_secs(600))
.build()
// TODO: Should we be catching the error here?
.unwrap();
Client {
server,
username: None,
password: None,
client,
}
}
/// Adds authentication to the client instance
///
/// ```
/// let client = Client::new("http://localhost:8042".to_string())
/// .auth("username".to_string(), "password".to_string());
/// ```
pub fn auth(mut self, username: String, password: String) -> Client {
self.username = Some(username);
self.password = Some(password);
self
}
fn add_auth(
&self,
request: reqwest::blocking::RequestBuilder,
) -> reqwest::blocking::RequestBuilder {
match (&self.username, &self.password) {
(Some(u), Some(p)) => request.basic_auth(u, Some(p)),
_ => request,
}
}
fn get(&self, path: &str) -> Result<Bytes> {
let url = format!("{}/{}", self.server, &path);
let mut request = self.client.get(&url);
request = self.add_auth(request);
let resp = request.send()?;
let status = resp.status();
let body = resp.bytes()?;
check_http_error(status, body)
}
fn get_stream<W: Write>(&self, path: &str, writer: &mut W) -> Result<()> {
let url = format!("{}/{}", self.server, &path);
let mut request = self.client.get(&url);
request = self.add_auth(request);
let mut resp = request.send()?;
let status = resp.status();
// TODO: Simplify this
if status >= reqwest::StatusCode::BAD_REQUEST {
let message = format!("API error: {}", status);
let body = resp.bytes()?;
if body.is_empty() {
return Err(Error::new(&message, None));
};
return Err(Error::new(&message, serde_json::from_slice(&body)?));
}
resp.copy_to(writer)?;
Ok(())
}
fn post(&self, path: &str, data: Value) -> Result<Bytes> {
let url = format!("{}/{}", self.server, path);
let mut request = self.client.post(&url).json(&data);
request = self.add_auth(request);
let resp = request.send()?;
let status = resp.status();
let body = resp.bytes()?;
check_http_error(status, body)
}
fn post_receive_stream<W: Write>(
&self,
path: &str,
data: Value,
writer: &mut W,
) -> Result<()> {
let url = format!("{}/{}", self.server, path);
let mut request = self.client.post(&url).json(&data);
request = self.add_auth(request);
let mut resp = request.send()?;
let status = resp.status();
// TODO: Simplify this
if status >= reqwest::StatusCode::BAD_REQUEST {
let message = format!("API error: {}", status);
let body = resp.bytes()?;
if body.is_empty() {
return Err(Error::new(&message, None));
};
return Err(Error::new(&message, serde_json::from_slice(&body)?));
}
resp.copy_to(writer)?;
Ok(())
}
fn post_bytes(&self, path: &str, data: &[u8]) -> Result<Bytes> {
let url = format!("{}/{}", self.server, path);
// TODO: .to_vec() here is probably not a good idea?
let mut request = self.client.post(&url).body(data.to_vec());
request = self.add_auth(request);
let resp = request.send()?;
let status = resp.status();
let body = resp.bytes()?;
check_http_error(status, body)
}
fn put(&self, path: &str, data: Value) -> Result<Bytes> {
let url = format!("{}/{}", self.server, path);
let mut request = self.client.put(&url).json(&data);
request = self.add_auth(request);
let resp = request.send()?;
let status = resp.status();
let body = resp.bytes()?;
check_http_error(status, body)
}
fn delete(&self, path: &str) -> Result<Bytes> {
let url = format!("{}/{}", self.server, &path);
let mut request = self.client.delete(&url);
request = self.add_auth(request);
let resp = request.send()?;
let status = resp.status();
let body = resp.bytes()?;
check_http_error(status, body)
}
fn list(&self, entity: &str) -> Result<Vec<String>> {
let resp = self.get(entity)?;
let json: Vec<String> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// List modalities
pub fn modalities(&self) -> Result<Vec<String>> {
self.list("modalities")
}
/// List patients
pub fn patients(&self) -> Result<Vec<String>> {
self.list("patients")
}
/// List studies
pub fn studies(&self) -> Result<Vec<String>> {
self.list("studies")
}
/// List series
pub fn series_list(&self) -> Result<Vec<String>> {
self.list("series")
}
/// List instances
pub fn instances(&self) -> Result<Vec<String>> {
self.list("instances")
}
/// List all modalities in an expanded format
pub fn modalities_expanded(&self) -> Result<HashMap<String, Modality>> {
let resp = self.get("modalities?expand")?;
let json: HashMap<String, Modality> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// List all patients in an expanded format
pub fn patients_expanded(&self) -> Result<Vec<Patient>> {
let resp = self.get("patients?expand")?;
let json: Vec<Patient> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// List all studies in an expanded format
pub fn studies_expanded(&self) -> Result<Vec<Study>> {
let resp = self.get("studies?expand")?;
let json: Vec<Study> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// List all series in an expanded format
pub fn series_expanded(&self) -> Result<Vec<Series>> {
let resp = self.get("series?expand")?;
let json: Vec<Series> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// List all instances in an expanded format
pub fn instances_expanded(&self) -> Result<Vec<Instance>> {
let resp = self.get("instances?expand")?;
let json: Vec<Instance> = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get a patient by its ID
pub fn patient(&self, id: &str) -> Result<Patient> {
let resp = self.get(&format!("patients/{}", id))?;
let json: Patient = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get a study by its ID
pub fn study(&self, id: &str) -> Result<Study> {
let resp = self.get(&format!("studies/{}", id))?;
let json: Study = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get a series by its ID
pub fn series(&self, id: &str) -> Result<Series> {
let resp = self.get(&format!("series/{}", id))?;
let json: Series = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get an instance by its ID
pub fn instance(&self, id: &str) -> Result<Instance> {
let resp = self.get(&format!("instances/{}", id))?;
let json: Instance = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get all DICOM tags of an instance in a simplified format
///
/// See related Orthanc documentation
/// [section](https://book.orthanc-server.com/users/rest.html#accessing-the-dicom-fields-of-an-instance-as-a-json-file)
/// for details
pub fn instance_tags(&self, id: &str) -> Result<Value> {
let resp = self.get(&format!("instances/{}/simplified-tags", id))?;
let json: Value = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get all DICOM tags of an instance in an expanded format
///
/// See related Orthanc documentation
/// [section](https://book.orthanc-server.com/users/rest.html#accessing-the-dicom-fields-of-an-instance-as-a-json-file)
/// for details
pub fn instance_tags_expanded(&self, id: &str) -> Result<Value> {
let resp = self.get(&format!("instances/{}/tags", id))?;
let json: Value = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get all DICOM tags' codings of an instance
///
/// Returns a `Vec<String>` of the following format: `["0008-0018", "0040-0260", "0040-0254"]`
pub fn instance_content(&self, id: &str) -> Result<Vec<String>> {
let resp = self.get(&format!("instances/{}/content", id))?;
let json = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get the value of a specific DICOM tag of an instance
///
/// `tag` is the DICOM tag coding, e.g. `0008-0018`
pub fn instance_tag(&self, id: &str, tag: &str) -> Result<String> {
let resp = self.get(&format!("instances/{}/content/{}", id, tag))?;
Ok(String::from_utf8_lossy(&resp).trim().to_string())
}
/// Download a patient as a collection of DICOM files
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Streamed data is a ZIP archive
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/patient.zip").unwrap();
/// client().patient_dicom("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", &mut file).unwrap();
/// ```
pub fn patient_dicom<W: Write>(&self, id: &str, writer: &mut W) -> Result<()> {
let path = format!("patients/{}/archive", id);
self.get_stream(&path, writer)
}
/// Download a study as a collection of DICOM files
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Streamed data is a ZIP archive
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/study.zip").unwrap();
/// client().study_dicom("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", &mut file).unwrap();
/// ```
pub fn study_dicom<W: Write>(&self, id: &str, writer: &mut W) -> Result<()> {
let path = format!("studies/{}/archive", id);
self.get_stream(&path, writer)?;
Ok(())
}
/// Download a series as a collection of DICOM files
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Streamed data is a ZIP archive
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/series.zip").unwrap();
/// client().series_dicom("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", &mut file).unwrap();
/// ```
pub fn series_dicom<W: Write>(&self, id: &str, writer: &mut W) -> Result<()> {
let path = format!("series/{}/archive", id);
self.get_stream(&path, writer)
}
/// Download an instance as a DICOM file
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/instance.dcm").unwrap();
/// client().instance_dicom("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", &mut file).unwrap();
/// ```
pub fn instance_dicom<W: Write>(&self, id: &str, writer: &mut W) -> Result<()> {
let path = format!("instances/{}/file", id);
self.get_stream(&path, writer)
}
/// Delete a patient
pub fn delete_patient(&self, id: &str) -> Result<RemainingAncestor> {
let resp = self.delete(&format!("patients/{}", id))?;
let json: RemainingAncestor = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Delete a study
pub fn delete_study(&self, id: &str) -> Result<RemainingAncestor> {
let resp = self.delete(&format!("studies/{}", id))?;
let json: RemainingAncestor = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Delete a series
pub fn delete_series(&self, id: &str) -> Result<RemainingAncestor> {
let resp = self.delete(&format!("series/{}", id))?;
let json: RemainingAncestor = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Delete an instance
pub fn delete_instance(&self, id: &str) -> Result<RemainingAncestor> {
let resp = self.delete(&format!("instances/{}", id))?;
let json: RemainingAncestor = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Send a C-ECHO request to a remote modality
///
/// If no error is returned, the request was successful
pub fn echo(&self, modality: &str, timeout: Option<u32>) -> Result<()> {
let mut data = HashMap::new();
// TODO: This does not seem idiomatic
if timeout != None {
data.insert("Timeout", timeout);
}
self.post(
&format!("modalities/{}/echo", modality),
serde_json::json!(data),
)
.map(|_| ())
}
/// Send a C-STORE request to a remote modality
///
/// `ids` is a slice of entity IDs to send. An ID can signify either of Patient, Study, Series
/// or instance
pub fn store(&self, modality: &str, ids: &[&str]) -> Result<StoreResult> {
let resp = self.post(
&format!("modalities/{}/store", modality),
serde_json::json!(ids),
)?;
let json: StoreResult = serde_json::from_slice(&resp)?;
Ok(json)
}
fn anonymize(
&self,
entity: &str,
id: &str,
anonymization: Option<Anonymization>,
) -> Result<ModificationResult> {
let data = match anonymization {
Some(a) => a,
// TODO: Just pass an empty object?
None => Anonymization {
replace: None,
keep: None,
keep_private_tags: None,
dicom_version: None,
force: None,
},
};
let resp = self.post(
&format!("{}/{}/anonymize", entity, id),
serde_json::to_value(data)?,
)?;
let json: ModificationResult = serde_json::from_slice(&resp)?;
Ok(json)
}
fn modify(
&self,
entity: &str,
id: &str,
modification: Modification,
) -> Result<ModificationResult> {
let resp = self.post(
&format!("{}/{}/modify", entity, id),
serde_json::to_value(modification)?,
)?;
let json: ModificationResult = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Anonymize a patient
pub fn anonymize_patient(
&self,
id: &str,
anonymization: Option<Anonymization>,
) -> Result<ModificationResult> {
self.anonymize("patients", id, anonymization)
}
/// Anonymize a study
pub fn anonymize_study(
&self,
id: &str,
anonymization: Option<Anonymization>,
) -> Result<ModificationResult> {
self.anonymize("studies", id, anonymization)
}
/// Anonymize a series
pub fn anonymize_series(
&self,
id: &str,
anonymization: Option<Anonymization>,
) -> Result<ModificationResult> {
self.anonymize("series", id, anonymization)
}
/// Anonymize an instance
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/anonymized_instance.dcm").unwrap();
/// client().anonymize_instance("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", None, &mut file).unwrap();
/// ```
pub fn anonymize_instance<W: Write>(
&self,
id: &str,
anonymization: Option<Anonymization>,
writer: &mut W,
) -> Result<()> {
let data = match anonymization {
Some(a) => a,
// TODO: Just pass an empty object?
None => Anonymization {
replace: None,
keep: None,
keep_private_tags: None,
dicom_version: None,
force: None,
},
};
self.post_receive_stream(
&format!("instances/{}/anonymize", id),
serde_json::to_value(data)?,
writer,
)?;
Ok(())
}
/// Modify a patient
pub fn modify_patient(
&self,
id: &str,
modification: Modification,
) -> Result<ModificationResult> {
self.modify("patients", id, modification)
}
/// Modify a study
pub fn modify_study(
&self,
id: &str,
modification: Modification,
) -> Result<ModificationResult> {
self.modify("studies", id, modification)
}
/// Modify a series
pub fn modify_series(
&self,
id: &str,
modification: Modification,
) -> Result<ModificationResult> {
self.modify("series", id, modification)
}
/// Modify an instance
///
/// Accepts a mutable reference to an object, that implements a `Write` trait, and mutates the
/// object, writing the data into it in a streaming fashion.
///
/// Example:
///
/// ```
/// let mut file = fs::File::create("/tmp/modified_instance.dcm").unwrap();
/// let modification = Modification {
/// replace: None,
/// remove: vec!["PatientName"],
/// force: false,
/// };
/// client().modify_instance("3693b9d5-8b0e2a80-2cf45dda-d19e7c22-8749103c", modification, &mut file).unwrap();
/// ```
pub fn modify_instance<W: Write>(
&self,
id: &str,
modification: Modification,
writer: &mut W,
) -> Result<()> {
self.post_receive_stream(
&format!("instances/{}/modify", id),
serde_json::to_value(modification)?,
writer,
)?;
Ok(())
}
/// Upload a DICOM file to Orthanc
///
/// ```
/// let data = fs::read("/tmp/instance.dcm").unwrap();
/// let client = Client::new("http://localhost:8042");
/// client.upload(&data).unwrap();
/// ```
pub fn upload(&self, data: &[u8]) -> Result<UploadResult> {
let resp = self.post_bytes("instances", data)?;
let json: UploadResult = serde_json::from_slice(&resp)?;
Ok(json)
}
// TODO: The following two methods are exactly the same
/// Create a modality
pub fn create_modality(&self, name: &str, modality: Modality) -> Result<()> {
self.put(
&format!("modalities/{}", name),
serde_json::to_value(modality)?,
)
.map(|_| ())
}
/// Modify a modality
pub fn modify_modality(&self, name: &str, modality: Modality) -> Result<()> {
self.put(
&format!("modalities/{}", name),
serde_json::to_value(modality)?,