123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347 |
- // Copyright (c) 2012-2020 fo-dicom contributors.
- // Licensed under the Microsoft Public License (MS-PL).
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Dicom;
- using Dicom.Log;
- using Dicom.Network;
- using QueryRetrieve_SCP.Model;
- using DicomClient = Dicom.Network.Client.DicomClient;
- namespace QueryRetrieve_SCP
- {
- public class QRService : DicomService, IDicomServiceProvider, IDicomCFindProvider, IDicomCEchoProvider, IDicomCMoveProvider, IDicomCGetProvider
- {
- private static readonly DicomTransferSyntax[] AcceptedTransferSyntaxes = new DicomTransferSyntax[]
- {
- DicomTransferSyntax.ExplicitVRLittleEndian,
- DicomTransferSyntax.ExplicitVRBigEndian,
- DicomTransferSyntax.ImplicitVRLittleEndian
- };
- private static readonly DicomTransferSyntax[] AcceptedImageTransferSyntaxes = new DicomTransferSyntax[]
- {
- // Lossless
- DicomTransferSyntax.JPEGLSLossless,
- DicomTransferSyntax.JPEG2000Lossless,
- DicomTransferSyntax.JPEGProcess14SV1,
- DicomTransferSyntax.JPEGProcess14,
- DicomTransferSyntax.RLELossless,
- // Lossy
- DicomTransferSyntax.JPEGLSNearLossless,
- DicomTransferSyntax.JPEG2000Lossy,
- DicomTransferSyntax.JPEGProcess1,
- DicomTransferSyntax.JPEGProcess2_4,
- // Uncompressed
- DicomTransferSyntax.ExplicitVRLittleEndian,
- DicomTransferSyntax.ExplicitVRBigEndian,
- DicomTransferSyntax.ImplicitVRLittleEndian
- };
- public string CallingAE { get; protected set; }
- public string CalledAE { get; protected set; }
- public IPAddress RemoteIP { get; private set; }
- public QRService(INetworkStream stream, Encoding fallbackEncoding, Logger log) : base(stream, fallbackEncoding, log)
- {
- var pi = stream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance);
- if (pi != null)
- {
- var endPoint = ((Socket)pi.GetValue(stream, null)).RemoteEndPoint as IPEndPoint;
- RemoteIP = endPoint.Address;
- }
- else
- {
- RemoteIP = new IPAddress(new byte[] { 127, 0, 0, 1 });
- }
- }
- public DicomCEchoResponse OnCEchoRequest(DicomCEchoRequest request)
- {
- Logger.Info($"Received verification request from AE {CallingAE} with IP: {RemoteIP}");
- return new DicomCEchoResponse(request, DicomStatus.Success);
- }
- public void OnConnectionClosed(Exception exception)
- {
- Clean();
- }
- public void OnReceiveAbort(DicomAbortSource source, DicomAbortReason reason)
- {
- //log the abort reason
- Logger.Error($"Received abort from {source}, reason is {reason}");
- }
- public Task OnReceiveAssociationReleaseRequestAsync()
- {
- Clean();
- return SendAssociationReleaseResponseAsync();
- }
- public Task OnReceiveAssociationRequestAsync(DicomAssociation association)
- {
- CallingAE = association.CallingAE;
- CalledAE = association.CalledAE;
- Logger.Info($"Received association request from AE: {CallingAE} with IP: {RemoteIP} ");
- if (QRServer.AETitle != CalledAE)
- {
- Logger.Error($"Association with {CallingAE} rejected since called aet {CalledAE} is unknown");
- return SendAssociationRejectAsync(DicomRejectResult.Permanent, DicomRejectSource.ServiceUser, DicomRejectReason.CalledAENotRecognized);
- }
- foreach (var pc in association.PresentationContexts)
- {
- if (pc.AbstractSyntax == DicomUID.Verification
- || pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelFIND
- || pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelMOVE
- || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelFIND
- || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelMOVE)
- {
- pc.AcceptTransferSyntaxes(AcceptedTransferSyntaxes);
- }
- else if (pc.AbstractSyntax == DicomUID.PatientRootQueryRetrieveInformationModelGET
- || pc.AbstractSyntax == DicomUID.StudyRootQueryRetrieveInformationModelGET)
- {
- pc.AcceptTransferSyntaxes(AcceptedImageTransferSyntaxes);
- }
- else if (pc.AbstractSyntax.StorageCategory != DicomStorageCategory.None)
- {
- pc.AcceptTransferSyntaxes(AcceptedImageTransferSyntaxes);
- }
- else
- {
- Logger.Warn($"Requested abstract syntax {pc.AbstractSyntax} from {CallingAE} not supported");
- pc.SetResult(DicomPresentationContextResult.RejectAbstractSyntaxNotSupported);
- }
- }
- Logger.Info($"Accepted association request from {CallingAE}");
- return SendAssociationAcceptAsync(association);
- }
- public IEnumerable<DicomCFindResponse> OnCFindRequest(DicomCFindRequest request)
- {
- var queryLevel = request.Level;
- var matchingFiles = new List<string>();
- IDicomImageFinderService finderService = QRServer.CreateFinderService;
- // a QR SCP has to define in a DICOM Conformance Statement for which dicom tags it can query
- // depending on the level of the query. Below there are only very few parameters evaluated.
- switch (queryLevel)
- {
- case DicomQueryRetrieveLevel.Patient:
- {
- var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
- var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
- matchingFiles = finderService.FindPatientFiles(patname, patid);
- }
- break;
- case DicomQueryRetrieveLevel.Study:
- {
- var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
- var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
- var accNr = request.Dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty);
- var studyUID = request.Dataset.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, string.Empty);
- matchingFiles = finderService.FindStudyFiles(patname, patid, accNr, studyUID);
- }
- break;
- case DicomQueryRetrieveLevel.Series:
- {
- var patname = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
- var patid = request.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty);
- var accNr = request.Dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty);
- var studyUID = request.Dataset.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, string.Empty);
- var seriesUID = request.Dataset.GetSingleValueOrDefault(DicomTag.SeriesInstanceUID, string.Empty);
- var modality = request.Dataset.GetSingleValueOrDefault(DicomTag.Modality, string.Empty);
- matchingFiles = finderService.FindSeriesFiles(patname, patid, accNr, studyUID, seriesUID, modality);
- }
- break;
- case DicomQueryRetrieveLevel.Image:
- yield return new DicomCFindResponse(request, DicomStatus.QueryRetrieveUnableToProcess);
- yield break;
- }
- // now read the required dicomtags from the matching files and return as results
- foreach (var matchingFile in matchingFiles)
- {
- var dicomFile = DicomFile.Open(matchingFile);
- var result = new DicomDataset();
- foreach (var requestedTag in request.Dataset)
- {
- // most of the requested DICOM tags are stored in the DICOM files and therefore saved into a database.
- // you can fill the responses by selecting the values from the database.
- // also be aware that there are some requested DicomTags like "ModalitiesInStudy" or "NumberOfStudyRelatedInstances"
- // or "NumberOfPatientRelatedInstances" and so on which have to be calculated and cannot be read from a DICOM file.
- if (dicomFile.Dataset.Contains(requestedTag.Tag))
- {
- dicomFile.Dataset.CopyTo(result, requestedTag.Tag);
- }
- // else if (requestedTag == DicomTag.NumberOfStudyRelatedInstances)
- // {
- // ... somehow calculate how many instances are stored within the study
- // result.Add(DicomTag.NumberOfStudyRelatedInstances, number);
- // } ....
- else
- {
- result.Add(requestedTag);
- }
- }
- yield return new DicomCFindResponse(request, DicomStatus.Pending) { Dataset = result };
- }
- yield return new DicomCFindResponse(request, DicomStatus.Success);
- }
- public void Clean()
- {
- // cleanup, like cancel outstanding move- or get-jobs
- }
- public IEnumerable<DicomCMoveResponse> OnCMoveRequest(DicomCMoveRequest request)
- {
- // the c-move request contains the DestinationAE. the data of this AE should be configured somewhere.
- if (request.DestinationAE != "STORESCP")
- {
- yield return new DicomCMoveResponse(request, DicomStatus.QueryRetrieveMoveDestinationUnknown);
- yield return new DicomCMoveResponse(request, DicomStatus.ProcessingFailure);
- yield break;
- }
- // this data should come from some data storage!
- var destinationPort = 11112;
- var destinationIP = "localhost";
- IDicomImageFinderService finderService = QRServer.CreateFinderService;
- IEnumerable<string> matchingFiles = Enumerable.Empty<string>();
- switch (request.Level)
- {
- case DicomQueryRetrieveLevel.Patient:
- matchingFiles = finderService.FindFilesByUID(request.Dataset.GetSingleValue<string>(DicomTag.PatientID), string.Empty, string.Empty);
- break;
- case DicomQueryRetrieveLevel.Study:
- matchingFiles = finderService.FindFilesByUID(string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID), string.Empty);
- break;
- case DicomQueryRetrieveLevel.Series:
- matchingFiles = finderService.FindFilesByUID(string.Empty, string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.SeriesInstanceUID));
- break;
- case DicomQueryRetrieveLevel.Image:
- yield return new DicomCMoveResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations);
- yield break;
- }
- var client = new DicomClient(destinationIP, destinationPort, false, QRServer.AETitle, request.DestinationAE);
- client.NegotiateAsyncOps();
- int storeTotal = matchingFiles.Count();
- int storeDone = 0; // this variable stores the number of instances that have already been sent
- int storeFailure = 0; // this variable stores the number of faulues returned in a OnResponseReceived
- foreach (string file in matchingFiles)
- {
- var storeRequest = new DicomCStoreRequest(file);
- // !!! there is a Bug in fo-dicom 3.0.2 that the OnResponseReceived handlers are invoked not until the DicomClient has already
- // sent all the instances. So the counters are not increased image by image sent but only once in a bulk after all storage
- // has been finished. This bug will be fixed hopefully soon.
- storeRequest.OnResponseReceived += (req, resp) =>
- {
- if (resp.Status == DicomStatus.Success)
- {
- Logger.Info("Storage of image successfull");
- storeDone++;
- }
- else
- {
- Logger.Error("Storage of image failed");
- storeFailure++;
- }
- };
- client.AddRequestAsync(storeRequest).Wait();
- }
- var sendTask = client.SendAsync();
- while (!sendTask.IsCompleted)
- {
- // 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.
- yield return new DicomCMoveResponse(request, DicomStatus.Pending) { Remaining = storeTotal - storeDone - storeFailure, Completed = storeDone };
- Thread.Sleep(TimeSpan.FromSeconds(2));
- }
- Logger.Info("..finished");
- yield return new DicomCMoveResponse(request, DicomStatus.Success);
- }
- public IEnumerable<DicomCGetResponse> OnCGetRequest(DicomCGetRequest request)
- {
- IDicomImageFinderService finderService = QRServer.CreateFinderService;
- IEnumerable<string> matchingFiles = Enumerable.Empty<string>();
- switch (request.Level)
- {
- case DicomQueryRetrieveLevel.Patient:
- matchingFiles = finderService.FindFilesByUID(request.Dataset.GetSingleValue<string>(DicomTag.PatientID), string.Empty, string.Empty);
- break;
- case DicomQueryRetrieveLevel.Study:
- matchingFiles = finderService.FindFilesByUID(string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID), string.Empty);
- break;
- case DicomQueryRetrieveLevel.Series:
- matchingFiles = finderService.FindFilesByUID(string.Empty, string.Empty, request.Dataset.GetSingleValue<string>(DicomTag.SeriesInstanceUID));
- break;
- case DicomQueryRetrieveLevel.Image:
- yield return new DicomCGetResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations);
- yield break;
- }
- foreach (var matchingFile in matchingFiles)
- {
- var storeRequest = new DicomCStoreRequest(matchingFile);
- SendRequestAsync(storeRequest).Wait();
- }
- yield return new DicomCGetResponse(request, DicomStatus.Success);
- }
- }
- }
|