File: WadoRs.cpp

package info (click to toggle)
orthanc-dicomweb 1.7%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,592 kB
  • sloc: javascript: 34,006; cpp: 14,041; python: 418; sh: 127; makefile: 31
file content (1306 lines) | stat: -rw-r--r-- 40,502 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2021 Osimis S.A., Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


#include "../Resources/Orthanc/Plugins/OrthancPluginCppWrapper.h"
#include "Configuration.h"
#include "DicomWebFormatter.h"

#include <Compatibility.h>
#include <ChunkedBuffer.h>
#include <Logging.h>
#include <Toolbox.h>

#include <memory>


static const char* const MAIN_DICOM_TAGS = "MainDicomTags";
static const char* const INSTANCES = "Instances";
static const char* const PATIENT_MAIN_DICOM_TAGS = "PatientMainDicomTags";


static std::string GetResourceUri(Orthanc::ResourceType level,
                                  const std::string& publicId)
{
  switch (level)
  {
    case Orthanc::ResourceType_Study:
      return "/studies/" + publicId;
      
    case Orthanc::ResourceType_Series:
      return "/series/" + publicId;
      
    case Orthanc::ResourceType_Instance:
      return "/instances/" + publicId;
      
    default:
      throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
  }
}



static void AcceptMultipartDicom(bool& transcode,
                                 Orthanc::DicomTransferSyntax& targetSyntax /* only if transcoding */,
                                 const OrthancPluginHttpRequest* request)
{
  /**
   * Up to release 1.4 of the DICOMweb plugin, WADO-RS
   * RetrieveInstance, RetrieveSeries and RetrieveStudy did *NOT*
   * transcode if no transer syntax was explicitly provided. This was
   * because the DICOM standard didn't specify a behavior in this case
   * up to DICOM 2016b:
   * http://dicom.nema.org/medical/dicom/2016b/output/chtml/part18/sect_6.5.3.html
   *
   * However, starting with DICOM 2016c, it is explicitly stated that
   * "If transfer-syntax is not specified in the dcm-parameters the
   * origin server shall use the Explicit VR Little Endian Transfer
   * Syntax "1.2.840.10008.1.2.1" for each Instance":
   * http://dicom.nema.org/medical/dicom/2016c/output/chtml/part18/sect_6.5.3.html
   * 
   * As a consequence, starting with release 1.5 of the DICOMweb
   * plugin, transcoding to "Little Endian Explicit" takes place by
   * default. If this transcoding is not desirable, the "Accept" HTTP
   * header can be set to
   * "multipart/related;type=application/dicom;transfer-syntax=*" (not
   * the asterisk "*") in order to prevent transcoding. The same
   * convention is used by the Google Cloud Platform:
   * https://cloud.google.com/healthcare/docs/dicom
   **/
  transcode = true;
  targetSyntax = Orthanc::DicomTransferSyntax_LittleEndianExplicit;
  
  std::string accept;

  if (!OrthancPlugins::LookupHttpHeader(accept, request, "accept"))
  {
    return;   // By default, return "multipart/related; type=application/dicom;"
  }

  std::string application;
  std::map<std::string, std::string> attributes;
  OrthancPlugins::ParseContentType(application, attributes, accept);

  if (application != "multipart/related" &&
      application != "*/*")
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "This WADO-RS plugin cannot generate the following content type: " + accept);
  }

  if (attributes.find("type") != attributes.end())
  {
    std::string s = attributes["type"];
    Orthanc::Toolbox::ToLowerCase(s);
    if (s != "application/dicom")
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                      "This WADO-RS plugin only supports application/dicom "
                                      "return type for DICOM retrieval (" + accept + ")");
    }
  }

  static const char* const TRANSFER_SYNTAX = "transfer-syntax";

  std::map<std::string, std::string>::const_iterator found = attributes.find(TRANSFER_SYNTAX);
  if (found != attributes.end())
  {
    /**
     * The "*" case below is related to Google Healthcare API:
     * https://groups.google.com/d/msg/orthanc-users/w1Ekrsc6-U8/T2a_DoQ5CwAJ
     **/
    if (found->second == "*")
    {
      transcode = false;
    }
    else
    {
      transcode = true;

      if (!Orthanc::LookupTransferSyntax(targetSyntax, found->second))
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                        "Unsupported transfer syntax in WADO-RS: " + found->second);
      }
    }
  }
}



static bool AcceptMetadata(const OrthancPluginHttpRequest* request,
                           bool& isXml)
{
  isXml = false;    // By default, return application/dicom+json

  std::string accept;
  if (!OrthancPlugins::LookupHttpHeader(accept, request, "accept"))
  {
    return true;
  }

  std::string application;
  std::map<std::string, std::string> attributes;
  OrthancPlugins::ParseContentType(application, attributes, accept);

  std::vector<std::string> applicationTokens;
  Orthanc::Toolbox::TokenizeString(applicationTokens, application, ',');

  for (size_t i = 0; i < applicationTokens.size(); i++)
  {
    std::string token = Orthanc::Toolbox::StripSpaces(applicationTokens[i]);
    
    if (token == "application/json" ||
        token == "application/dicom+json" ||
        token == "*/*")
    {
      return true;
    }
  }

  if (application != "multipart/related")
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "This WADO-RS plugin cannot generate the following content type: " + accept);
  }

  if (attributes.find("type") != attributes.end())
  {
    std::string s = attributes["type"];
    Orthanc::Toolbox::ToLowerCase(s);
    if (s == "application/dicom+xml")
    {
      isXml = true;
    }
    else
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                      "This WADO-RS plugin only supports application/dicom+xml "
                                      "type for multipart/related accept (" + accept + ")");
    }
  }
  else
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "Missing \"type\" in multipart/related accept type (" + accept + ")");
  }

  if (attributes.find("transfer-syntax") != attributes.end())
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "This WADO-RS plugin cannot change the transfer syntax to " + 
                                    attributes["transfer-syntax"]);
  }

  return true;
}



static bool AcceptBulkData(const OrthancPluginHttpRequest* request)
{
  std::string accept;

  if (!OrthancPlugins::LookupHttpHeader(accept, request, "accept"))
  {
    return true;   // By default, return "multipart/related; type=application/octet-stream;"
  }

  std::string application;
  std::map<std::string, std::string> attributes;
  OrthancPlugins::ParseContentType(application, attributes, accept);

  if (application != "multipart/related" &&
      application != "*/*")
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "This WADO-RS plugin cannot generate the following "
                                    "bulk data type: " + accept);
  }

  if (attributes.find("type") != attributes.end())
  {
    std::string s = attributes["type"];
    Orthanc::Toolbox::ToLowerCase(s);
    if (s != "application/octet-stream")
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                      "This WADO-RS plugin only supports application/octet-stream "
                                      "return type for bulk data retrieval (" + accept + ")");
    }
  }

  if (attributes.find("ra,ge") != attributes.end())
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                    "This WADO-RS plugin does not support Range retrieval, "
                                    "it can only return entire bulk data object");
  }

  return true;
}


static void AnswerListOfDicomInstances(OrthancPluginRestOutput* output,
                                       Orthanc::ResourceType level,
                                       const std::string& publicId,
                                       bool transcode,
                                       Orthanc::DicomTransferSyntax targetSyntax /* only if transcoding */)
{
  if (level != Orthanc::ResourceType_Study &&
      level != Orthanc::ResourceType_Series &&
      level != Orthanc::ResourceType_Instance)
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
  }

  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();

  Json::Value instances;

  if (level == Orthanc::ResourceType_Instance)
  {
    Json::Value tmp = Json::objectValue;
    tmp["ID"] = publicId;
    
    instances = Json::arrayValue;
    instances.append(tmp);
  }
  else
  {
    if (!OrthancPlugins::RestApiGet(instances, GetResourceUri(level, publicId) + "/instances", false))
    {
      // Internal error
      OrthancPluginSendHttpStatusCode(context, output, 400);
      return;
    }
  }

  if (OrthancPluginStartMultipartAnswer(context, output, "related", "application/dicom"))
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
  }

  for (Json::Value::ArrayIndex i = 0; i < instances.size(); i++)
  {
    const std::string uri = "/instances/" + instances[i]["ID"].asString();

    bool transcodeThisInstance;
    
    std::string sourceTransferSyntax;
    if (!transcode)
    {
      transcodeThisInstance = false;      
    }
    else if (OrthancPlugins::RestApiGetString(sourceTransferSyntax, uri + "/metadata/TransferSyntax", false))
    {
      // Avoid transcoding if the source file already uses the expected transfer syntax
      Orthanc::DicomTransferSyntax syntax;
      if (Orthanc::LookupTransferSyntax(syntax, sourceTransferSyntax))
      {
        transcodeThisInstance = (syntax != targetSyntax);
      }
      else
      {
        transcodeThisInstance = true;
      }
    }
    else
    {
      // The transfer syntax of the source file is unknown, transcode it to be sure
      transcodeThisInstance = true;
    }
    
    OrthancPlugins::MemoryBuffer dicom;
    if (dicom.RestApiGet(uri + "/file", false))
    {
      if (transcodeThisInstance)
      {
        std::unique_ptr<OrthancPlugins::DicomInstance> transcoded(
          OrthancPlugins::DicomInstance::Transcode(
            dicom.GetData(), dicom.GetSize(), Orthanc::GetTransferSyntaxUid(targetSyntax)));

        if (OrthancPluginSendMultipartItem(
              context, output, reinterpret_cast<const char*>(transcoded->GetBuffer()),
              transcoded->GetSize()) != 0)
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
        }
      }
      else
      {
        if (OrthancPluginSendMultipartItem(context, output, dicom.GetData(), dicom.GetSize()) != 0)
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
        }
      }
    }
  }
}



namespace
{
  class SetOfDicomInstances : public boost::noncopyable
  {
  private:
    std::vector<Orthanc::DicomMap*>  instances_;

  public:
    ~SetOfDicomInstances()
    {
      for (size_t i = 0; i < instances_.size(); i++)
      {
        assert(instances_[i] != NULL);
        delete instances_[i];
      }
    }

    size_t GetSize() const
    {
      return instances_.size();
    }

    bool ReadInstance(const std::string& publicId)
    {
      Json::Value dicomAsJson;
      
      if (OrthancPlugins::RestApiGet(dicomAsJson, "/instances/" + publicId + "/tags", false))
      {
        std::unique_ptr<Orthanc::DicomMap> instance(new Orthanc::DicomMap);
        instance->FromDicomAsJson(dicomAsJson);
        instances_.push_back(instance.release());
        
        return true;
      }
      else
      {
        return false;
      }
    }

    
    void MinorityReport(Orthanc::DicomMap& target,
                        const Orthanc::DicomTag& tag) const
    {
      typedef std::map<std::string, unsigned int>  Counters;

      Counters counters;

      for (size_t i = 0; i < instances_.size(); i++)
      {
        assert(instances_[i] != NULL);

        std::string value;
        if (instances_[i]->LookupStringValue(value, tag, false))
        {
          Counters::iterator found = counters.find(value);
          if (found == counters.end())
          {
            counters[value] = 1;
          }
          else
          {
            found->second ++;
          }
        }
      }

      if (!counters.empty())
      {
        Counters::const_iterator current = counters.begin();
          
        std::string maxValue = current->first;
        size_t maxCount = current->second;

        ++current;

        while (current != counters.end())
        {
          if (maxCount < current->second)
          {
            maxValue = current->first;
            maxCount = current->second;
          }
            
          ++current;
        }

        target.SetValue(tag, maxValue, false);

        // Take the ceiling of the number of available instances
        const size_t threshold = instances_.size() / 2 + 1;
        if (maxCount < threshold)
        {
          LOG(WARNING) << "No consensus on the value of a tag during WADO-RS Retrieve "
                       << "Metadata in Extrapolate mode: " << tag.Format();
        }
      }
    }
  };

  
  class MainDicomTagsCache : public boost::noncopyable
  {
  private:
    struct Info : public boost::noncopyable
    {
      Orthanc::DicomMap  dicom_;
      std::string        parent_;
    };
    
    typedef std::pair<std::string, Orthanc::ResourceType>  Index;
    typedef std::map<Index, Info*>                         Content;

    Content  content_;

    static bool ReadResource(Orthanc::DicomMap& dicom,
                             std::string& parent,
                             OrthancPlugins::MetadataMode mode,
                             const std::string& orthancId,
                             Orthanc::ResourceType level)
    {
      std::string uri;
      std::string parentField;

      switch (level)
      {
        case Orthanc::ResourceType_Study:
          uri = "/studies/" + orthancId;
          break;
            
        case Orthanc::ResourceType_Series:
          uri = "/series/" + orthancId;
          parentField = "ParentStudy";
          break;
            
        case Orthanc::ResourceType_Instance:
          uri = "/instances/" + orthancId;
          parentField = "ParentSeries";
          break;

        default:
          throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
      }

      Json::Value value;
      if (!OrthancPlugins::RestApiGet(value, uri, false))
      {
        return false;
      }
         

      if (value.type() != Json::objectValue ||
          !value.isMember(MAIN_DICOM_TAGS))
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
      }

      dicom.ParseMainDicomTags(value[MAIN_DICOM_TAGS], level);

      if (level == Orthanc::ResourceType_Study)
      {
        if (value.isMember(PATIENT_MAIN_DICOM_TAGS))
        {
          dicom.ParseMainDicomTags(value[PATIENT_MAIN_DICOM_TAGS], Orthanc::ResourceType_Patient);
        }
        else
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
        }
      }
        
      if (!parentField.empty())
      {
        if (value.isMember(parentField) &&
            value[parentField].type() == Json::stringValue)
        {
          parent = value[parentField].asString();
        }
        else
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
        }
      }

      
      if (mode == OrthancPlugins::MetadataMode_Extrapolate &&
          (level == Orthanc::ResourceType_Series ||
           level == Orthanc::ResourceType_Study))
      {
        std::set<Orthanc::DicomTag> tags;
        OrthancPlugins::Configuration::GetExtrapolatedMetadataTags(tags, level);

        if (!tags.empty())
        {
          /**
           * Complete the series/study-level tags, with instance-level
           * tags that are not considered as "main DICOM tags" in
           * Orthanc, but that are necessary for Web viewers, and that
           * are expected to be constant throughout all the instances of
           * the study/series. To this end, we read up to "N" DICOM
           * instances of this study/series from disk, and for the tags
           * of interest, we look at whether there is a consensus in the
           * value among these instances. Obviously, this is an
           * approximation to improve performance.
           **/

          std::set<std::string> allInstances;

          switch (level)
          {
            case Orthanc::ResourceType_Series:
              if (!value.isMember(INSTANCES) ||
                  value[INSTANCES].type() != Json::arrayValue)
              {
                throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
              }
              else
              {
                for (Json::Value::ArrayIndex i = 0; i < value[INSTANCES].size(); i++)
                {
                  if (value[INSTANCES][i].type() != Json::stringValue)
                  {
                    throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
                  }
                  else
                  {
                    allInstances.insert(value[INSTANCES][i].asString());
                  }            
                }
              }
              
              break;

            case Orthanc::ResourceType_Study:
            {
              Json::Value tmp;
              if (OrthancPlugins::RestApiGet(tmp, "/studies/" + orthancId + "/instances", false))
              {
                if (tmp.type() != Json::arrayValue)
                {
                  throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
                }

                for (Json::Value::ArrayIndex i = 0; i < tmp.size(); i++)
                {
                  if (tmp[i].type() != Json::objectValue ||
                      !tmp[i].isMember("ID") ||
                      tmp[i]["ID"].type() != Json::stringValue)
                  {
                    throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
                  }
                  else
                  {
                    allInstances.insert(tmp[i]["ID"].asString());
                  }
                }
              }
              
              break;
            }

            default:
              throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
          }

          
          // Select up to N random instances. The instances are
          // implicitly selected randomly, as the public ID of an
          // instance is a SHA-1 hash (whose domain is uniformly distributed)

          static const size_t N = 3;
          SetOfDicomInstances selectedInstances;

          for (std::set<std::string>::const_iterator it = allInstances.begin();
               selectedInstances.GetSize() < N && it != allInstances.end(); ++it)
          {
            selectedInstances.ReadInstance(*it);
          }

          for (std::set<Orthanc::DicomTag>::const_iterator
                 it = tags.begin(); it != tags.end(); ++it)
          {
            selectedInstances.MinorityReport(dicom, *it);
          }
        }
      }

      return true;
    }
    

    bool Lookup(Orthanc::DicomMap& dicom,
                std::string& parent,
                OrthancPlugins::MetadataMode mode,
                const std::string& orthancId,
                Orthanc::ResourceType level)
    {
      Content::iterator found = content_.find(std::make_pair(orthancId, level));
      
      if (found == content_.end())
      {
        std::unique_ptr<Info> info(new Info);
        if (!ReadResource(info->dicom_, info->parent_, mode, orthancId, level))
        {
          return false;
        }

        found = content_.insert(std::make_pair(std::make_pair(orthancId, level), info.release())).first;
      }

      assert(found != content_.end() &&
             found->second != NULL);
      dicom.Merge(found->second->dicom_);
      parent = found->second->parent_;

      return true;
    }


  public:
    ~MainDicomTagsCache()
    {
      for (Content::iterator it = content_.begin(); it != content_.end(); ++it)
      {
        assert(it->second != NULL);
        delete it->second;
      }
    }


    bool GetInstance(Orthanc::DicomMap& dicom,
                     OrthancPlugins::MetadataMode mode,
                     const std::string& orthancId)
    {
      std::string seriesId, studyId, nope;
      
      return (ReadResource(dicom, seriesId, mode, orthancId, Orthanc::ResourceType_Instance) &&
              Lookup(dicom, studyId, mode, seriesId, Orthanc::ResourceType_Series) &&
              Lookup(dicom, nope /* patient id is unused */, mode, studyId, Orthanc::ResourceType_Study));
    }
  };
}



static void WriteInstanceMetadata(OrthancPlugins::DicomWebFormatter::HttpWriter& writer,
                                  OrthancPlugins::MetadataMode mode,
                                  MainDicomTagsCache& cache,
                                  const std::string& orthancId,
                                  const std::string& studyInstanceUid,
                                  const std::string& seriesInstanceUid,
                                  const std::string& sopInstanceUid,
                                  const std::string& wadoBase)
{
  assert(!orthancId.empty() &&
         !studyInstanceUid.empty() &&
         !seriesInstanceUid.empty() &&
         !sopInstanceUid.empty() &&
         !wadoBase.empty());

  const std::string bulkRoot = (wadoBase +
                                "studies/" + studyInstanceUid +
                                "/series/" + seriesInstanceUid + 
                                "/instances/" + sopInstanceUid + "/bulk");

  switch (mode)
  {
    case OrthancPlugins::MetadataMode_MainDicomTags:
    case OrthancPlugins::MetadataMode_Extrapolate:
    {
      Orthanc::DicomMap dicom;
      if (cache.GetInstance(dicom, mode, orthancId))
      {
        writer.AddOrthancMap(dicom);
      }

      break;
    }

    case OrthancPlugins::MetadataMode_Full:
    {
      // On a SSD drive, this version is twice slower than if using
      // cache (see below)
    
      OrthancPlugins::MemoryBuffer dicom;
      if (dicom.RestApiGet("/instances/" + orthancId + "/file", false))
      {
        writer.AddDicom(dicom.GetData(), dicom.GetSize(), bulkRoot);
      }

      break;
    }

    default:
      throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
  }
    
  
#if 0
  /**
   **/

  // TODO - Have a global setting to enable/disable caching of DICOMweb

  // TODO - Have a way to clear the "4444" attachments if Orthanc
  // version changes => Store Orthanc core version in a prefix or in
  // another attachment?
    
  OrthancPlugins::MemoryBuffer buffer;

  if (writer.IsXml())
  {
    // DICOMweb XML is not cached
    if (buffer.RestApiGet("/instances/" + orthancId + "/file", false))
    {
      writer.AddDicom(buffer.GetData(), buffer.GetSize(), bulkRoot);
    }
  }
  else
  {
    if (buffer.RestApiGet("/instances/" + orthancId + "/attachments/4444/data", false))
    {
      writer.AddDicomWebSerializedJson(buffer.GetData(), buffer.GetSize());
    }
    else if (buffer.RestApiGet("/instances/" + orthancId + "/file", false))
    {
      // "Ignore binary mode" in DICOMweb conversion if caching is
      // enabled, as the bulk root can change across executions

      std::string dicomweb;
      {
        // TODO - Avoid a global mutex => Need to change Orthanc SDK
        OrthancPlugins::DicomWebFormatter::Apply(
          dicomweb, OrthancPlugins::GetGlobalContext(), buffer.GetData(), buffer.GetSize(),
          false /* JSON */, OrthancPluginDicomWebBinaryMode_Ignore, "");
      }

      buffer.RestApiPut("/instances/" + orthancId + "/attachments/4444", dicomweb, false);
      writer.AddDicomWebSerializedJson(dicomweb.c_str(), dicomweb.size());
    }
  }
#endif
}



bool LocateStudy(OrthancPluginRestOutput* output,
                 std::string& orthancId,
                 std::string& studyInstanceUid,
                 const OrthancPluginHttpRequest* request)
{
  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();

  if (request->method != OrthancPluginHttpMethod_Get)
  {
    OrthancPluginSendMethodNotAllowed(context, output, "GET");
    return false;
  }

  studyInstanceUid = request->groups[0];

  try
  {
    OrthancPlugins::OrthancString tmp;
    tmp.Assign(OrthancPluginLookupStudy(context, studyInstanceUid.c_str()));

    if (tmp.GetContent() != NULL)
    {
      tmp.ToString(orthancId);
      return true;
    }
  }
  catch (Orthanc::OrthancException&)
  {
  }

  throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem, 
                                  "Accessing an inexistent study with WADO-RS: " + studyInstanceUid);
}


bool LocateSeries(OrthancPluginRestOutput* output,
                  std::string& orthancId,
                  std::string& studyInstanceUid,
                  std::string& seriesInstanceUid,
                  const OrthancPluginHttpRequest* request)
{
  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();

  if (request->method != OrthancPluginHttpMethod_Get)
  {
    OrthancPluginSendMethodNotAllowed(context, output, "GET");
    return false;
  }

  studyInstanceUid = request->groups[0];
  seriesInstanceUid = request->groups[1];

  bool found = false;

  try
  {
    OrthancPlugins::OrthancString tmp;
    tmp.Assign(OrthancPluginLookupSeries(context, seriesInstanceUid.c_str()));

    if (tmp.GetContent() != NULL)
    {
      tmp.ToString(orthancId);
      found = true;
    }
  }
  catch (Orthanc::OrthancException&)
  {
  }

  if (!found)
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem, 
                                    "Accessing an inexistent series with WADO-RS: " + seriesInstanceUid);
  }
  
  Json::Value study;
  if (!OrthancPlugins::RestApiGet(study, "/series/" + orthancId + "/study", false))
  {
    OrthancPluginSendHttpStatusCode(context, output, 404);
    return false;
  }
  else if (study[MAIN_DICOM_TAGS]["StudyInstanceUID"].asString() != studyInstanceUid)
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem, 
                                    "No series " + seriesInstanceUid + " in study " + studyInstanceUid);
  }
  else
  {
    return true;
  }
}


bool LocateInstance(OrthancPluginRestOutput* output,
                    std::string& orthancId,
                    std::string& studyInstanceUid,
                    std::string& seriesInstanceUid,
                    std::string& sopInstanceUid,
                    const OrthancPluginHttpRequest* request)
{
  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();

  if (request->method != OrthancPluginHttpMethod_Get)
  {
    OrthancPluginSendMethodNotAllowed(context, output, "GET");
    return false;
  }

  studyInstanceUid = request->groups[0];
  seriesInstanceUid = request->groups[1];
  sopInstanceUid = request->groups[2];
  
  {
    OrthancPlugins::OrthancString tmp;
    tmp.Assign(OrthancPluginLookupInstance(context, sopInstanceUid.c_str()));

    if (tmp.GetContent() == NULL)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem,
                                      "Accessing an inexistent instance with WADO-RS: " + sopInstanceUid);
    }

    tmp.ToString(orthancId);
  }
  
  Json::Value study, series;
  if (!OrthancPlugins::RestApiGet(series, "/instances/" + orthancId + "/series", false) ||
      !OrthancPlugins::RestApiGet(study, "/instances/" + orthancId + "/study", false))
  {
    OrthancPluginSendHttpStatusCode(context, output, 404);
    return false;
  }
  else if (study[MAIN_DICOM_TAGS]["StudyInstanceUID"].asString() != studyInstanceUid ||
           series[MAIN_DICOM_TAGS]["SeriesInstanceUID"].asString() != seriesInstanceUid)
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem,
                                    "Instance " + sopInstanceUid + 
                                    " is not both in study " + studyInstanceUid +
                                    " and in series " + seriesInstanceUid);
  }
  else
  {
    return true;
  }
}


void RetrieveDicomStudy(OrthancPluginRestOutput* output,
                        const char* url,
                        const OrthancPluginHttpRequest* request)
{
  bool transcode;
  Orthanc::DicomTransferSyntax targetSyntax;

  AcceptMultipartDicom(transcode, targetSyntax, request);
  
  std::string orthancId, studyInstanceUid;
  if (LocateStudy(output, orthancId, studyInstanceUid, request))
  {
    AnswerListOfDicomInstances(output, Orthanc::ResourceType_Study, orthancId, transcode, targetSyntax);
  }
}


void RetrieveDicomSeries(OrthancPluginRestOutput* output,
                         const char* url,
                         const OrthancPluginHttpRequest* request)
{
  bool transcode;
  Orthanc::DicomTransferSyntax targetSyntax;
  
  AcceptMultipartDicom(transcode, targetSyntax, request);
  
  std::string orthancId, studyInstanceUid, seriesInstanceUid;
  if (LocateSeries(output, orthancId, studyInstanceUid, seriesInstanceUid, request))
  {
    AnswerListOfDicomInstances(output, Orthanc::ResourceType_Series, orthancId, transcode, targetSyntax);
  }
}



void RetrieveDicomInstance(OrthancPluginRestOutput* output,
                           const char* url,
                           const OrthancPluginHttpRequest* request)
{
  bool transcode;
  Orthanc::DicomTransferSyntax targetSyntax;
  
  AcceptMultipartDicom(transcode, targetSyntax, request);
  
  std::string orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid;
  if (LocateInstance(output, orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid, request))
  {
    AnswerListOfDicomInstances(output, Orthanc::ResourceType_Instance, orthancId, transcode, targetSyntax);
  }
}



namespace
{
  class Identifier
  {
  private:
    std::string  orthancId_;
    std::string  dicomUid_;

  public:
    Identifier(const std::string& orthancId,
               const std::string& dicomUid) :
      orthancId_(orthancId),
      dicomUid_(dicomUid)
    {
    }

    const std::string& GetOrthancId() const
    {
      return orthancId_;
    }

    const std::string& GetDicomUid() const
    {
      return dicomUid_;
    }
  };
}


static void GetChildrenIdentifiers(std::list<Identifier>& target,
                                   Orthanc::ResourceType level,
                                   const std::string& orthancId)
{
  static const char* const ID = "ID";
  static const char* const SERIES_INSTANCE_UID = "SeriesInstanceUID";
  static const char* const SOP_INSTANCE_UID = "SOPInstanceUID";

  target.clear();

  const char* tag = NULL;
  std::string uri;

  switch (level)
  {
    case Orthanc::ResourceType_Study:
      uri = "/studies/" + orthancId + "/series";
      tag = SERIES_INSTANCE_UID;
      break;
       
    case Orthanc::ResourceType_Series:
      uri = "/series/" + orthancId + "/instances";
      tag = SOP_INSTANCE_UID;
      break;

    default:
      throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
  }

  assert(tag != NULL);
  
  Json::Value children;
  if (OrthancPlugins::RestApiGet(children, uri, false))
  {
    if (children.type() != Json::arrayValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
    }

    for (Json::Value::ArrayIndex i = 0; i < children.size(); i++)
    {
      if (children[i].type() != Json::objectValue ||
          !children[i].isMember(ID) ||
          !children[i].isMember(MAIN_DICOM_TAGS) ||
          children[i][ID].type() != Json::stringValue ||
          children[i][MAIN_DICOM_TAGS].type() != Json::objectValue ||
          !children[i][MAIN_DICOM_TAGS].isMember(tag) ||
          children[i][MAIN_DICOM_TAGS][tag].type() != Json::stringValue)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
      }
      else
      {
        target.push_back(Identifier(children[i][ID].asString(),
                                    children[i][MAIN_DICOM_TAGS][tag].asString()));
                                    
      }
    }
  }  
}



void RetrieveStudyMetadata(OrthancPluginRestOutput* output,
                           const char* url,
                           const OrthancPluginHttpRequest* request)
{
  bool isXml;
  if (!AcceptMetadata(request, isXml))
  {
    OrthancPluginSendHttpStatusCode(OrthancPlugins::GetGlobalContext(), output, 400 /* Bad request */);
  }
  else
  {
    const OrthancPlugins::MetadataMode mode =
      OrthancPlugins::Configuration::GetMetadataMode(Orthanc::ResourceType_Study);
    
    MainDicomTagsCache cache;

    std::string studyOrthancId, studyInstanceUid;
    if (LocateStudy(output, studyOrthancId, studyInstanceUid, request))
    {
      OrthancPlugins::DicomWebFormatter::HttpWriter writer(output, isXml);

      std::list<Identifier> series;
      GetChildrenIdentifiers(series, Orthanc::ResourceType_Study, studyOrthancId);

      for (std::list<Identifier>::const_iterator a = series.begin(); a != series.end(); ++a)
      {
        std::list<Identifier> instances;
        GetChildrenIdentifiers(instances, Orthanc::ResourceType_Series, a->GetOrthancId());

        for (std::list<Identifier>::const_iterator b = instances.begin(); b != instances.end(); ++b)
        {
          WriteInstanceMetadata(writer, mode, cache, b->GetOrthancId(), studyInstanceUid, a->GetDicomUid(),
                                b->GetDicomUid(), OrthancPlugins::Configuration::GetBaseUrl(request));
        }
      }

      writer.Send();
    }
  }
}


void RetrieveSeriesMetadata(OrthancPluginRestOutput* output,
                            const char* url,
                            const OrthancPluginHttpRequest* request)
{
  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();
  
  bool isXml;
  if (!AcceptMetadata(request, isXml))
  {
    OrthancPluginSendHttpStatusCode(context, output, 400 /* Bad request */);
  }
  else
  {
    const OrthancPlugins::MetadataMode mode =
      OrthancPlugins::Configuration::GetMetadataMode(Orthanc::ResourceType_Series);
    
    MainDicomTagsCache cache;

    std::string seriesOrthancId, studyInstanceUid, seriesInstanceUid;
    if (LocateSeries(output, seriesOrthancId, studyInstanceUid, seriesInstanceUid, request))
    {
      OrthancPlugins::DicomWebFormatter::HttpWriter writer(output, isXml);
      
      std::list<Identifier> instances;
      GetChildrenIdentifiers(instances, Orthanc::ResourceType_Series, seriesOrthancId);

      for (std::list<Identifier>::const_iterator a = instances.begin(); a != instances.end(); ++a)
      {
        WriteInstanceMetadata(writer, mode, cache, a->GetOrthancId(), studyInstanceUid, seriesInstanceUid,
                              a->GetDicomUid(), OrthancPlugins::Configuration::GetBaseUrl(request));
      }

      writer.Send();
    }
  }
}


void RetrieveInstanceMetadata(OrthancPluginRestOutput* output,
                              const char* url,
                              const OrthancPluginHttpRequest* request)
{
  bool isXml;
  if (!AcceptMetadata(request, isXml))
  {
    OrthancPluginSendHttpStatusCode(OrthancPlugins::GetGlobalContext(), output, 400 /* Bad request */);
  }
  else
  {
    MainDicomTagsCache cache;

    std::string orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid;
    if (LocateInstance(output, orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid, request))
    {
      OrthancPlugins::DicomWebFormatter::HttpWriter writer(output, isXml);
      WriteInstanceMetadata(writer, OrthancPlugins::MetadataMode_Full, cache, orthancId, studyInstanceUid,
                            seriesInstanceUid, sopInstanceUid, OrthancPlugins::Configuration::GetBaseUrl(request));
      writer.Send();      
    }
  }
}


void RetrieveBulkData(OrthancPluginRestOutput* output,
                      const char* url,
                      const OrthancPluginHttpRequest* request)
{
  OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();

  if (!AcceptBulkData(request))
  {
    OrthancPluginSendHttpStatusCode(context, output, 400 /* Bad request */);
    return;
  }

  std::string orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid;
  OrthancPlugins::MemoryBuffer content;
  if (LocateInstance(output, orthancId, studyInstanceUid, seriesInstanceUid, sopInstanceUid, request) &&
      content.RestApiGet("/instances/" + orthancId + "/file", false))
  {
    std::string bulk(request->groups[3]);

    std::vector<std::string> path;
    Orthanc::Toolbox::TokenizeString(path, bulk, '/');

    // Map the bulk data URI to the Orthanc "/instances/.../content/..." built-in URI
    std::string orthanc = "/instances/" + orthancId + "/content";

    Orthanc::DicomTag tmp(0, 0);
    
    if (path.size() == 1 &&
        Orthanc::DicomTag::ParseHexadecimal(tmp, path[0].c_str()) &&
        tmp == Orthanc::DICOM_TAG_PIXEL_DATA)
    {
      // Accessing pixel data: Return the raw content of the fragments in a multipart stream.
      // TODO - Is this how DICOMweb should work?
      orthanc += "/" + Orthanc::DICOM_TAG_PIXEL_DATA.Format();

      Json::Value frames;
      if (OrthancPlugins::RestApiGet(frames, orthanc, false))
      {
        if (frames.type() != Json::arrayValue ||
            OrthancPluginStartMultipartAnswer(context, output, "related", "application/octet-stream") != 0)
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_Plugin);
        }

        for (Json::Value::ArrayIndex i = 0; i < frames.size(); i++)
        {
          std::string frame;
          
          if (frames[i].type() != Json::stringValue ||
              !OrthancPlugins::RestApiGetString(frame, orthanc + "/" + frames[i].asString(), false) ||
              OrthancPluginSendMultipartItem(context, output, frame.c_str(), frame.size()) != 0)
          {
            throw Orthanc::OrthancException(Orthanc::ErrorCode_Plugin);
          }
        }
      }
      else
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem);
      }      
    }
    else
    {
      if (path.size() % 2 != 1)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                        "Bulk data URI in WADO-RS should have an odd number of items: " + bulk);
      }

      for (size_t i = 0; i < path.size() / 2; i++)
      {
        int index;

        try
        {
          index = boost::lexical_cast<int>(path[2 * i + 1]);
        }
        catch (boost::bad_lexical_cast&)
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_BadRequest,
                                          "Bad sequence index in bulk data URI: " + bulk);
        }

        orthanc += "/" + path[2 * i] + "/" + boost::lexical_cast<std::string>(index - 1);
      }

      orthanc += "/" + path.back();

      std::string result; 
      if (OrthancPlugins::RestApiGetString(result, orthanc, false))
      {
        if (OrthancPluginStartMultipartAnswer(context, output, "related", "application/octet-stream") != 0 ||
            OrthancPluginSendMultipartItem(context, output, result.c_str(), result.size()) != 0)
        {
          throw Orthanc::OrthancException(Orthanc::ErrorCode_Plugin);
        }
      }
      else
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem);
      }
    }
  }
}