QRService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Copyright (c) 2012-2020 fo-dicom contributors.
  2. // Licensed under the Microsoft Public License (MS-PL).
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Dicom;
  13. using Dicom.Log;
  14. using Dicom.Network;
  15. using QueryRetrieve_SCP.Model;
  16. using DicomClient = Dicom.Network.Client.DicomClient;
  17. namespace QueryRetrieve_SCP
  18. {
  19. public class QRService : DicomService, IDicomServiceProvider, IDicomCFindProvider, IDicomCEchoProvider, IDicomCMoveProvider, IDicomCGetProvider
  20. {
  21. private static readonly DicomTransferSyntax[] AcceptedTransferSyntaxes = new DicomTransferSyntax[]
  22. {
  23. DicomTransferSyntax.ExplicitVRLittleEndian,
  24. DicomTransferSyntax.ExplicitVRBigEndian,
  25. DicomTransferSyntax.ImplicitVRLittleEndian
  26. };
  27. private static readonly DicomTransferSyntax[] AcceptedImageTransferSyntaxes = new DicomTransferSyntax[]
  28. {
  29. // Lossless
  30. DicomTransferSyntax.JPEGLSLossless,
  31. DicomTransferSyntax.JPEG2000Lossless,
  32. DicomTransferSyntax.JPEGProcess14SV1,
  33. DicomTransferSyntax.JPEGProcess14,
  34. DicomTransferSyntax.RLELossless,
  35. // Lossy
  36. DicomTransferSyntax.JPEGLSNearLossless,
  37. DicomTransferSyntax.JPEG2000Lossy,
  38. DicomTransferSyntax.JPEGProcess1,
  39. DicomTransferSyntax.JPEGProcess2_4,
  40. // Uncompressed
  41. DicomTransferSyntax.ExplicitVRLittleEndian,
  42. DicomTransferSyntax.ExplicitVRBigEndian,
  43. DicomTransferSyntax.ImplicitVRLittleEndian
  44. };
  45. public string CallingAE { get; protected set; }
  46. public string CalledAE { get; protected set; }
  47. public IPAddress RemoteIP { get; private set; }
  48. public QRService(INetworkStream stream, Encoding fallbackEncoding, Logger log) : base(stream, fallbackEncoding, log)
  49. {
  50. var pi = stream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance);
  51. if (pi != null)
  52. {
  53. var endPoint = ((Socket)pi.GetValue(stream, null)).RemoteEndPoint as IPEndPoint;
  54. RemoteIP = endPoint.Address;
  55. }
  56. else
  57. {
  58. RemoteIP = new IPAddress(new byte[] { 127, 0, 0, 1 });
  59. }
  60. }
  61. public DicomCEchoResponse OnCEchoRequest(DicomCEchoRequest request)
  62. {
  63. Logger.Info($"Received verification request from AE {CallingAE} with IP: {RemoteIP}");
  64. return new DicomCEchoResponse(request, DicomStatus.Success);
  65. }
  66. public void OnConnectionClosed(Exception exception)
  67. {
  68. Clean();
  69. }
  70. public void OnReceiveAbort(DicomAbortSource source, DicomAbortReason reason)
  71. {
  72. //log the abort reason
  73. Logger.Error($"Received abort from {source}, reason is {reason}");
  74. }
  75. public Task OnReceiveAssociationReleaseRequestAsync()
  76. {
  77. Clean();
  78. return SendAssociationReleaseResponseAsync();
  79. }
  80. public Task OnReceiveAssociationRequestAsync(DicomAssociation association)
  81. {
  82. CallingAE = association.CallingAE;
  83. CalledAE = association.CalledAE;
  84. Logger.Info($"Received association request from AE: {CallingAE} with IP: {RemoteIP} ");
  85. if (QRServer.AETitle != CalledAE)
  86. {
  87. Logger.Error($"Association with {CallingAE} rejected since called aet {CalledAE} is unknown");
  88. return SendAssociationRejectAsync(DicomRejectResult.Permanent, DicomRejectSource.ServiceUser, DicomRejectReason.CalledAENotRecognized);
  89. }
  90. foreach (var pc in association.PresentationContexts)
  91. {
  92. if (pc.AbstractSyntax == DicomUID.Verification
  93. || pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelFIND
  94. || pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelMOVE
  95. || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelFIND
  96. || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelMOVE)
  97. {
  98. pc.AcceptTransferSyntaxes(AcceptedTransferSyntaxes);
  99. }
  100. else if (pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelGET
  101. || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelGET)
  102. {
  103. pc.AcceptTransferSyntaxes(AcceptedImageTransferSyntaxes);
  104. }
  105. else if (pc.AbstractSyntax.StorageCategory != DicomStorageCategory.None)
  106. {
  107. pc.AcceptTransferSyntaxes(AcceptedImageTransferSyntaxes);
  108. }
  109. else
  110. {
  111. Logger.Warn($"Requested abstract syntax {pc.AbstractSyntax} from {CallingAE} not supported");
  112. pc.SetResult(DicomPresentationContextResult.RejectAbstractSyntaxNotSupported);
  113. }
  114. }
  115. Logger.Info($"Accepted association request from {CallingAE}");
  116. return SendAssociationAcceptAsync(association);
  117. }
  118. public IEnumerable<DicomCFindResponse> OnCFindRequest(DicomCFindRequest request)
  119. {
  120. var queryLevel = request.Level;
  121. var matchingFiles = new List<string>();
  122. IDicomImageFinderService finderService = QRServer.CreateFinderService;
  123. // a QR SCP has to define in a DICOM Conformance Statement for which dicom tags it can query
  124. // depending on the level of the query. Below there are only very few parameters evaluated.
  125. switch (queryLevel)
  126. {
  127. case DicomQueryRetrieveLevel.Patient:
  128. {
  129. var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
  130. var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
  131. matchingFiles = finderService.FindPatientFiles(patname, patid);
  132. }
  133. break;
  134. case DicomQueryRetrieveLevel.Study:
  135. {
  136. var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
  137. var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
  138. var accNr = request.Dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty);
  139. var studyUID = request.Dataset.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, string.Empty);
  140. matchingFiles = finderService.FindStudyFiles(patname, patid, accNr, studyUID);
  141. }
  142. break;
  143. case DicomQueryRetrieveLevel.Series:
  144. {
  145. var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
  146. var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
  147. var accNr = request.Dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty);
  148. var studyUID = request.Dataset.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, string.Empty);
  149. var seriesUID = request.Dataset.GetSingleValueOrDefault(DicomTag.SeriesInstanceUID, string.Empty);
  150. var modality = request.Dataset.GetSingleValueOrDefault(DicomTag.Modality, string.Empty);
  151. matchingFiles = finderService.FindSeriesFiles(patname, patid, accNr, studyUID, seriesUID, modality);
  152. }
  153. break;
  154. case DicomQueryRetrieveLevel.Image:
  155. yield return new DicomCFindResponse(request, DicomStatus.QueryRetrieveUnableToProcess);
  156. yield break;
  157. }
  158. // now read the required dicomtags from the matching files and return as results
  159. foreach (var matchingFile in matchingFiles)
  160. {
  161. var dicomFile = DicomFile.Open(matchingFile);
  162. var result = new DicomDataset();
  163. foreach (var requestedTag in request.Dataset)
  164. {
  165. // most of the requested DICOM tags are stored in the DICOM files and therefore saved into a database.
  166. // you can fill the responses by selecting the values from the database.
  167. // also be aware that there are some requested DicomTags like "ModalitiesInStudy" or "NumberOfStudyRelatedInstances"
  168. // or "NumberOfPatientRelatedInstances" and so on which have to be calculated and cannot be read from a DICOM file.
  169. if (dicomFile.Dataset.Contains(requestedTag.Tag))
  170. {
  171. dicomFile.Dataset.CopyTo(result, requestedTag.Tag);
  172. }
  173. // else if (requestedTag == DicomTag.NumberOfStudyRelatedInstances)
  174. // {
  175. // ... somehow calculate how many instances are stored within the study
  176. // result.Add(DicomTag.NumberOfStudyRelatedInstances, number);
  177. // } ....
  178. else
  179. {
  180. result.Add(requestedTag);
  181. }
  182. }
  183. yield return new DicomCFindResponse(request, DicomStatus.Pending) { Dataset = result };
  184. }
  185. yield return new DicomCFindResponse(request, DicomStatus.Success);
  186. }
  187. public void Clean()
  188. {
  189. // cleanup, like cancel outstanding move- or get-jobs
  190. }
  191. public IEnumerable<DicomCMoveResponse> OnCMoveRequest(DicomCMoveRequest request)
  192. {
  193. // the c-move request contains the DestinationAE. the data of this AE should be configured somewhere.
  194. if (request.DestinationAE != "STORESCP")
  195. {
  196. yield return new DicomCMoveResponse(request, DicomStatus.QueryRetrieveMoveDestinationUnknown);
  197. yield return new DicomCMoveResponse(request, DicomStatus.ProcessingFailure);
  198. yield break;
  199. }
  200. // this data should come from some data storage!
  201. var destinationPort = 11112;
  202. var destinationIP = "localhost";
  203. IDicomImageFinderService finderService = QRServer.CreateFinderService;
  204. IEnumerable<string> matchingFiles = Enumerable.Empty<string>();
  205. switch (request.Level)
  206. {
  207. case DicomQueryRetrieveLevel.Patient:
  208. matchingFiles = finderService.FindFilesByUID(request.Dataset.GetSingleValue<string>(DicomTag.PatientID), string.Empty, string.Empty);
  209. break;
  210. case DicomQueryRetrieveLevel.Study:
  211. matchingFiles = finderService.FindFilesByUID(string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID), string.Empty);
  212. break;
  213. case DicomQueryRetrieveLevel.Series:
  214. matchingFiles = finderService.FindFilesByUID(string.Empty, string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.SeriesInstanceUID));
  215. break;
  216. case DicomQueryRetrieveLevel.Image:
  217. yield return new DicomCMoveResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations);
  218. yield break;
  219. }
  220. var client = new DicomClient(destinationIP, destinationPort, false, QRServer.AETitle, request.DestinationAE);
  221. client.NegotiateAsyncOps();
  222. int storeTotal = matchingFiles.Count();
  223. int storeDone = 0; // this variable stores the number of instances that have already been sent
  224. int storeFailure = 0; // this variable stores the number of faulues returned in a OnResponseReceived
  225. foreach (string file in matchingFiles)
  226. {
  227. var storeRequest = new DicomCStoreRequest(file);
  228. // !!! there is a Bug in fo-dicom 3.0.2 that the OnResponseReceived handlers are invoked not until the DicomClient has already
  229. // sent all the instances. So the counters are not increased image by image sent but only once in a bulk after all storage
  230. // has been finished. This bug will be fixed hopefully soon.
  231. storeRequest.OnResponseReceived += (req, resp) =>
  232. {
  233. if (resp.Status == DicomStatus.Success)
  234. {
  235. Logger.Info("Storage of image successfull");
  236. storeDone++;
  237. }
  238. else
  239. {
  240. Logger.Error("Storage of image failed");
  241. storeFailure++;
  242. }
  243. };
  244. client.AddRequestAsync(storeRequest).Wait();
  245. }
  246. var sendTask = client.SendAsync();
  247. while (!sendTask.IsCompleted)
  248. {
  249. // while the send-task is runnin we inform the QR SCU every 2 seconds about the status and how many instances are remaining to send.
  250. yield return new DicomCMoveResponse(request, DicomStatus.Pending) { Remaining = storeTotal - storeDone - storeFailure, Completed = storeDone };
  251. Thread.Sleep(TimeSpan.FromSeconds(2));
  252. }
  253. Logger.Info("..finished");
  254. yield return new DicomCMoveResponse(request, DicomStatus.Success);
  255. }
  256. public IEnumerable<DicomCGetResponse> OnCGetRequest(DicomCGetRequest request)
  257. {
  258. IDicomImageFinderService finderService = QRServer.CreateFinderService;
  259. IEnumerable<string> matchingFiles = Enumerable.Empty<string>();
  260. switch (request.Level)
  261. {
  262. case DicomQueryRetrieveLevel.Patient:
  263. matchingFiles = finderService.FindFilesByUID(request.Dataset.GetSingleValue<string>(DicomTag.PatientID), string.Empty, string.Empty);
  264. break;
  265. case DicomQueryRetrieveLevel.Study:
  266. matchingFiles = finderService.FindFilesByUID(string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID), string.Empty);
  267. break;
  268. case DicomQueryRetrieveLevel.Series:
  269. matchingFiles = finderService.FindFilesByUID(string.Empty, string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.SeriesInstanceUID));
  270. break;
  271. case DicomQueryRetrieveLevel.Image:
  272. yield return new DicomCGetResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations);
  273. yield break;
  274. }
  275. foreach (var matchingFile in matchingFiles)
  276. {
  277. var storeRequest = new DicomCStoreRequest(matchingFile);
  278. SendRequestAsync(storeRequest).Wait();
  279. }
  280. yield return new DicomCGetResponse(request, DicomStatus.Success);
  281. }
  282. }
  283. }