Merge branch 'cornerstone-tools-next' of https://github.com/OHIF/Viewers into cornerstone-tools-next

This commit is contained in:
James Petts 2018-11-12 11:11:51 +00:00
commit edfbad10af
159 changed files with 2250 additions and 11240 deletions

View File

@ -1 +0,0 @@
local

View File

@ -41,7 +41,6 @@ ohif:cornerstone-settings
ohif:viewerbase
ohif:studies
ohif:study-list
ohif:dicom-services
ohif:hanging-protocols
ohif:metadata

View File

@ -92,8 +92,6 @@ ohif:core@0.0.1
ohif:cornerstone@0.0.1
ohif:cornerstone-settings@0.0.1
ohif:design@0.0.1
ohif:dicom-services@0.0.1
ohif:dicomweb-client@0.0.1
ohif:hanging-protocols@0.0.1
ohif:header@0.0.1
ohif:hotkeys@0.0.1
@ -143,7 +141,6 @@ tracker@1.2.0
ui@1.0.13
underscore@1.0.10
url@1.2.0
validatejs@0.0.1
webapp@1.6.2
webapp-hashing@1.0.9
zuuk:stale-session@1.0.8

View File

@ -14,6 +14,9 @@
{{/if}}
{{/section}}
{{#section 'headerMenu'}}
<span class="research-use pull-left m-r-1">
INVESTIGATIONAL USE ONLY
</span>
<span class="user-name pull-left m-r-1">{{userName}}</span>
<div class="menu-toggle pull-right">
<i class="fa fa-cog"></i>

View File

@ -32,7 +32,7 @@ Template.viewerSection.events({
window.ResizeViewportManager.handleResize();
},
'ohif.lesiontracker.timepoint.changeViewType .timepoint-browser-list'(event, instance, viewType) {
'ohif.measurements.timepoint.changeViewType .timepoint-browser-list'(event, instance, viewType) {
const $browserList = $(event.currentTarget);
const $allBrowserItems = $browserList.find('.timepoint-browser-item');
@ -43,7 +43,7 @@ Template.viewerSection.events({
const { timepointIds, currentTimepointId } = OHIF.viewer.data;
timepointIds.forEach(timepointId => {
const $browserItem = $allBrowserItems.filter(`[data-id=${timepointId}]`);
$browserItem.find('.timepoint-item').trigger('ohif.lesiontracker.timepoint.load');
$browserItem.find('.timepoint-item').trigger('ohif.measurements.timepoint.load');
});
// Show only current timepoint expanded on key timepoints tab

View File

@ -3,10 +3,26 @@ import { Router } from 'meteor/clinical:router';
import { OHIF } from 'meteor/ohif:core';
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'layout'
loadingTemplate: 'loading'
});
// If we are running a disconnected client similar to the StandaloneViewer
// (see https://docs.ohif.org/standalone-viewer/usage.html) we don't want
// our routes to get stuck while waiting for Pub / Sub.
//
// In this case, the developer is required to add Servers and specify
// a CurrentServer with some other approach (e.g. a separate script).
if (Meteor.settings &&
Meteor.settings.public &&
Meteor.settings.public.clientOnly !== true) {
Router.waitOn(function() {
return [
Meteor.subscribe('servers'),
Meteor.subscribe('currentServer')
];
});
}
Router.onBeforeAction('loading');
Router.onBeforeAction(function() {

File diff suppressed because it is too large Load Diff

View File

@ -9,20 +9,20 @@
"version": "1.0.0",
"description": "",
"dependencies": {
"@babel/runtime": "^7.0.0-beta.54",
"bcrypt": "^0.8.7",
"@babel/runtime": "7.0.0-beta.51",
"bcrypt": "^3.0.1",
"loglevel": "^1.6.1",
"url": "^0.11.0"
},
"devDependencies": {
"babel-eslint": "^6.1.2",
"eslint": "^3.7.0",
"eslint-config-airbnb": "^12.0.0",
"eslint-import-resolver-meteor": "^0.3.3",
"eslint-plugin-import": "^1.16.0",
"eslint-plugin-jsx-a11y": "^2.2.2",
"eslint-plugin-meteor": "^4.0.0",
"eslint-plugin-react": "^6.3.0"
"babel-eslint": "^10.0.1",
"eslint": "^5.6.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-import-resolver-meteor": "^0.4.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-meteor": "^5.1.0",
"eslint-plugin-react": "^7.11.1"
},
"main": "index.js",
"repository": {

View File

@ -1 +0,0 @@
starrynight run-tests --framework gagarin --debug --verbose --webdriver http://localhost:9515 --path ../Packages/*/tests/gagarin/**/*.js

View File

@ -1 +0,0 @@
starrynight run-tests --framework nightwatch

View File

@ -1 +0,0 @@
reports

View File

@ -1,4 +0,0 @@
exports.assertion = function() {
return this; // allows the command to be chained.
};

View File

@ -1,4 +0,0 @@
exports.command = function() {
return this;
};

View File

@ -1,15 +0,0 @@
exports.command = function(username, password) {
this
.waitForElementVisible('#entrySignIn', 1000)
.verify.elementPresent("#signInPageTitle")
.verify.elementPresent("#signInPageMessage")
.verify.elementPresent("#signInPageEmailInput")
.verify.elementPresent("#signInPagePasswordInput")
.verify.elementPresent("#signInToAppButton")
.verify.elementPresent("#needAnAccountButton")
.verify.containsText("#signInPageTitle", "Sign In")
.verify.containsText("#signInPageMessage", "Improve your clincal practice with checklists.")
return this; // allows the command to be chained.
};

View File

@ -1,11 +0,0 @@
exports.command = function(username, password) {
this
.waitForElementVisible('#entrySignUp', 1000)
.verify.elementPresent("#signUpPageEmailInput")
.verify.elementPresent("#signUpPagePasswordInput")
.verify.elementPresent("#signUpPagePasswordConfirmInput")
.verify.elementPresent("#signUpPageJoinNowButton")
return this; // allows the command to be chained.
};

View File

@ -1,14 +0,0 @@
exports.command = function(username, password) {
this
.waitForElementVisible('#entrySignIn', 1000)
.verify.elementPresent("#signInPageEmailInput")
.verify.elementPresent("#signInPagePasswordInput")
.setValue("#signInPageEmailInput", username)
.setValue("#signInPagePasswordInput", password)
.click("#signInToAppButton").pause(1000)
return this; // allows the command to be chained.
};

View File

@ -1,8 +0,0 @@
exports.command = function(email, password) {
this
.verify.elementPresent("#logoutButton")
.click("#logoutButton").pause(500)
return this; // allows the command to be chained.
};

View File

@ -1,23 +0,0 @@
exports.command = function(email, password) {
this
.waitForElementVisible('#entrySignUp', 1000)
.verify.elementPresent("#signUpPageEmailInput")
.verify.elementPresent("#signUpPagePasswordInput")
.verify.elementPresent("#signUpPagePasswordConfirmInput")
.clearValue("#signUpPageEmailInput")
.clearValue("#signUpPagePasswordInput")
.clearValue("#signUpPagePasswordConfirmInput")
// .setValue("#signUpPageUsernameInput", "Jane Doe")
.setValue("#signUpPageEmailInput", email)
.setValue("#signUpPagePasswordInput", password)
.setValue("#signUpPagePasswordConfirmInput", password)
.click("#signUpPageJoinNowButton").pause(200)
return this; // allows the command to be chained.
};

View File

@ -1,21 +0,0 @@
// async version calls method on the server
exports.command = function(methodName, timeout) {
var client = this;
if (!timeout) {
timeout = 5000;
}
this
.timeoutsAsyncScript(timeout)
.executeAsync(function(data, meteorCallback){
//return HipaaLogger.logEventObject(data);
Meteor.call(methodName, data, function(meteorError, meteorResult){
var response = (meteorError ? { error: meteorError } : { result: meteorResult });
meteorCallback(response);
})
}, [hipaaEvent], function(result){
console.log("result.value", result.value);
client.assert.ok(result.value);
}).pause(1000)
return this;
};

View File

@ -1,40 +0,0 @@
/*exports.command = function(sessionName, expectedValue, timeout, callback) {
var self = this;
if (!timeout) {
timeout = 5000;
}
var glassOpacity = false;
this
.timeoutsAsyncScript(timeout)
.executeAsync(function (data, callback) {
return Session.get('glassOpacity');
}, [''], function (response) { // you need to pass an ARRAY of ONE argument, must be a bug
if (response.value.error) {
throw 'Meteor apply (call) returned an error: ' + response.value.error;
} else if (typeof callback === 'function') {
callback.call(self);
}
})
return this;
};*/
// syncrhonous version; only works for checking javascript objects on client
exports.command = function(sessionVarName, expectedValue) {
var client = this;
this
.execute(function(data){
return Session.get(data);
}, [sessionVarName], function(result){
client.assert.ok(result.value);
if(expectedValue){
client.assert.equal(result.value, expectedValue);
}
}).pause(1000)
return this;
};

View File

@ -1,10 +0,0 @@
exports.command = function(username, password) {
this
.verify.elementPresent("#appBody")
.verify.elementPresent("#navbarHeader")
.verify.elementPresent("#contentContainer")
.verify.elementPresent("#contentContainer .content-scrollable")
.verify.elementPresent("#navbarFooter")
return this; // allows the command to be chained.
};

View File

@ -1,22 +0,0 @@
// async version calls method on the server
exports.command = function(methodName, timeout) {
/*var client = this;
if (!timeout) {
timeout = 5000;
}
this
.timeoutsAsyncScript(timeout)
.executeAsync(function(data, meteorCallback){
//return HipaaLogger.logEventObject(data);
Meteor.call(methodName, data, function(meteorError, meteorResult){
var response = (meteorError ? { error: meteorError } : { result: meteorResult });
meteorCallback(response);
})
}, [hipaaEvent], function(result){
console.log("result.value", result.value);
client.assert.ok(result.value);
}).pause(1000)
return this;*/
return this;
};

View File

@ -1,9 +0,0 @@
exports.command = function(input, callback) {
this
.frame(null)
.waitForElementVisible("body", 1000, "=============================================================")
.verify.elementPresent("body", "== " + input)
return this; // allows the command to be chained.
};

View File

@ -1,7 +0,0 @@
exports.command = function(pageId) {
this
.waitForElementVisible(pageId, 3000)
return this; // allows the command to be chained.
};

View File

@ -1,8 +0,0 @@
{
"default" : {
"myGlobal" : 1
},
"test_env" : {
"myGlobal" : 2
}
}

View File

@ -1 +0,0 @@
hh:mm:ss.sss INFO - Initializing debug log

View File

@ -1,34 +0,0 @@
//var Utils = require('lib/util/utils.js');
module.exports = {
testTrue: function(client){
client.assert.equal(true, true);
}
/*testFormatElapsedTime : function(client) {
var test = client.assert;
var resultMs = Utils.formatElapsedTime(999);
var resultSec = Utils.formatElapsedTime(1999);
var resultMin = Utils.formatElapsedTime(122299, true);
test.equal(resultMs, '999ms');
test.equal(resultSec, '1.999s');
test.equal(resultMin, '2m 2s / 122299ms');
},
testMakeFnAsync : function(client) {
function asynFn(done) {
done();
}
function syncFn() {}
var test = client.assert;
test.equal(Utils.makeFnAsync(1, asynFn), asynFn);
var convertedFn = Utils.makeFnAsync(1, syncFn);
convertedFn(function() {
test.ok('converted fn called');
});
}*/
};

View File

@ -1,14 +0,0 @@
// add tests to this file using the Nightwatch.js API
// http://nightwatchjs.org/api
module.exports = {
"Layout & Static Pages" : function (client) {
client
.url("http://localhost:3000")
.resizeWindow(1024, 768)
.verify.elementPresent("body")
.end();
}
};

View File

@ -37,8 +37,6 @@ ohif:cornerstone
ohif:cornerstone-settings
ohif:viewerbase
ohif:study-list
ohif:dicom-services
ohif:dicomweb-client
ohif:hanging-protocols
ohif:metadata
ohif:user-oidc

View File

@ -82,8 +82,6 @@ ohif:core@0.0.1
ohif:cornerstone@0.0.1
ohif:cornerstone-settings@0.0.1
ohif:design@0.0.1
ohif:dicom-services@0.0.1
ohif:dicomweb-client@0.0.1
ohif:hanging-protocols@0.0.1
ohif:header@0.0.1
ohif:hotkeys@0.0.1
@ -129,6 +127,5 @@ tracker@1.2.0
ui@1.0.13
underscore@1.0.10
url@1.2.0
validatejs@0.0.1
webapp@1.6.2
webapp-hashing@1.0.9

2
OHIFViewer/bin/orthancDIMSE.sh Executable file
View File

@ -0,0 +1,2 @@
echo "Starting Meteor server..."
METEOR_PACKAGE_DIRS="../Packages" meteor --settings ../config/orthancDIMSE.json

View File

@ -0,0 +1,3 @@
<body>
<div id="notificationArea" class="notification-area"></div>
</body>

View File

@ -0,0 +1,2 @@
body
background-color: black

View File

@ -22,10 +22,10 @@ Meteor.startup(function() {
cornerstoneWADOImageLoader.configure({
beforeSend: function(xhr) {
const accessToken = OHIF.user.getAccessToken();
const headers = OHIF.DICOMWeb.getAuthorizationHeader();
if (accessToken) {
xhr.setRequestHeader("Authorization", `Bearer ${accessToken}`);
if (headers.Authorization) {
xhr.setRequestHeader("Authorization", headers.Authorization);
}
}
});

View File

@ -1,8 +1,7 @@
active-entry
hipaa-audit-log
meteor-stale-session
validatejs
orthanc-remote
ohif-cornerstone
ohif-viewerbase/client/compatibility
ohif-core/client/lib/third-party/
ohif-core/client/lib/third-party/

View File

@ -5,7 +5,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
// Meteor packages
api.use([

View File

@ -5,7 +5,7 @@
* @param [defaultValue] - The value to return if the element is not present
* @returns {*}
*/
const getAttribute = function(element, defaultValue) {
export default function getAttribute(element, defaultValue) {
if (!element) {
return defaultValue;
}
@ -42,5 +42,3 @@ function convertToInt(input) {
return parseInt(output, 16);
}
export default getAttribute;

View File

@ -0,0 +1,26 @@
import { OHIF } from 'meteor/ohif:core';
import { btoa } from 'isomorphic-base64';
/**
* Returns the Authorization header as part of an Object.
*
* @returns {Object}
*/
export default function getAuthorizationHeader() {
const headers = {};
// Check for OHIF.user since this can also be run on the server
const accessToken = OHIF.user && OHIF.user.getAccessToken && OHIF.user.getAccessToken();
const server = OHIF.servers.getCurrentServer();
if (server &&
server.requestOptions &&
server.requestOptions.auth) {
// HTTP Basic Auth (user:password)
headers.Authorization = `Basic ${btoa(server.requestOptions.auth)}`;
} else if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
return headers;
}

View File

@ -1,4 +1,4 @@
const getModalities = function(modality, modalitiesInStudy) {
export default function getModalities(modality, modalitiesInStudy) {
var modalities = {};
if (modality) {
modalities = modality;
@ -19,5 +19,3 @@ const getModalities = function(modality, modalitiesInStudy) {
}
return modalities;
};
export default getModalities;

View File

@ -1,25 +1,19 @@
import get from './get.js';
import { OHIF } from 'meteor/ohif:core';
import getAttribute from './getAttribute.js';
import getBulkData from './getBulkData.js';
import getJSON from './getJSON.js';
import getAuthorizationHeader from './getAuthorizationHeader.js';
import getModalities from './getModalities.js';
import getName from './getName.js';
import getNumber from './getNumber.js';
import getString from './getString.js';
import getAccessToken from './getAccessToken.js';
import makeRequest from './makeRequest.js';
const DICOMWeb = {
get,
getAttribute,
getBulkData,
getJSON,
getAuthorizationHeader,
getModalities,
getName,
getNumber,
getString,
getAccessToken,
makeRequest
};
export { DICOMWeb };
OHIF.DICOMWeb = DICOMWeb;

View File

@ -1 +1,2 @@
import './object.js';
import './DICOMWeb/';

View File

@ -16,4 +16,4 @@ OHIF.utils.absoluteUrl = function(path) {
}
return absolutePath.replace(/\/\/+/g, '/');
};
};

View File

@ -53,7 +53,9 @@ OHIF.mixins.select2 = new OHIF.Mixin({
}
// Check if there is already an empty option on items list
if (!_.findWhere(items, { value: '' })) {
// Note: If this is a multi-select input. Do not add a placeholder
const isMultiple = instance.data.options && instance.data.options.multiple;
if (!_.findWhere(items, { value: '' }) && isMultiple === false) {
// Clone the current items
const newItems = _.clone(items) || [];
newItems.unshift({

View File

@ -36,3 +36,4 @@ import './input/text.html';
import './notification';
import './popover/form.html';
import './popover/popoverSimple.html';

View File

@ -0,0 +1,4 @@
<template name="popoverSimple">
{{#if this.message}}{{this.message}}{{/if}}
{{>UI.contentBlock}}
</template>

View File

@ -8,13 +8,22 @@
<span>rows per page</span>
</div>
</div>
<div class="col-xs-8 col-sm-9 col-md-9">
<div class="form-inline form-group page-number">
<label>
<ul class="pagination-control no-margins"></ul>
</label>
{{#if paginationButtonsEnabled}}
<div class="col-xs-8 col-sm-9 col-md-9">
<div class="form-inline form-group page-buttons noselect">
<label>
<ul class="pagination-control no-margins">
<li class="page-item prev disabled">
<a href="#" class="page-link">Previous</a>
</li>
<li class="page-item next disabled">
<a href="#" class="page-link">Next</a>
</li>
</ul>
</label>
</div>
</div>
</div>
{{/if}}
</div>
{{/form}}
</template>

View File

@ -1,8 +1,6 @@
import { Template } from 'meteor/templating';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import 'twbs-pagination';
const visiblePages = 10;
import { $ } from 'meteor/jquery';
Template.paginationArea.onCreated(function() {
const instance = Template.instance();
@ -19,60 +17,66 @@ Template.paginationArea.onCreated(function() {
Template.paginationArea.onRendered(() => {
const instance = Template.instance();
instance.$paginationControl = instance.$('.pagination-control');
// Track changes on recordCount and rowsPerPage
instance.autorun(() => {
const recordCount = instance.data.recordCount.get();
const rowsPerPage = instance.data.rowsPerPage.get();
const currentPage = instance.data.currentPage.get();
// Destroy plugin if exists
if (instance.$paginationControl.data().twbsPagination) {
instance.$paginationControl.twbsPagination('destroy');
}
Meteor.defer(() => {
const prevButton = instance.$('.prev')[0];
const nextButton = instance.$('.next')[0];
if (!prevButton || !nextButton) {
return;
}
if (recordCount && rowsPerPage) {
const totalPages = Math.ceil(recordCount / rowsPerPage);
// Enable if there are potentially more records, otherwise disable it
if (recordCount >= rowsPerPage) {
nextButton.classList.remove('disabled');
} else {
nextButton.classList.add('disabled');
}
// Initialize plugin
instance.$paginationControl.twbsPagination({
totalPages,
visiblePages,
onPageClick: (event, page) => {
// Update currentPage
// Decrease page by 1 to set currentPage
// Since reactive table current page index starts by 0
instance.data.currentPage.set(page - 1);
}
});
}
// Enable the previous button if it is not the first page, otherwise disable it
if (currentPage > 0) {
prevButton.classList.remove('disabled');
} else {
prevButton.classList.add('disabled');
}
});
});
});
Template.paginationArea.onDestroyed(() => {
const instance = Template.instance();
if (instance.$paginationControl.data().twbsPagination) {
instance.$paginationControl.twbsPagination('destroy');
}
});
Template.paginationArea.helpers({
recordCount() {
paginationButtonsEnabled() {
const instance = Template.instance();
return instance.data.recordCount.get();
},
isRowsPerPageSelected(rowsPerPage) {
const instance = Template.instance();
return rowsPerPage === instance.data.rowsPerPage.get();
const recordCount = instance.data.recordCount.get();
const rowsPerPage = instance.data.rowsPerPage.get();
const currentPage = instance.data.currentPage.get();
// Show pagination if it is not first page or there are potentially more records
return currentPage > 0 || recordCount >= rowsPerPage;
}
});
Template.paginationArea.events({
'click .prev > a'(event, instance) {
const currentPage = instance.data.currentPage.get();
instance.data.currentPage.set(currentPage - 1);
},
'click .next > a'(event, instance) {
const currentPage = instance.data.currentPage.get();
instance.data.currentPage.set(currentPage + 1);
},
'change [data-key=rowsPerPage]'(event, instance) {
const rowsPerPage = $(event.currentTarget).data('component').value();
// Update rowsPerPage
instance.data.rowsPerPage.set(parseInt(rowsPerPage, 10));
instance.data.currentPage.set(0);
}
});

View File

@ -18,7 +18,7 @@
select
width: 42px
.page-number
.page-buttons
margin: 0
text-align: right
@ -29,28 +29,34 @@
margin: 0
li
display: table-cell
padding: 5px 2px
a
padding: 4px 8px
theme('background-color', '$primaryBackgroundColor')
theme('border-color', '$uiGray')
theme('background-color', '$uiGrayDarkest')
color: white
padding: 4px 8px
text-decoration: none
&:hover
theme('color', '$activeColor')
.active
a
theme('background-color', '$uiGray')
border-color: #ddd
color: white
.active
a
theme('background-color', '$uiGray')
border-color: #ddd
color: white
.disabled
cursor: not-allowed
a, a:hover, a:focus, a:active
theme('background-color', '$uiGrayDarkest')
theme('border-color', '$uiGray')
theme('color', '$uiGrayLight')
pointer-events: none
&:not(.disabled):hover a
theme('background-color', '$uiGrayDark')

View File

@ -29,6 +29,7 @@ OHIF.ui.handleError = error => {
cancelClass: 'btn-secondary'
}, error || {});
OHIF.log.error(error);
// TODO: Find a better way to handle errors instead of displaying a dialog for all of them.
// OHIF.ui.showDialog('dialogForm', data);
};

View File

@ -52,25 +52,33 @@ OHIF.ui.showPopover = (templateName, popoverData, options={}) => {
const popoverOptions = Object.assign({} , defaults, options);
popoverOptions.content = Blaze.toHTMLWithData(template, popoverData);
if (popoverOptions.hideOnClick) {
$element.click(function() {
$(this).popover('hide');
});
}
$element.popover(popoverOptions);
$element.one('shown.bs.popover', function(event) {
const popoverId = $element.attr('aria-describedby');
const popover = document.getElementById(popoverId);
const $popover = $(popover);
const $popoverContent = $popover.find('.popover-content');
const dismissPopover = () => $element.popover('hide');
if (popoverOptions.trigger !== 'hover') {
$element.one('shown.bs.popover', function(event) {
const popoverId = $element.attr('aria-describedby');
const popover = document.getElementById(popoverId);
const $popover = $(popover);
const $popoverContent = $popover.find('.popover-content');
const dismissPopover = () => $element.popover('hide');
$popoverContent.html('');
$popoverContent.html('');
const view = Blaze.renderWithData(template, templateData, $popoverContent[0]);
$element.one('hidden.bs.popover', () => {
Blaze.remove(view);
$element.popover('destroy');
const view = Blaze.renderWithData(template, templateData, $popoverContent[0]);
$element.one('hidden.bs.popover', () => {
Blaze.remove(view);
$element.popover('destroy');
});
promise.then(dismissPopover).catch(dismissPopover);
});
promise.then(dismissPopover).catch(dismissPopover);
});
}
if (popoverOptions.trigger === 'manual') {
$element.popover('show');

View File

@ -11,6 +11,7 @@ const OHIF = {
viewer: {},
cornerstone: {},
user: {},
DICOMWeb: {}, // Temporarily added
};
// Expose the OHIF object to the client if it is on development mode

View File

@ -1,5 +1,5 @@
Npm.depends({
'twbs-pagination': '1.4.1'
'isomorphic-base64': '1.0.2',
});
Package.describe({
@ -9,7 +9,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('standard-app-packages');
@ -44,5 +44,4 @@ Package.onUse(function(api) {
// Client and server imports
api.addFiles('both/index.js', ['client', 'server']);
});

View File

@ -42,9 +42,10 @@ export class MetadataProvider {
const seriesMetadata = data.series;
const studyMetadata = data.study;
const numImages = data.numImages;
const metadata = {};
metadata.frameNumber = data.frameNumber;
metadata.study = {
accessionNumber: studyMetadata.accessionNumber,
patientId: studyMetadata.patientId,

View File

@ -5,7 +5,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('ohif:cornerstone');

View File

@ -11,11 +11,11 @@ Npm.depends({
'cornerstone-math': '0.1.6',
'dicom-parser': '1.8.0',
'cornerstone-wado-image-loader': '2.1.4',
'dcmjs': '0.1.5'
'dcmjs': '0.2.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.versionsFrom('1.7');
api.use('ecmascript');

View File

@ -16,7 +16,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2.3');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('standard-app-packages');

View File

@ -1,27 +0,0 @@
Package.describe({
name: 'ohif:dicom-services',
summary: 'DICOM Services: DIMSE C-Service functions',
version: '0.0.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.use('http');
api.use('ecmascript');
// DIMSE functions
api.addFiles('server/DIMSE/require.js', 'server');
api.addFiles('server/DIMSE/constants.js', 'server');
api.addFiles('server/DIMSE/elements_data.js', 'server');
api.addFiles('server/DIMSE/Field.js', 'server');
api.addFiles('server/DIMSE/RWStream.js', 'server');
api.addFiles('server/DIMSE/Data.js', 'server');
api.addFiles('server/DIMSE/Message.js', 'server');
api.addFiles('server/DIMSE/PDU.js', 'server');
api.addFiles('server/DIMSE/CSocket.js', 'server');
api.addFiles('server/DIMSE/Connection.js', 'server');
api.addFiles('server/DIMSE/DIMSE.js', 'server');
api.export('DIMSE', 'server');
});

View File

@ -1,657 +0,0 @@
import { OHIF } from 'meteor/ohif:core';
var EventEmitter = Npm.require('events').EventEmitter;
function time() {
return Math.floor(Date.now() / 1000);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var Envelope = function(command, dataset) {
EventEmitter.call(this);
this.command = command;
this.dataset = dataset;
};
util.inherits(Envelope, EventEmitter);
CSocket = function(socket, options) {
EventEmitter.call(this);
this.socket = socket;
this.negotiatedContexts = {};
this.receiving = null;
this.receiveLength = null;
this.minRecv = null;
this.lastReceived = null;
this.presentationContexts = [];
this.associated = false;
this.pendingPDVs = null;
this.connected = false;
this.started = null;
this.intervalId = null;
this.lastCommand = null;
this.lastSent = null;
this.messages = {};
this.messageIdCounter = 0;
this.callingAe = null;
this.calledAe = null;
this.id = getRandomInt(1000, 9999);
this.options = options;
var o = this;
this.socket.on('connect', function() {
OHIF.log.info('Connect');
o.ready();
});
this.socket.on('data', function(data) {
o.received(data);
});
this.socket.on('error', function(socketError) {
OHIF.log.error('There was an error with DIMSE connection socket.');
OHIF.log.error(socketError.stack);
OHIF.log.trace();
o.emit('error', new Meteor.Error('server-internal-error', socketError.message));
});
this.socket.on('timeout', function(socketError) {
OHIF.log.error('The connection timed out. The server is not responding.');
OHIF.log.error(socketError.stack);
OHIF.log.trace();
o.emit('error', new Meteor.Error('server-connection-error', socketError.message));
});
this.socket.on('close', function() {
if (o.intervalId) {
clearInterval(o.intervalId);
}
o.connected = false;
OHIF.log.info('Connection closed');
o.emit('close');
});
this.on('released', function() {
this.released();
});
this.on('aborted', function(pdu) {
OHIF.log.warn('Association aborted with reason ' + pdu.reason);
this.released();
});
this.on('message', function(pdvs) {
this.receivedMessage(pdvs);
});
};
util.inherits(CSocket, EventEmitter);
CSocket.prototype.setCallingAE = function(ae) {
this.callingAe = ae;
};
CSocket.prototype.setCalledAe = function(ae) {
this.calledAe = ae;
};
CSocket.prototype.associate = function() {
var associateRQ = new AssociateRQ();
associateRQ.setCalledAETitle(this.calledAe);
associateRQ.setCallingAETitle(this.callingAe);
associateRQ.setApplicationContextItem(new ApplicationContextItem());
var contextItems = [];
this.presentationContexts.forEach(function(context) {
var contextItem = new PresentationContextItem(),
syntaxes = [];
context.transferSyntaxes.forEach(function(transferSyntax) {
var transfer = new TransferSyntaxItem();
transfer.setTransferSyntaxName(transferSyntax);
syntaxes.push(transfer);
});
contextItem.setTransferSyntaxesItems(syntaxes);
contextItem.setPresentationContextID(context.id);
var abstractItem = new AbstractSyntaxItem();
abstractItem.setAbstractSyntaxName(context.abstractSyntax);
contextItem.setAbstractSyntaxItem(abstractItem);
contextItems.push(contextItem);
});
associateRQ.setPresentationContextItems(contextItems);
var maxLengthItem = new MaximumLengthItem(),
classUIDItem = new ImplementationClassUIDItem(),
versionItem = new ImplementationVersionNameItem();
classUIDItem.setImplementationClassUID(C.IMPLEM_UID);
versionItem.setImplementationVersionName(C.IMPLEM_VERSION);
var packageSize = this.options.maxPackageSize ? this.options.maxPackageSize : C.DEFAULT_MAX_PACKAGE_SIZE;
maxLengthItem.setMaximumLengthReceived(packageSize);
var userInfo = new UserInformationItem();
userInfo.setUserDataItems([maxLengthItem, classUIDItem, versionItem]);
associateRQ.setUserInformationItem(userInfo);
this.send(associateRQ);
};
CSocket.prototype.getContext = function(id) {
for (var k in this.presentationContexts) {
var ctx = this.presentationContexts[k];
if (id === ctx.id) {
return ctx;
}
}
return null;
};
CSocket.prototype.getSyntax = function(contextId) {
if (!this.negotiatedContexts[contextId]) return null;
return this.negotiatedContexts[contextId].transferSyntax;
};
CSocket.prototype.getContextByUID = function(uid) {
for (var k in this.negotiatedContexts) {
var ctx = this.negotiatedContexts[k];
if (ctx.abstractSyntax === uid) {
return ctx;
}
}
return null;
};
CSocket.prototype.getContextId = function(contextId) {
if (!this.negotiatedContexts[contextId]) {
return null;
}
return this.negotiatedContexts[contextId].id;
};
CSocket.prototype.setPresentationContexts = function(uids) {
var contexts = [],
id = 0;
uids.forEach(function(uid) {
id++;
if (typeof uid === 'string') {
contexts.push({
id: id,
abstractSyntax: uid,
transferSyntaxes: [C.IMPLICIT_LITTLE_ENDIAN, C.EXPLICIT_LITTLE_ENDIAN, C.EXPLICIT_BIG_ENDIAN]
});
} else {
contexts.push({
id: id,
abstractSyntax: uid.context,
transferSyntaxes: uid.syntaxes
});
}
});
this.presentationContexts = contexts;
};
CSocket.prototype.newMessageId = function() {
return (++this.messageIdCounter) % 65536;
};
CSocket.prototype.resetReceive = function() {
this.receiving = this.receiveLength = null;
};
CSocket.prototype.send = function(pdu, afterCbk) {
//console.log('SEND PDU-TYPE: ', pdu.type);
var toSend = pdu.buffer();
//console.log('send buffer', toSend.toString('hex'));
return this.socket.write(toSend, afterCbk ? afterCbk : null);
};
CSocket.prototype.release = function() {
var releaseRQ = new ReleaseRQ();
this.send(releaseRQ);
};
CSocket.prototype.released = function() {
this.socket.end();
};
CSocket.prototype.ready = function() {
OHIF.log.info('Connection established');
this.connected = true;
this.started = time();
var o = this;
if (this.options.idle) {
this.intervalId = setInterval(function() {
o.checkIdle();
}, 3000);
}
};
CSocket.prototype.checkIdle = function() {
var current = time(),
idl = this.options.idle;
if (!this.lastReceived && (current - this.started >= idl)) {
this.idleClose();
} else if (this.lastReceived && (current - this.lastReceived >= idl)) {
this.idleClose();
}
};
CSocket.prototype.idleClose = function() {
OHIF.log.info('Exceed idle time, closing connection');
this.release();
};
CSocket.prototype.received = function(data) {
do {
data = this.process(data);
} while (data !== null);
this.lastReceived = time();
};
CSocket.prototype.process = function(data) {
if (this.receiving === null) {
if (this.minRecv) {
data = Buffer.concat([this.minRecv, data], this.minRecv.length + data.length);
this.minRecv = null;
}
if (data.length < 6) {
this.minRecv = data;
return null;
}
var stream = new ReadStream(data);
var type = stream.read(C.TYPE_UINT8);
stream.increment(1);
var len = stream.read(C.TYPE_UINT32),
cmp = data.length - 6;
if (len > cmp) {
this.receiving = data;
this.receiveLength = len;
} else {
var process = data,
remaining = null;
if (len < cmp) {
process = data.slice(0, len + 6);
remaining = data.slice(len + 6, cmp + 6);
}
this.resetReceive();
this.interpret(new ReadStream(process), this);
if (remaining) {
return remaining;
}
}
} else {
OHIF.log.info('Data received');
var newData = Buffer.concat([this.receiving, data], this.receiving.length + data.length),
pduLength = newData.length - 6;
if (pduLength < this.receiveLength) {
this.receiving = newData;
} else {
var remaining = null;
if (pduLength > this.receiveLength) {
remaining = newData.slice(this.receiveLength + 6, pduLength + 6);
newData = newData.slice(0, this.receiveLength + 6);
}
this.resetReceive();
this.interpret(new ReadStream(newData));
if (remaining) {
return remaining;
}
}
}
return null;
};
CSocket.prototype.interpret = function(stream) {
var pdatas = [],
size = stream.size(),
o = this;
while (stream.offset < size) {
var pdu = PDU.createByStream(stream);
//console.log("Received PDU-TYPE " + PDU.typeToString(pdu.type));
if (pdu.is(C.ITEM_TYPE_PDU_ASSOCIATE_AC)) {
pdu.presentationContextItems.forEach(function(ctx) {
var requested = o.getContext(ctx.presentationContextID);
if (!requested) {
throw 'Accepted presentation context not found';
}
o.negotiatedContexts[ctx.presentationContextID] = {
id: ctx.presentationContextID,
transferSyntax: ctx.transferSyntaxesItems[0].transferSyntaxName,
abstractSyntax: requested.abstractSyntax
};
});
//console.log('Accepted');
this.associated = true;
this.emit('associated', pdu);
} else if (pdu.is(C.ITEM_TYPE_PDU_ASSOCIATE_RQ)) {
var accepd = new AssociateAC();
pdu.presentationContextItems.forEach(function(ctx) {
});
} else if (pdu.is(C.ITEM_TYPE_PDU_RELEASE_RP)) {
//console.log('Released');
this.associated = false;
this.emit('released');
} else if (pdu.is(C.ITEM_TYPE_PDU_AABORT)) {
//console.log('Aborted');
this.emit('aborted', pdu);
} else if (pdu.is(C.ITEM_TYPE_PDU_PDATA)) {
pdatas.push(pdu);
}
}
if (pdatas) {
var pdvs = this.pendingPDVs ? this.pendingPDVs : [];
pdatas.forEach(function(pdata) {
pdvs = pdvs.concat(pdata.presentationDataValueItems);
});
this.pendingPDVs = null;
var i = 0,
count = pdvs.length;
while (i < count) {
if (!pdvs[i].isLast) {
var j = i + 1;
while (j < count) {
pdvs[i].messageStream.concat(pdvs[j].messageStream);
if (pdvs[j++].isLast) {
pdvs[i].isLast = true;
break;
}
}
if (pdvs[i].isLast) {
this.emit('message', pdvs[i]);
} else {
this.pendingPDVs = [pdvs[i]];
}
i = j;
} else {
this.emit('message', pdvs[i++]);
}
}
}
};
CSocket.prototype.receivedMessage = function(pdv) {
var syntax = this.getSyntax(pdv.contextId),
msg = DicomMessage.read(pdv.messageStream, pdv.type, syntax, this.options.vr);
if (msg.isCommand()) {
this.lastCommand = msg;
if (msg.isResponse()) {
var replyId = msg.respondedTo(),
listener = this.messages[replyId].listener;
if (msg.is(C.COMMAND_C_GET_RSP) || msg.is(C.COMMAND_C_MOVE_RSP)) {
//console.log('remaining', msg.getNumOfRemainingSubOperations(), msg.getNumOfCompletedSubOperations());
}
if (msg.failure()) {
OHIF.log.info('message failed with status ', msg.getStatus().toString(16));
}
listener.emit('response', msg);
if (msg.isFinal()) {
if (listener) {
listener.emit('end', msg);
if (!msg.haveData())
delete this.messages[replyId];
}
if (msg.is(C.COMMAND_C_GET_RSP)) {
if (!msg.getNumOfRemainingSubOperations()) {
if (this.lastGets && this.lastGets.length > 0) this.lastGets.shift();
}
}
}
} else {
/*if (msg.is(0x01)) {
console.log('ae title ', msg.getValue(0x00001031))
}*/
}
} else {
if (!this.lastCommand) {
throw 'Only dataset?';
} else if (!this.lastCommand.haveData()) {
throw "Last command didn't indicate presence of data";
}
if (this.lastCommand.isResponse()) {
var replyId = this.lastCommand.respondedTo();
if (this.messages[replyId].listener) {
var flag = this.lastCommand.failure() ? true : false;
this.messages[replyId].listener.emit('result', msg, flag);
if (this.lastCommand.failure()) {
delete this.messages[replyId];
}
}
} else {
if (this.lastCommand.is(C.COMMAND_C_STORE_RQ)) {
var moveMessageId = this.lastCommand.getMoveMessageId(),
useId = moveMessageId;
if (!moveMessageId) {
//!! Going to deprecate now
//kinda hacky but we know this c-store is came from a c-get
if (this.lastGets.length > 0) {
useId = this.lastGets[0];
} else {
throw 'Where does this c-store came from?';
}
} else{
OHIF.log.info('move ', moveMessageId);
}
//this.storeResponse(useId, msg);
}
}
}
};
CSocket.prototype.wrapToPData = function(message, context) {
var useContext = message.contextUID ? message.contextUID : context;
var ctx = this.getContextByUID(useContext);
var pdata = new PDataTF(),
pdv = new PresentationDataValueItem(ctx.id);
pdv.setMessage(message);
pdata.setPresentationDataValueItems([pdv]);
return pdata;
};
CSocket.prototype.sendMessage = function(context, command, dataset) {
var nContext = this.getContextByUID(context),
syntax = nContext.transferSyntax,
cid = nContext.id,
messageId = this.newMessageId(),
msgData = {};
msgData.listener = new Envelope(command);
var o = this;
msgData.listener.on('cancel', function() {
var cancelMessage = null;
if (this.command.is(C.COMMAND_C_FIND_RQ) || this.command.is(C.COMMAND_C_MOVE_RQ)) {
cancelMessage = new CCancelRQ();
cancelMessage.setReplyMessageId(this.command.messageId);
cancelMessage.setSyntax(C.IMPLICIT_LITTLE_ENDIAN);
o.send(o.wrapToPData(cancelMessage, this.command.contextUID));
}
});
command.setSyntax(C.IMPLICIT_LITTLE_ENDIAN);
command.setContextId(context);
command.setMessageId(messageId);
if (dataset) {
command.setDataSetPresent(C.DATA_SET_PRESENT);
}
this.lastSent = command;
if (command.is(C.COMMAND_C_GET_RQ)) {
this.lastGets.push(messageId);
}
var pdata = this.wrapToPData(command);
msgData.command = command;
this.messages[messageId] = msgData;
OHIF.log.info('Sending command ' + command.typeString());
this.send(pdata);
if (dataset && typeof dataset === 'object') {
dataset.setSyntax(syntax);
var dsData = new PDataTF(),
dPdv = new PresentationDataValueItem(cid);
dPdv.setMessage(dataset);
dsData.setPresentationDataValueItems([dPdv]);
this.send(dsData);
}
return msgData.listener;
};
CSocket.prototype.sendPData = function(pdv, after) {
var pdata = new PDataTF();
pdata.setPresentationDataValueItems([pdv]);
//console.log('Sending pdata');
//console.log(pdata.totalLength());
this.send(pdata, after);
};
CSocket.prototype.verify = function() {
this.setPresentationContexts([C.SOP_VERIFICATION]);
this.startAssociationRequest(function() {
//associated, we can release now
this.release();
});
};
CSocket.prototype.wrapMessage = function(data) {
if (data) {
var datasetMessage = new DataSetMessage();
datasetMessage.setElements(data);
return datasetMessage;
} else {
return data;
}
};
CSocket.prototype.find = function(params, options) {
return this.sendMessage(options.context, new CFindRQ(), this.wrapMessage(params));
};
CSocket.prototype.move = function(destination, params, options) {
var moveMessage = new CMoveRQ();
moveMessage.setDestination(destination);
return this.sendMessage(options.context, moveMessage, this.wrapMessage(params));
};
CSocket.prototype.storeInstance = function(sopClassUID, sopInstanceUID, options) {
var storeMessage = new CStoreRQ();
storeMessage.setAffectedSOPInstanceUID(sopInstanceUID);
storeMessage.setAffectedSOPClassUID(sopClassUID);
return this.sendMessage(sopClassUID, storeMessage, true);
};
CSocket.prototype.moveInstances = function(destination, params, options) {
var sendParams = Object.assign({
0x00080052: C.QUERY_RETRIEVE_LEVEL_IMAGE,
}, params);
options = Object.assign({
context: C.SOP_STUDY_ROOT_MOVE
}, options);
return this.move(destination, sendParams, options);
};
CSocket.prototype.findPatients = function(params, options) {
var sendParams = Object.assign({
0x00080052: C.QUERY_RETRIEVE_LEVEL_PATIENT,
0x00100010: '',
0x00100020: '',
0x00100030: '',
0x00100040: '',
}, params);
options = Object.assign({
context: C.SOP_PATIENT_ROOT_FIND
}, options);
return this.find(sendParams, options);
};
CSocket.prototype.findStudies = function(params, options) {
var sendParams = Object.assign({
0x00080052: C.QUERY_RETRIEVE_LEVEL_STUDY,
0x00080020: '',
0x00100010: '',
0x00080061: '',
0x0020000D: ''
}, params);
options = Object.assign({
context: C.SOP_STUDY_ROOT_FIND
}, options);
return this.find(sendParams, options);
};
CSocket.prototype.findSeries = function(params, options) {
var sendParams = Object.assign({
0x00080052: C.QUERY_RETRIEVE_LEVEL_SERIES,
0x00080020: '',
0x0020000E: '',
0x0008103E: '',
0x0020000D: ''
}, params);
options = Object.assign({
context: C.SOP_STUDY_ROOT_FIND
}, options);
return this.find(sendParams, options);
};
CSocket.prototype.findInstances = function(params, options) {
var sendParams = Object.assign({
0x00080052: C.QUERY_RETRIEVE_LEVEL_IMAGE,
0x00080020: '',
0x0020000E: '',
0x0008103E: '',
0x0020000D: ''
}, params);
options = Object.assign({
context: C.SOP_STUDY_ROOT_FIND
}, options);
return this.find(sendParams, options);
};

View File

@ -1,291 +0,0 @@
import { _ } from 'meteor/underscore';
import { OHIF } from 'meteor/ohif:core';
// Uses NodeJS 'net'
// https://nodejs.org/api/net.html
var net = Npm.require('net');
var Socket = net.Socket;
Connection = function(options) {
EventEmitter.call(this);
this.options = Object.assign({
maxPackageSize: C.DEFAULT_MAX_PACKAGE_SIZE,
idle: false,
reconnect: true,
vr: {
split: true
}
}, options);
this.reset();
};
util.inherits(Connection, EventEmitter);
var StoreHandle = function() {
EventEmitter.call(this);
};
util.inherits(StoreHandle, EventEmitter);
Connection.prototype.reset = function() {
this.defaultPeer = null;
this.defaultServer = null;
_.each(this.peers, peerInfo => {
_.each(peerInfo.sockets, socket => socket.emit('close'));
});
this.peers = {};
};
Connection.prototype.addPeer = function(options) {
if (!options.aeTitle || !options.host || !options.port) {
return false;
}
var peer = {
host: options.host,
port: options.port,
sockets: {}
};
this.peers[options.aeTitle] = peer;
if (options.default) {
if (options.server) {
this.defaultServer = options.aeTitle;
} else {
this.defaultPeer = options.aeTitle;
}
}
if (options.server) {
//start listening
peer.server = net.createServer();
peer.server.listen(options.port, options.host, function() {
OHIF.log.info('listening on', this.address());
});
peer.server.on('error', function(err) {
OHIF.log.info('server error', err);
});
peer.server.on('connection', nativeSocket => {
//incoming connections
var socket = new CSocket(nativeSocket, this.options);
this.addSocket(options.aeTitle, socket);
//close server on close socket
socket.on('close', function() {
peer.server.close();
});
});
}
};
Connection.prototype.selectPeer = function(aeTitle) {
if (!aeTitle || !this.peers[aeTitle]) {
throw 'No such peer';
}
return this.peers[aeTitle];
};
Connection.prototype._sendFile = function(socket, sHandle, file, maxSend, metaLength, list) {
var fileNameText = typeof file.file === 'string' ? file.file : 'buffer';
OHIF.log.info(`Sending file ${fileNameText}`);
var useContext = socket.getContextByUID(file.context);
var self = this;
PDU.generatePDatas(useContext.id, file.file, maxSend, null, metaLength, function(err, handle) {
if (err) {
OHIF.log.info('Error while sending file');
return;
}
var processNext = function() {
var next = list.shift();
if (next) {
self._sendFile(socket, sHandle, next, maxSend, metaLength, list);
} else {
socket.release();
}
};
var store = socket.storeInstance(useContext.abstractSyntax, file.uid);
handle.on('pdv', function(pdv) {
socket.sendPData(pdv);
});
handle.on('error', function(err) {
sHandle.emit('file', err, fileNameText);
processNext();
});
store.on('response', function(msg) {
var statusText = msg.getStatus().toString(16);
OHIF.log.info('STORE reponse with status', statusText);
var error = null;
if (msg.failure()) {
error = new Error(statusText);
}
sHandle.emit('file', error, fileNameText);
processNext();
});
});
};
Connection.prototype.storeInstances = function(fileList) {
var contexts = {};
var read = 0;
var length = fileList.length;
var toSend = [];
var self = this;
var handle = new StoreHandle();
var lastProcessedMetaLength;
fileList.forEach(function(bufferOrFile) {
var fileNameText = typeof bufferOrFile === 'string' ? bufferOrFile : 'buffer';
DicomMessage.readMetaHeader(bufferOrFile, function(err, metaMessage, metaLength) {
read++;
if (err) {
handle.emit('file', err, fileNameText);
if (read === length && toSend.length > 0 && lastProcessedMetaLength) {
sendProcessedFiles(self, contexts, toSend, handle, lastProcessedMetaLength);
}
return;
}
OHIF.log.info(`Dicom file ${(typeof bufferOrFile === 'string' ? bufferOrFile : 'buffer')} found`);
lastProcessedMetaLength = metaLength;
var syntax = metaMessage.getValue(0x00020010);
var sopClassUID = metaMessage.getValue(0x00020002);
var instanceUID = metaMessage.getValue(0x00020003);
if (!contexts[sopClassUID]) {
contexts[sopClassUID] = [];
}
if (syntax && contexts[sopClassUID].indexOf(syntax) === -1) {
contexts[sopClassUID].push(syntax);
}
toSend.push({
file: bufferOrFile,
context: sopClassUID,
uid: instanceUID
});
if (read === length) {
sendProcessedFiles(self, contexts, toSend, handle, metaLength);
}
});
});
return handle;
};
// Starts to send dcm files
sendProcessedFiles = function(self, contexts, toSend, handle, metaLength) {
var useContexts = [];
_.each(contexts, (useSyntaxes, context) => {
if (useSyntaxes.length > 0) {
useContexts.push({
context: context,
syntaxes: useSyntaxes
});
} else {
throw 'No syntax specified for context ' + context;
}
});
self.associate({
contexts: useContexts
}, function(ac) {
var maxSend = ac.getMaxSize();
var next = toSend.shift();
self._sendFile(this, handle, next, maxSend, metaLength, toSend);
});
};
Connection.prototype.storeResponse = function(messageId, msg) {
var rq = this.messages[messageId];
if (rq.listener[2]) {
var status = rq.listener[2].call(this, msg);
if (status !== undefined && status !== null && rq.command.store) {
//store ok, ready to send c-store-rsp
var storeSr = rq.command.store;
var replyMessage = storeSr.replyWith(status);
replyMessage.setAffectedSOPInstanceUID(this.lastCommand.getSOPInstanceUID());
replyMessage.setReplyMessageId(this.lastCommand.messageId);
this.sendMessage(replyMessage, null, null, storeSr);
} else {
throw 'Missing store status';
}
}
};
Connection.prototype.allClosed = function() {
var allClosed = true;
for (var i in this.peers) {
if (Object.keys(peers[i].sockets).length > 0) {
allClosed = false;
break;
}
}
return allClosed;
};
Connection.prototype.addSocket = function(hostAE, socket) {
var peerInfo = this.selectPeer(hostAE);
peerInfo.sockets[socket.id] = socket;
socket.on('close', function() {
if (peerInfo.sockets[this.id]) {
delete peerInfo.sockets[this.id];
}
});
};
Connection.prototype.associate = function(options, callback) {
const self = this;
var hostAE = options.hostAE ? options.hostAE : this.defaultPeer;
var sourceAE = options.sourceAE ? options.sourceAE : this.defaultServer;
if (!hostAE || !sourceAE) {
throw 'Peers not provided or no defaults in settings';
}
var peerInfo = this.selectPeer(hostAE);
var nativeSocket = new Socket();
var socket = new CSocket(nativeSocket, this.options);
if (callback) {
socket.once('associated', callback);
}
OHIF.log.info('Starting Connection...');
socket.setCalledAe(hostAE);
socket.setCallingAE(sourceAE);
nativeSocket.connect({
host: peerInfo.host,
port: peerInfo.port
}, () => {
//connected
this.addSocket(hostAE, socket);
if (options.contexts) {
socket.setPresentationContexts(options.contexts);
} else {
throw new Meteor.Error('Contexts must be specified');
}
socket.associate();
});
return socket;
};

View File

@ -1,368 +0,0 @@
import { OHIF } from 'meteor/ohif:core';
var Future = Npm.require('fibers/future');
DIMSE = {
connection: new Connection({
vr: {
split: false
}
})
};
var conn = DIMSE.connection;
var getInstanceRetrievalParams = function(studyInstanceUID, seriesInstanceUID) {
return {
0x0020000D: studyInstanceUID ? studyInstanceUID : '',
0x0020000E: (studyInstanceUID && seriesInstanceUID) ? seriesInstanceUID : '',
0x00080005: '', // specificCharacterSet
0x00080020: '', // studyDate
0x00080030: '', // studyDescription
0x00080090: '', // referringPhysicianName
0x00100010: '', // patientName
0x00100020: '', // patientId
0x00100030: '', // patientBirthDate
0x00100040: '', // patientSex
0x00200010: '', // studyId
0x0008103E: '', // seriesDescription
0x00200011: '', // seriesNumber
0x00080080: '', // institutionName
0x00080016: '', // sopClassUid
0x00080018: '', // sopInstanceUid
0x00080060: '', // modality
0x00200013: '', // instanceNumber
0x00280010: '', // rows
0x00280011: '', // columns
0x00280100: '', // bitsAllocated
0x00280101: '', // bitsStored
0x00280102: '', // highBit
0x00280103: '', // pixelRepresentation
0x00280004: '', // photometricInterpretation
0x0008002A: '', // acquisitionDatetime
0x00280008: '', // numFrames
//0x00280009: '', // frameIncrementPointer // This appears to be breaking Orthanc DIMSE connections
0x00181063: '', // frameTime
0x00181065: '', // frameTimeVector
0x00281052: '', // rescaleIntercept
0x00281053: '', // rescaleSlope
0x00280002: '', // samplesPerPixel
0x00180050: '', // sliceThickness
0x00201041: '', // sliceLocation
//0x00189327: '', // tablePosition // This appears to be breaking Orthanc DIMSE connections
0x00281050: '', // windowCenter
0x00281051: '', // windowWidth
0x00280030: '', // pixelSpacing
0x00200062: '', // laterality
0x00185101: '', // viewPosition
0x00080008: '', // imageType
0x00200032: '', // imagePositionPatient
0x00200037: '', // imageOrientationPatient
0x00200052: '', // frameOfReferenceUID
0x00282110: '', // lossyImageCompression
0x00282112: '', // lossyImageCompressionRatio
0x00282114: '', // lossyImageCompressionMethod,
0x00180088: '' // spacingBetweenSlices
// Orthanc has a bug here so we can't retrieve sequences at the moment
// https://groups.google.com/forum/#!topic/orthanc-users/ghKJfvtnK8Y
//0x00282111: '', // derivationDescription
//0x00082112: '' // sourceImageSequence
};
};
DIMSE.associate = function(contexts, callback, options) {
var defaults = {
contexts: contexts
};
options = Object.assign(defaults, options);
OHIF.log.info('Associating...');
const socket = conn.associate(options, function(pdu) {
// associated
OHIF.log.info('==Associated');
callback.call(this, null, pdu);
});
socket.on('error', function (error) {
callback(error, null);
});
socket.on('timeout', function (error) {
callback(error, null);
});
};
DIMSE.retrievePatients = function(params, options) {
//var start = new Date();
var future = new Future;
DIMSE.associate([C.SOP_PATIENT_ROOT_FIND], function(error, pdu) {
if (error) {
OHIF.log.error('Could not retrieve patients');
OHIF.log.trace();
return future.return([]);
}
var defaultParams = {
0x00100010: '',
0x00100020: '',
0x00100030: '',
0x00100040: '',
0x00101010: '',
0x00101040: ''
};
var result = this.findPatients(Object.assign(defaultParams, params)),
o = this;
var patients = [];
result.on('result', function(msg) {
patients.push(msg);
});
result.on('end', function() {
o.release();
});
this.on('close', function() {
//var time = new Date() - start;console.log(time + 'ms taken');
future.return(patients);
});
}, options);
return future.wait();
};
DIMSE.retrieveStudies = function(params, options) {
//var start = new Date();
var future = new Future;
DIMSE.associate([C.SOP_STUDY_ROOT_FIND], function(error, pdu) {
if (error) {
OHIF.log.error('Could not retrieve studies');
OHIF.log.trace();
return future.throw(error);
}
var defaultParams = {
0x0020000D: '',
0x00080060: '',
0x00080005: '',
0x00080020: '',
0x00080030: '',
0x00080090: '',
0x00100010: '',
0x00100020: '',
0x00200010: '',
0x00100030: ''
};
var result = this.findStudies(Object.assign(defaultParams, params)),
o = this;
var studies = [];
result.on('result', function(msg) {
studies.push(msg);
});
result.on('end', function() {
o.release();
});
this.on('close', function() {
//var time = new Date() - start;console.log(time + 'ms taken');
future.return(studies);
});
}, options);
return future.wait();
};
DIMSE._retrieveInstancesBySeries = function(conn, series, studyInstanceUID, callback, params) {
var aSeries = series.shift(),
seriesInstanceUID = aSeries.getValue(0x0020000E),
defaultParams = getInstanceRetrievalParams(studyInstanceUID, seriesInstanceUID);
var result = conn.findInstances(Object.assign(defaultParams, params)),
instances = [];
result.on('result', function(msg) {
instances.push(msg);
});
result.on('end', function() {
if (series.length > 0) {
callback(instances, false);
DIMSE._retrieveInstancesBySeries(conn, series, studyInstanceUID, callback, params);
} else {
callback(instances, true);
}
});
};
DIMSE.retrieveInstancesByStudyOnlyMulti = function(studyInstanceUID, params, options) {
if (!studyInstanceUID) {
return [];
}
var series = DIMSE.retrieveSeries(studyInstanceUID, params, options),
instances = [];
series.forEach(function(seriesData) {
var seriesInstanceUID = seriesData.getValue(0x0020000E);
var relatedInstances = DIMSE.retrieveInstances(studyInstanceUID, seriesInstanceUID, params, options);
instances = instances.concat(relatedInstances);
});
return instances;
};
DIMSE.retrieveInstancesByStudyOnly = function(studyInstanceUID, params, options) {
if (!studyInstanceUID) {
return [];
}
var future = new Future;
DIMSE.associate([C.SOP_STUDY_ROOT_FIND], function(error, pdu) {
if (error) {
OHIF.log.error('Could not retrieve Instances By Study');
OHIF.log.trace();
return future.throw(error);
}
var defaultParams = {
0x0020000D: studyInstanceUID,
0x00080005: '',
0x00080020: '',
0x00080030: '',
0x00080090: '',
0x00100010: '',
0x00100020: '',
0x00200010: '',
0x0008103E: '',
0x0020000E: '',
0x00200011: ''
};
var result = this.findSeries(Object.assign(defaultParams, params));
var series = [];
var conn = this;
var allInstances = [];
result.on('result', function(msg) {
series.push(msg);
});
result.on('end', function() {
if (series.length > 0) {
DIMSE._retrieveInstancesBySeries(conn, series, studyInstanceUID, function(relatedInstances, isEnd) {
allInstances = allInstances.concat(relatedInstances);
if (isEnd) {
conn.release();
}
});
} else {
conn.release();
}
});
conn.on('close', function() {
future.return(allInstances);
});
});
return future.wait();
};
DIMSE.retrieveSeries = function(studyInstanceUID, params, options) {
var future = new Future;
DIMSE.associate([C.SOP_STUDY_ROOT_FIND], function(error, pdu) {
if (error) {
OHIF.log.error('Could not retrieve series');
OHIF.log.trace();
return future.return([]);
}
var defaultParams = {
0x0020000D: studyInstanceUID ? studyInstanceUID : '',
0x00080005: '',
0x00080020: '',
0x00080030: '',
0x00080090: '',
0x00100010: '',
0x00100020: '',
0x00200010: '',
0x0008103E: '',
0x0020000E: '',
0x00200011: ''
};
var result = this.findSeries(Object.assign(defaultParams, params)),
o = this;
var series = [];
result.on('result', function(msg) {
series.push(msg);
});
result.on('end', function() {
o.release();
});
this.on('close', function() {
future.return(series);
});
}, options);
return future.wait();
};
DIMSE.retrieveInstances = function(studyInstanceUID, seriesInstanceUID, params, options) {
var future = new Future;
DIMSE.associate([C.SOP_STUDY_ROOT_FIND], function(error, pdu) {
if (error) {
OHIF.log.error('Could not retrieve instances');
OHIF.log.trace();
return future.throw(error);
}
var defaultParams = getInstanceRetrievalParams(studyInstanceUID, seriesInstanceUID);
var result = this.findInstances(Object.assign(defaultParams, params)),
o = this;
var instances = [];
result.on('result', function(msg) {
instances.push(msg);
});
result.on('end', function() {
o.release();
});
this.on('close', function() {
future.return(instances);
});
}, options);
return future.wait();
};
DIMSE.storeInstances = function(fileList, callback) {
var handle = conn.storeInstances(fileList);
handle.on('file', function(err, file) {
callback(err, file);
});
};
DIMSE.moveInstances = function(studyInstanceUID, seriesInstanceUID, sopInstanceUID, sopClassUID, params) {
DIMSE.associate([C.SOP_STUDY_ROOT_MOVE, sopClassUID], function(error) {
if (error) {
OHIF.log.error('Could not move instances');
OHIF.log.trace();
return;
}
var defaultParams = {
0x0020000D: studyInstanceUID ? studyInstanceUID : '',
0x0020000E: seriesInstanceUID ? seriesInstanceUID : '',
0x00080018: sopInstanceUID ? sopInstanceUID : ''
};
this.moveInstances('OHIFDCM', Object.assign(defaultParams, params));
});
};

File diff suppressed because it is too large Load Diff

View File

@ -1,156 +0,0 @@
Field = function(type, value) {
this.type = type;
this.value = value;
};
Field.prototype.length = function() {
return calcLength(this.type, this.value);
};
Field.prototype.write = function(stream) {
stream.write(this.type, this.value);
};
Field.prototype.isNumeric = function() {
return false;
};
BufferField = function(buffer, start, length) {
Field.call(this, C.TYPE_BUFFER, buffer);
this.bufferLength = length;
this.bufferStart = start;
};
util.inherits(BufferField, Field);
BufferField.prototype.length = function() {
return this.bufferLength;
};
BufferField.prototype.write = function(stream) {
stream.writeRawBuffer(this.value, this.bufferStart, this.bufferLength);
};
StringField = function(str) {
Field.call(this, C.TYPE_ASCII, typeof str == 'string' ? str : '');
};
util.inherits(StringField, Field);
FilledField = function(value, length) {
Field.call(this, C.TYPE_COMPOSITE, value);
this.fillLength = length;
};
util.inherits(FilledField, Field);
FilledField.prototype.length = function() {
return this.fillLength;
};
FilledField.prototype.write = function(stream) {
var len = this.value.length;
if (len < this.fillLength && len >= 0) {
if (len > 0)
stream.write(C.TYPE_ASCII, this.value);
var zeroLength = this.fillLength - len;
stream.write(C.TYPE_HEX, '20'.repeat(zeroLength));
} else if (len == this.fillLength) {
stream.write(C.TYPE_ASCII, this.value);
} else {
throw 'Length mismatch';
}
};
HexField = function(hex) {
Field.call(this, C.TYPE_HEX, hex);
};
util.inherits(HexField, Field);
ReservedField = function(length) {
length = length || 1;
Field.call(this, C.TYPE_HEX, '00'.repeat(length));
};
util.inherits(ReservedField, Field);
UInt8Field = function(value) {
Field.call(this, C.TYPE_UINT8, value);
};
util.inherits(UInt8Field, Field);
UInt8Field.prototype.isNumeric = function() {
return true;
};
UInt16Field = function(value) {
Field.call(this, C.TYPE_UINT16, value);
};
util.inherits(UInt16Field, Field);
UInt16Field.prototype.isNumeric = function() {
return true;
};
UInt32Field = function(value) {
Field.call(this, C.TYPE_UINT32, value);
};
util.inherits(UInt32Field, Field);
UInt32Field.prototype.isNumeric = function() {
return true;
};
Int8Field = function(value) {
Field.call(this, C.TYPE_INT8, value);
};
util.inherits(Int8Field, Field);
Int8Field.prototype.isNumeric = function() {
return true;
};
Int16Field = function(value) {
Field.call(this, C.TYPE_INT16, value);
};
util.inherits(Int16Field, Field);
Int16Field.prototype.isNumeric = function() {
return true;
};
Int32Field = function(value) {
Field.call(this, C.TYPE_INT32, value);
};
util.inherits(Int32Field, Field);
Int32Field.prototype.isNumeric = function() {
return true;
};
FloatField = function(value) {
Field.call(this, C.TYPE_FLOAT, value);
};
util.inherits(FloatField, Field);
FloatField.prototype.isNumeric = function() {
return true;
};
DoubleField = function(value) {
Field.call(this, C.TYPE_DOUBLE, value);
};
util.inherits(DoubleField, Field);
DoubleField.prototype.isNumeric = function() {
return true;
};

View File

@ -1,590 +0,0 @@
DicomMessage = function(syntax) {
this.syntax = syntax ? syntax : null;
this.type = C.DATA_TYPE_COMMAND;
this.messageId = C.DEFAULT_MESSAGE_ID;
this.elementPairs = {};
};
DicomMessage.prototype.isCommand = function() {
return this.type == C.DATA_TYPE_COMMAND;
};
DicomMessage.prototype.setSyntax = function(syntax) {
this.syntax = syntax;
for (var tag in this.elementPairs) {
this.elementPairs[tag].setSyntax(this.syntax);
}
};
DicomMessage.prototype.setMessageId = function(id) {
this.messageId = id;
};
DicomMessage.prototype.setReplyMessageId = function(id) {
this.replyMessageId = id;
};
DicomMessage.prototype.command = function(cmds) {
cmds.unshift(this.newElement(0x00000800, this.dataSetPresent ? C.DATA_SET_PRESENT : C.DATE_SET_ABSENCE));
cmds.unshift(this.newElement(0x00000700, this.priority));
cmds.unshift(this.newElement(0x00000110, this.messageId));
cmds.unshift(this.newElement(0x00000100, this.commandType));
cmds.unshift(this.newElement(0x00000002, this.contextUID));
var length = 0;
cmds.forEach(function(cmd) {
length += cmd.length(cmd.getFields());
});
cmds.unshift(this.newElement(0x00000000, length));
return cmds;
};
DicomMessage.prototype.response = function(cmds) {
cmds.unshift(this.newElement(0x00000800, this.dataSetPresent ? C.DATA_SET_PRESENT : C.DATE_SET_ABSENCE));
cmds.unshift(this.newElement(0x00000120, this.replyMessageId));
cmds.unshift(this.newElement(0x00000100, this.commandType));
if (this.contextUID)
cmds.unshift(this.newElement(0x00000002, this.contextUID));
var length = 0;
cmds.forEach(function(cmd) {
length += cmd.length(cmd.getFields());
});
cmds.unshift(this.newElement(0x00000000, length));
return cmds;
};
DicomMessage.prototype.setElements = function(pairs) {
var p = {};
for (var tag in pairs) {
p[tag] = this.newElement(tag, pairs[tag]);
}
this.elementPairs = p;
};
DicomMessage.prototype.newElement = function(tag, value) {
return elementByType(tag, value, this.syntax);
};
DicomMessage.prototype.setElement = function(key, value) {
this.elementPairs[key] = elementByType(key, value);
};
DicomMessage.prototype.setElementPairs = function(pairs) {
this.elementPairs = pairs;
};
DicomMessage.prototype.setContextId = function(context) {
this.contextUID = context;
};
DicomMessage.prototype.setPriority = function(pri) {
this.priority = pri;
};
DicomMessage.prototype.setType = function(type) {
this.type = type;
};
DicomMessage.prototype.setDataSetPresent = function(present) {
this.dataSetPresent = present == 0x0101 ? false : true;
};
DicomMessage.prototype.haveData = function() {
return this.dataSetPresent;
};
DicomMessage.prototype.tags = function() {
return Object.keys(this.elementPairs);
};
DicomMessage.prototype.key = function(tag) {
return elementKeywordByTag(tag);
};
DicomMessage.prototype.getValue = function(tag) {
return this.elementPairs[tag] ? this.elementPairs[tag].getValue() : null;
};
DicomMessage.prototype.affectedSOPClassUID = function() {
return this.getValue(0x00000002);
};
DicomMessage.prototype.getMessageId = function() {
return this.getValue(0x00000110);
};
DicomMessage.prototype.getFields = function() {
var eles = [];
for (var tag in this.elementPairs) {
eles.push(this.elementPairs[tag]);
}
return eles;
};
DicomMessage.prototype.length = function(elems) {
var len = 0;
elems.forEach(function(elem) {
len += elem.length(elem.getFields());
});
return len;
};
DicomMessage.prototype.isResponse = function() {
return false;
};
DicomMessage.prototype.is = function(type) {
return this.commandType == type;
};
DicomMessage.prototype.write = function(stream) {
var fields = this.getFields(),
o = this;
fields.forEach(function(field) {
field.setSyntax(o.syntax);
field.write(stream);
});
};
DicomMessage.prototype.printElements = function(pairs, indent) {
var typeName = '';
for (var tag in pairs) {
var value = pairs[tag].getValue();
typeName += (' '.repeat(indent)) + this.key(tag) + ' : ';
if (value instanceof Array) {
var o = this;
value.forEach(function(p) {
if (typeof p == 'object') {
typeName += '[\n' + o.printElements(p, indent + 2) + (' '.repeat(indent)) + ']';
} else {
typeName += '[' + p + ']';
}
});
if (typeName[typeName.length - 1] != '\n') {
typeName += '\n';
}
} else {
typeName += value + '\n';
}
}
return typeName;
};
DicomMessage.prototype.typeString = function() {
var typeName = '';
if (!this.isCommand()) {
typeName = 'DateSet Message';
} else {
switch (this.commandType) {
case C.COMMAND_C_GET_RSP : typeName = 'C-GET-RSP'; break;
case C.COMMAND_C_MOVE_RSP : typeName = 'C-MOVE-RSP'; break;
case C.COMMAND_C_GET_RQ : typeName = 'C-GET-RQ'; break;
case C.COMMAND_C_STORE_RQ : typeName = 'C-STORE-RQ'; break;
case C.COMMAND_C_FIND_RSP : typeName = 'C-FIND-RSP'; break;
case C.COMMAND_C_MOVE_RQ : typeName = 'C-MOVE-RQ'; break;
case C.COMMAND_C_FIND_RQ : typeName = 'C-FIND-RQ'; break;
case C.COMMAND_C_STORE_RSP : typeName = 'C-STORE-RSP'; break;
}
}
return typeName;
};
DicomMessage.prototype.toString = function() {
var typeName = this.typeString();
typeName += ' [\n';
typeName += this.printElements(this.elementPairs, 0);
typeName += ']';
return typeName;
};
DicomMessage.prototype.walkObject = function(pairs) {
var obj = {},
o = this;
for (var tag in pairs) {
var v = pairs[tag].getValue(),
u = v;
if (v instanceof Array) {
u = [];
v.forEach(function(a) {
if (typeof a == 'object') {
u.push(o.walkObject(a));
} else u.push(a);
});
}
obj[tag] = u;
}
return obj;
};
DicomMessage.prototype.toObject = function() {
return this.walkObject(this.elementPairs);
};
DicomMessage.readToPairs = function(stream, syntax, options) {
var pairs = {};
while (!stream.end()) {
var elem = new DataElement();
if (options) {
elem.setOptions(options);
}
elem.setSyntax(syntax);
elem.readBytes(stream);
pairs[elem.tag.value] = elem;
}
return pairs;
};
var fileValid = function(stream) {
return stream.readString(4, C.TYPE_ASCII) == 'DICM';
};
var readMetaStream = function(stream, useSyntax, length, callback) {
var message = new FileMetaMessage();
message.setElementPairs(DicomMessage.readToPairs(stream, useSyntax));
if (callback) {
callback(null, message, length);
}
return message;
};
DicomMessage.readMetaHeader = function(bufferOrFile, callback) {
var useSyntax = C.EXPLICIT_LITTLE_ENDIAN;
if (bufferOrFile instanceof Buffer) {
var stream = new ReadStream(bufferOrFile);
stream.reset();
stream.increment(128);
if (!fileValid(stream)) {
return quitWithError('Invalid a dicom file ', callback);
}
var el = readAElement(stream, useSyntax),
metaLength = el.value,
metaStream = stream.more(metaLength);
return readMetaStream(metaStream, useSyntax, metaLength, callback);
} else if (typeof bufferOrFile == 'string') {
fs.open(bufferOrFile, 'r', function(err, fd) {
if (err) {
//fs.closeSync(fd);
return quitWithError('Cannot open file', callback);
}
var buffer = Buffer.alloc(16);
fs.read(fd, buffer, 0, 16, 128, function(err, bytesRead) {
if (err || bytesRead != 16) {
fs.closeSync(fd);
return quitWithError('Cannot read file', callback);
}
var stream = new ReadStream(buffer);
if (!fileValid(stream)) {
fs.closeSync(fd);
return quitWithError('Not a dicom file ' + bufferOrFile, callback);
}
var el = readAElement(stream, useSyntax),
metaLength = el.value,
metaBuffer = Buffer.alloc(metaLength);
fs.read(fd, metaBuffer, 0, metaLength, 144, function(err, bytesRead) {
fs.closeSync(fd);
if (err || bytesRead != metaLength) {
return quitWithError('Invalid a dicom file ' + bufferOrFile, callback);
}
var metaStream = new ReadStream(metaBuffer);
return readMetaStream(metaStream, useSyntax, metaLength, callback);
});
});
});
}
return null;
};
DicomMessage.read = function(stream, type, syntax, options) {
var elements = [],
pairs = {},
useSyntax = type == C.DATA_TYPE_COMMAND ? C.IMPLICIT_LITTLE_ENDIAN : syntax;
stream.reset();
while (!stream.end()) {
var elem = new DataElement();
if (options) {
elem.setOptions(options);
}
elem.setSyntax(useSyntax);
elem.readBytes(stream);//return;
pairs[elem.tag.value] = elem;
}
var message = null;
if (type == C.DATA_TYPE_COMMAND) {
var cmdType = pairs[0x00000100].value;
switch (cmdType) {
case 0x8020 : message = new CFindRSP(useSyntax); break;
case 0x8021 : message = new CMoveRSP(useSyntax); break;
case 0x8010 : message = new CGetRSP(useSyntax); break;
case 0x0001 : message = new CStoreRQ(useSyntax); break;
case 0x0020 : message = new CFindRQ(useSyntax); break;
case 0x8001 : message = new CStoreRSP(useSyntax); break;
default : throw 'Unrecognized command type ' + cmdType.toString(16); break;
}
message.setElementPairs(pairs);
message.setDataSetPresent(message.getValue(0x00000800));
message.setContextId(message.getValue(0x00000002));
if (!message.isResponse()) {
message.setMessageId(message.getValue(0x00000110));
} else {
message.setReplyMessageId(message.getValue(0x00000120));
}
} else if (type == C.DATA_TYPE_DATA) {
message = new DataSetMessage(useSyntax);
message.setElementPairs(pairs);
} else {
throw 'Unrecognized message type';
}
return message;
};
DataSetMessage = function(syntax) {
DicomMessage.call(this, syntax);
this.type = C.DATA_TYPE_DATA;
};
util.inherits(DataSetMessage, DicomMessage);
DataSetMessage.prototype.is = function(type) {
return false;
};
FileMetaMessage = function(syntax) {
DicomMessage.call(this, syntax);
this.type = null;
};
util.inherits(FileMetaMessage, DicomMessage);
CommandMessage = function(syntax) {
DicomMessage.call(this, syntax);
this.type = C.DATA_TYPE_COMMAND;
this.priority = C.PRIORITY_MEDIUM;
this.dataSetPresent = true;
};
util.inherits(CommandMessage, DicomMessage);
CommandMessage.prototype.getFields = function() {
return this.command(CommandMessage.super_.prototype.getFields.call(this));
};
CommandResponse = function(syntax) {
DicomMessage.call(this, syntax);
this.type = C.DATA_TYPE_COMMAND;
this.dataSetPresent = true;
};
util.inherits(CommandResponse, DicomMessage);
CommandResponse.prototype.isResponse = function() {
return true;
};
CommandResponse.prototype.respondedTo = function() {
return this.getValue(0x00000120);
};
CommandResponse.prototype.isFinal = function() {
return this.success() || this.failure() || this.cancel();
};
CommandResponse.prototype.warning = function() {
var status = this.getStatus();
return (status == 0x0001) || (status >> 12 == 0xb);
};
CommandResponse.prototype.success = function() {
return this.getStatus() == 0x0000;
};
CommandResponse.prototype.failure = function() {
var status = this.getStatus();
return (status >> 12 == 0xa) || (status >> 12 == 0xc) || (status >> 8 == 0x1);
};
CommandResponse.prototype.cancel = function() {
return this.getStatus() == C.STATUS_CANCEL;
};
CommandResponse.prototype.pending = function() {
var status = this.getStatus();
return (status == 0xff00) || (status == 0xff01);
};
CommandResponse.prototype.getStatus = function() {
return this.getValue(0x00000900);
};
CommandResponse.prototype.setStatus = function(status) {
this.setElement(0x00000900, status);
};
// following four methods only available to C-GET-RSP and C-MOVE-RSP
CommandResponse.prototype.getNumOfRemainingSubOperations = function() {
return this.getValue(0x00001020);
};
CommandResponse.prototype.getNumOfCompletedSubOperations = function() {
return this.getValue(0x00001021);
};
CommandResponse.prototype.getNumOfFailedSubOperations = function() {
return this.getValue(0x00001022);
};
CommandResponse.prototype.getNumOfWarningSubOperations = function() {
return this.getValue(0x00001023);
};
//end
CommandResponse.prototype.getFields = function() {
return this.response(CommandResponse.super_.prototype.getFields.call(this));
};
CFindRSP = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x8020;
};
util.inherits(CFindRSP, CommandResponse);
CGetRSP = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x8010;
};
util.inherits(CGetRSP, CommandResponse);
CMoveRSP = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x8021;
};
util.inherits(CMoveRSP, CommandResponse);
CFindRQ = function(syntax) {
CommandMessage.call(this, syntax);
this.commandType = 0x20;
this.contextUID = C.SOP_STUDY_ROOT_FIND;
};
util.inherits(CFindRQ, CommandMessage);
CCancelRQ = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x0fff;
this.contextUID = null;
this.dataSetPresent = false;
};
util.inherits(CCancelRQ, CommandResponse);
CCancelMoveRQ = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x0fff;
this.contextUID = null;
this.dataSetPresent = false;
};
util.inherits(CCancelMoveRQ, CommandResponse);
CMoveRQ = function(syntax, destination) {
CommandMessage.call(this, syntax);
this.commandType = 0x21;
this.contextUID = C.SOP_STUDY_ROOT_MOVE;
this.setDestination(destination || '');
};
util.inherits(CMoveRQ, CommandMessage);
CMoveRQ.prototype.setStore = function(cstr) {
this.store = cstr;
};
CMoveRQ.prototype.setDestination = function(dest) {
this.setElement(0x00000600, dest);
};
CGetRQ = function(syntax) {
CommandMessage.call(this, syntax);
this.commandType = 0x10;
this.contextUID = C.SOP_STUDY_ROOT_GET;
this.store = null;
};
util.inherits(CGetRQ, CommandMessage);
CGetRQ.prototype.setStore = function(cstr) {
this.store = cstr;
};
CStoreRQ = function(syntax) {
CommandMessage.call(this, syntax);
this.commandType = 0x01;
this.contextUID = C.SOP_STUDY_ROOT_GET;
};
util.inherits(CStoreRQ, CommandMessage);
CStoreRQ.prototype.getOriginAETitle = function() {
return this.getValue(0x00001030);
};
CStoreRQ.prototype.getMoveMessageId = function() {
return this.getValue(0x00001031);
};
CStoreRQ.prototype.getAffectedSOPInstanceUID = function() {
return this.getValue(0x00001000);
};
CStoreRQ.prototype.setAffectedSOPInstanceUID = function(uid) {
this.setElement(0x00001000, uid);
};
CStoreRQ.prototype.setAffectedSOPClassUID = function(uid) {
this.setElement(0x00000002, uid);
};
CStoreRSP = function(syntax) {
CommandResponse.call(this, syntax);
this.commandType = 0x8001;
this.contextUID = C.SOP_STUDY_ROOT_GET;
this.dataSetPresent = false;
};
util.inherits(CStoreRSP, CommandResponse);
CStoreRSP.prototype.setAffectedSOPInstanceUID = function(uid) {
this.setElement(0x00001000, uid);
};
CStoreRSP.prototype.getAffectedSOPInstanceUID = function(uid) {
return this.getValue(0x00001000);
};

View File

@ -1,814 +0,0 @@
PDVHandle = function() {
}
util.inherits(PDVHandle, EventEmitter);
PDU = function() {
this.fields = [];
this.lengthBytes = 4;
}
PDU.prototype.length = function(fields) {
var len = 0;
fields.forEach(function(f) {
len += !f.getFields ? f.length() : f.length(f.getFields());
});
return len;
}
PDU.prototype.is = function(type) {
return this.type == type;
}
PDU.prototype.getFields = function(fields) {
var len = this.lengthField(fields);
fields.unshift(len);
if (this.type !== null) {
fields.unshift(new ReservedField());
fields.unshift(new HexField(this.type));
}
return fields;
}
PDU.prototype.lengthField = function(fields) {
if (this.lengthBytes == 4) {
return new UInt32Field(this.length(fields));
} else if (this.lengthBytes == 2) {
return new UInt16Field(this.length(fields));
} else {
throw "Invalid length bytes";
}
}
PDU.prototype.read = function(stream) {
stream.read(C.TYPE_HEX, 1);
var length = stream.read(C.TYPE_UINT32);
this.readBytes(stream, length);
}
PDU.prototype.load = function(stream) {
return PDU.createByStream(stream);
}
PDU.prototype.loadPDV = function(stream, length) {
if (stream.end()) return false;
var bytesRead = 0, pdvs = [];
while (bytesRead < length) {
var plength = stream.read(C.TYPE_UINT32),
pdv = new PresentationDataValueItem();
pdv.readBytes(stream, plength);
bytesRead += plength + 4;
pdvs.push(pdv);
}
return pdvs;
}
PDU.prototype.loadDicomMessage = function(stream, isCommand, isLast) {
var message = DicomMessage.read(stream, isCommand, isLast);
return message;
}
PDU.prototype.stream = function() {
var stream = new WriteStream(),
fields = this.getFields();
// writing to buffer
fields.forEach(function(field){
field.write(stream);
});
return stream;
}
PDU.prototype.buffer = function() {
return this.stream().buffer();
}
var interpretCommand = function(stream, isLast) {
parseDicomMessage(stream);
}
mergePDVs = function(pdvs) {
var merges = [], count = pdvs.length, i = 0;
while (i < count) {console.log(pdvs[i].isLast, pdvs[i].type);
if (!pdvs[i].isLast) {
var j = i;
while (!pdvs[j++].isLast && j < count) {
pdvs[i].messageStream.concat(pdvs[j].messageStream);
}
merges.push(pdvs[i]);
i = j;
} else {
merges.push(pdvs[i++]);
}
}
return merges;
}
PDU.splitPData = function(pdata, maxSize) {
var totalLength = pdata.totalLength();
if (totalLength > maxSize) {
//split into chunks of pdatas
var chunks = Math.floor(totalLength / maxSize), left = totalLength % maxSize;
for (var i = 0;i < chunks;i++) {
if (i == chunks - 1) {
if (left < 6) {
//need to move some of the last chunk
}
}
}
} else {
return [pdata];
}
}
var readChunk = function(fd, bufferSize, slice, callback) {
var buffer = Buffer.alloc(bufferSize), length = slice.length, start = slice.start;
fs.read(fd, buffer, 0, length, start, function(err, bytesRead) {
callback(err, bytesRead, buffer, slice);
});
}
PDU.generatePDatas = function(context, bufferOrFile, maxSize, length, metaLength, callback) {
var total, isFile = false;
if (typeof bufferOrFile == 'string') {
var stats = fs.statSync(bufferOrFile);
total = stats['size'];
isFile = true;
} else if (bufferOrFile instanceof Buffer) {
total = length ? length : bufferOrFile.length;
}
var handler = new PDVHandle();
var slices = [], start = metaLength + 144, index = 0;
maxSize -= 6;
while (start < total) {
var sliceLength = maxSize, isLast = false;
if (total - start < maxSize) {
sliceLength = total - start;
isLast = true;
}
slices.push({start : start, length : sliceLength, isLast : isLast, index : index});
start += sliceLength;
index++;
}
if (isFile) {
fs.open(bufferOrFile, 'r', function(err, fd) {
if (err) {
//fs.closeSync(fd);
return quitWithError(err, callback);
} else callback(null, handler);
var after = function(err, bytesRead, buffer, slice) {
if (err) {
fs.closeSync(fd);
handler.emit('error', err);
return;
}
var pdv = new RawDataPDV(context, buffer, 0, slice.length, slice.isLast);
handler.emit('pdv', pdv);
if (slices.length < 1) {
handler.emit('end');
fs.closeSync(fd);
} else {
var next = slices.shift();
readChunk(fd, maxSize, next, after);
}
};
var sl = slices.shift();
readChunk(fd, maxSize, sl, after);
});
} else {
for (var i = 0;i < slices.length;i++) {
var toSlice = slices[i];
var buffer = bufferOrFile.slice(toSlice.start, toSlice.length);
var pdv = new RawDataPDV(context, buffer, 0, toSlice.length, toSlice.isLast);
handler.emit('pdv', pdv);
if (i == slices.length - 1) {
handler.emit('end');
}
}
}
return;
}
PDU.typeToString = function(type) {
var pdu = null, typeNum = parseInt(type, 16);
//console.log("RECEIVED PDU-TYPE ", typeNum);
switch (typeNum) {
case 0x01 : pdu = 'ASSOCIATE-RQ'; break;
case 0x02 : pdu = 'ASSOCIATE-AC'; break;
case 0x04 : pdu = 'P-DATA-TF'; break;
case 0x06 : pdu = 'RELEASE-RP'; break;
case 0x07 : pdu = 'ASSOCIATE-ABORT'; break;
case 0x10 : pdu = 'APPLICATION-CONTEXT-ITEM'; break;
case 0x20 : pdu = 'PRESENTATION-CONTEXT-ITEM'; break;
case 0x21 : pdu = 'PRESENTATION-CONTEXT-ITEM-AC'; break;
case 0x30 : pdu = 'ABSTRACT-SYNTAX-ITEM'; break;
case 0x40 : pdu = 'TRANSFER-SYNTAX-ITEM'; break;
case 0x50 : pdu = 'USER-INFORMATION-ITEM'; break;
case 0x51 : pdu = 'MAXIMUM-LENGTH-ITEM'; break;
case 0x52 : pdu = 'IMPLEMENTATION-CLASS-UID-ITEM'; break;
case 0x55 : pdu = 'IMPLEMENTATION-VERSION-NAME-ITEM'; break;
default : break;
}
return pdu;
}
PDU.createByStream = function(stream) {
if (stream.end()) return null;
var pduType = stream.read(C.TYPE_HEX, 1), typeNum = parseInt(pduType, 16), pdu = null;
//console.log("RECEIVED PDU-TYPE ", pduType);
switch (typeNum) {
case 0x01 : pdu = new AssociateRQ(); break;
case 0x02 : pdu = new AssociateAC(); break;
case 0x04 : pdu = new PDataTF(); break;
case 0x06 : pdu = new ReleaseRP(); break;
case 0x07 : pdu = new AssociateAbort(); break;
case 0x10 : pdu = new ApplicationContextItem(); break;
case 0x20 : pdu = new PresentationContextItem(); break;
case 0x21 : pdu = new PresentationContextItemAC(); break;
case 0x30 : pdu = new AbstractSyntaxItem(); break;
case 0x40 : pdu = new TransferSyntaxItem(); break;
case 0x50 : pdu = new UserInformationItem(); break;
case 0x51 : pdu = new MaximumLengthItem(); break;
case 0x52 : pdu = new ImplementationClassUIDItem(); break;
case 0x55 : pdu = new ImplementationVersionNameItem(); break;
default : throw "Unrecoginized pdu type " + pduType; break;
}
if (pdu)
pdu.read(stream);
return pdu;
}
var nextItemIs = function(stream, pduType) {
if (stream.end()) return false;
var nextType = stream.read(C.TYPE_HEX, 1);
stream.increment(-1);
return pduType == nextType;
}
AssociateRQ = function() {
PDU.call(this);
this.type = C.ITEM_TYPE_PDU_ASSOCIATE_RQ;
this.protocolVersion = 1;
}
util.inherits(AssociateRQ, PDU);
AssociateRQ.prototype.setProtocolVersion = function(version) {
this.protocolVersion = version;
}
AssociateRQ.prototype.setCalledAETitle = function(title) {
this.calledAETitle = title;
}
AssociateRQ.prototype.setCallingAETitle = function(title) {
this.callingAETitle = title;
}
AssociateRQ.prototype.setApplicationContextItem = function(item) {
this.applicationContextItem = item;
}
AssociateRQ.prototype.setPresentationContextItems = function(items) {
this.presentationContextItems = items;
}
AssociateRQ.prototype.setUserInformationItem = function(item) {
this.userInformationItem = item;
}
AssociateRQ.prototype.allAccepted = function() {
for (var i in this.presentationContextItems) {
var item = this.presentationContextItems[i];
if (!item.accepted()) return false;
}
return true;
}
AssociateRQ.prototype.getFields = function() {
var f = [
new UInt16Field(this.protocolVersion), new ReservedField(2),
new FilledField(this.calledAETitle, 16), new FilledField(this.callingAETitle, 16),
new ReservedField(32), this.applicationContextItem
];
this.presentationContextItems.forEach(function(context){
f.push(context);
});
f.push(this.userInformationItem);
return AssociateRQ.super_.prototype.getFields.call(this, f);
}
AssociateRQ.prototype.readBytes = function(stream, length) {
this.type = C.ITEM_TYPE_PDU_ASSOCIATE_RQ;
var version = stream.read(C.TYPE_UINT16);
this.setProtocolVersion(version);
stream.increment(2);
var calledAE = stream.read(C.TYPE_ASCII, 16);
this.setCalledAETitle(calledAE);
var callingAE = stream.read(C.TYPE_ASCII, 16);
this.setCallingAETitle(callingAE);
stream.increment(32);
var appContext = this.load(stream);
this.setApplicationContextItem(appContext);
var presContexts = [];
do {
presContexts.push(this.load(stream));
} while (nextItemIs(stream, C.ITEM_TYPE_PRESENTATION_CONTEXT));
this.setPresentationContextItems(presContexts);
var userItem = this.load(stream);
this.setUserInformationItem(userItem);
}
AssociateRQ.prototype.buffer = function() {
return AssociateRQ.super_.prototype.buffer.call(this);
}
AssociateAC = function() {
AssociateRQ.call(this);
};
util.inherits(AssociateAC, AssociateRQ);
AssociateAC.prototype.readBytes = function(stream, length) {
this.type = C.ITEM_TYPE_PDU_ASSOCIATE_AC;
var version = stream.read(C.TYPE_UINT16);
this.setProtocolVersion(version);
stream.increment(66);
var appContext = this.load(stream);
this.setApplicationContextItem(appContext);
var presContexts = [];
do {
presContexts.push(this.load(stream));
} while (nextItemIs(stream, C.ITEM_TYPE_PRESENTATION_CONTEXT_AC));
this.setPresentationContextItems(presContexts);
var userItem = this.load(stream);
this.setUserInformationItem(userItem);
}
AssociateAC.prototype.getMaxSize = function() {
var items = this.userInformationItem.userDataItems, length = items.length, size = null;
for (var i = 0;i < length;i++) {
if (items[i].is(C.ITEM_TYPE_MAXIMUM_LENGTH)) {
size = items[i].maximumLengthReceived;
break;
}
}
return size;
}
AssociateAbort = function() {
this.type = C.ITEM_TYPE_PDU_AABORT;
this.source = 1;
this.reason = 0;
PDU.call(this);
}
util.inherits(AssociateAbort, PDU);
AssociateAbort.prototype.setSource = function(src) {
this.source = src;
}
AssociateAbort.prototype.setReason = function(reason) {
this.reason = reason;
}
AssociateAbort.prototype.readBytes = function(stream, length) {
stream.increment(2);
var source = stream.read(C.TYPE_UINT8);
this.setSource(source);
var reason = stream.read(C.TYPE_UINT8);
this.setReason(reason);
}
AssociateAbort.prototype.getFields = function() {
return AssociateAbort.super_.prototype.getFields.call(this, [
new ReservedField(), new ReservedField(),
new UInt8Field(this.source), new UInt8Field(this.reason)
]);
}
ReleaseRQ = function() {
this.type = C.ITEM_TYPE_PDU_RELEASE_RQ;
PDU.call(this);
};
util.inherits(ReleaseRQ, PDU);
ReleaseRQ.prototype.getFields = function() {
return ReleaseRQ.super_.prototype.getFields.call(this, [new ReservedField(4)]);
};
ReleaseRP = function() {
this.type = C.ITEM_TYPE_PDU_RELEASE_RP;
PDU.call(this);
}
util.inherits(ReleaseRP, PDU);
ReleaseRP.prototype.readBytes = function(stream, length) {
stream.increment(4);
};
ReleaseRP.prototype.getFields = function() {
return ReleaseRP.super_.prototype.getFields.call(this, [new ReservedField(4)]);
}
PDataTF = function() {
this.type = C.ITEM_TYPE_PDU_PDATA;
this.presentationDataValueItems = [];
PDU.call(this);
}
util.inherits(PDataTF, PDU);
PDataTF.prototype.setPresentationDataValueItems = function(items) {
this.presentationDataValueItems = items ? items : [];
}
PDataTF.prototype.getFields = function() {
var fields = this.presentationDataValueItems;
return PDataTF.super_.prototype.getFields.call(this, fields);
}
PDataTF.prototype.totalLength = function() {
var fields = this.presentationDataValueItems;
return this.length(fields);
}
PDataTF.prototype.readBytes = function(stream, length) {
var pdvs = this.loadPDV(stream, length);
//let merges = mergePDVs(pdvs);
this.setPresentationDataValueItems(pdvs);
}
Item = function() {
PDU.call(this);
this.lengthBytes = 2;
};
util.inherits(Item, PDU);
Item.prototype.read = function(stream) {
stream.read(C.TYPE_HEX, 1);
var length = stream.read(C.TYPE_UINT16);
this.readBytes(stream, length);
}
Item.prototype.write = function(stream) {
stream.concat(this.stream());
}
Item.prototype.getFields = function(fields) {
return Item.super_.prototype.getFields.call(this, fields);
}
PresentationDataValueItem = function(context) {
this.type = null;
this.isLast = true;
this.dataFragment = null;
this.contextId = context;
this.messageStream = null;
Item.call(this);
this.lengthBytes = 4;
};
util.inherits(PresentationDataValueItem, Item);
PresentationDataValueItem.prototype.setContextId = function(id) {
this.contextId = id;
}
PresentationDataValueItem.prototype.setFlag = function(flag) {
this.flag = flag;
}
PresentationDataValueItem.prototype.setPresentationDataValue = function(pdv) {
this.pdv = pdv;
}
PresentationDataValueItem.prototype.setMessage = function(msg) {
this.dataFragment = msg;
}
PresentationDataValueItem.prototype.getMessage = function() {
return this.dataFragment;
}
PresentationDataValueItem.prototype.readBytes = function(stream, length) {
this.contextId = stream.read(C.TYPE_UINT8);
var messageHeader = stream.read(C.TYPE_UINT8);
this.isLast = messageHeader >> 1;
this.type = messageHeader & 1 ? C.DATA_TYPE_COMMAND : C.DATA_TYPE_DATA;
//load dicom messages
this.messageStream = stream.more(length - 2);
}
PresentationDataValueItem.prototype.getFields = function() {
var fields = [new UInt8Field(this.contextId)];
//define header
var messageHeader = (1 & this.dataFragment.type) | ((this.isLast ? 1 : 0) << 1);
fields.push(new UInt8Field(messageHeader));
fields.push(this.dataFragment);
return PresentationDataValueItem.super_.prototype.getFields.call(this, fields);
}
RawDataPDV = function(context, buffer, start, length, isLast) {
this.type = null;
this.isLast = isLast;
this.dataFragmentBuffer = buffer;
this.bufferStart = start;
this.bufferLength = length;
this.contextId = context;
Item.call(this);
this.lengthBytes = 4;
};
util.inherits(RawDataPDV, Item);
RawDataPDV.prototype.getFields = function() {
var fields = [new UInt8Field(this.contextId)];
var messageHeader = (this.isLast ? 1 : 0) << 1;
fields.push(new UInt8Field(messageHeader));
fields.push(new BufferField(this.dataFragmentBuffer, this.bufferStart, this.bufferLength));
return RawDataPDV.super_.prototype.getFields.call(this, fields);
}
ApplicationContextItem = function() {
this.type = C.ITEM_TYPE_APPLICATION_CONTEXT;
this.applicationContextName = C.APPLICATION_CONTEXT_NAME;
Item.call(this);
}
util.inherits(ApplicationContextItem, Item);
ApplicationContextItem.prototype.setApplicationContextName = function(name) {
this.applicationContextName = name;
}
ApplicationContextItem.prototype.getFields = function() {
return ApplicationContextItem.super_.prototype.getFields.call(this, [new StringField(this.applicationContextName)]);
}
ApplicationContextItem.prototype.readBytes = function(stream, length) {
var appContext = stream.read(C.TYPE_ASCII, length);
this.setApplicationContextName(appContext);
}
ApplicationContextItem.prototype.buffer = function() {
return ApplicationContextItem.super_.prototype.buffer.call(this);
}
PresentationContextItem = function() {
this.type = C.ITEM_TYPE_PRESENTATION_CONTEXT;
Item.call(this);
};
util.inherits(PresentationContextItem, Item);
PresentationContextItem.prototype.setPresentationContextID = function(id) {
this.presentationContextID = id;
}
PresentationContextItem.prototype.setAbstractSyntaxItem = function(item) {
this.abstractSyntaxItem = item;
}
PresentationContextItem.prototype.setTransferSyntaxesItems = function(items) {
this.transferSyntaxesItems = items;
}
PresentationContextItem.prototype.setResultReason = function(reason) {
this.resultReason = reason;
}
PresentationContextItem.prototype.accepted = function() {
return this.resultReason == 0;
}
PresentationContextItem.prototype.readBytes = function(stream, length) {
var contextId = stream.read(C.TYPE_UINT8);
this.setPresentationContextID(contextId);
stream.increment(1);
stream.increment(1);
stream.increment(1);
var abstractItem = this.load(stream);
this.setAbstractSyntaxItem(abstractItem);
var transContexts = [];
do {
transContexts.push(this.load(stream));
} while (nextItemIs(stream, C.ITEM_TYPE_TRANSFER_CONTEXT));
this.setTransferSyntaxesItems(transContexts);
}
PresentationContextItem.prototype.getFields = function() {
var f = [
new UInt8Field(this.presentationContextID),
new ReservedField(), new ReservedField(), new ReservedField(), this.abstractSyntaxItem
];
this.transferSyntaxesItems.forEach(function(syntaxItem){
f.push(syntaxItem);
});
return PresentationContextItem.super_.prototype.getFields.call(this, f);
}
PresentationContextItem.prototype.buffer = function() {
return PresentationContextItem.super_.prototype.buffer.call(this);
}
PresentationContextItemAC = function() {
this.type = C.ITEM_TYPE_PRESENTATION_CONTEXT_AC;
Item.call(this);
};
util.inherits(PresentationContextItemAC, PresentationContextItem);
PresentationContextItemAC.prototype.readBytes = function(stream, length) {
var contextId = stream.read(C.TYPE_UINT8);
this.setPresentationContextID(contextId);
stream.increment(1);
var resultReason = stream.read(C.TYPE_UINT8);
this.setResultReason(resultReason);
stream.increment(1);
var transItem = this.load(stream);
this.setTransferSyntaxesItems([transItem]);
}
AbstractSyntaxItem = function() {
this.type = C.ITEM_TYPE_ABSTRACT_CONTEXT;
Item.call(this);
}
util.inherits(AbstractSyntaxItem, Item);
AbstractSyntaxItem.prototype.setAbstractSyntaxName = function(name) {
this.abstractSyntaxName = name;
}
AbstractSyntaxItem.prototype.getFields = function() {
return AbstractSyntaxItem.super_.prototype.getFields.call(this, [new StringField(this.abstractSyntaxName)]);
}
AbstractSyntaxItem.prototype.buffer = function() {
return AbstractSyntaxItem.super_.prototype.buffer.call(this);
}
AbstractSyntaxItem.prototype.readBytes = function(stream, length) {
var name = stream.read(C.TYPE_ASCII, length);
this.setAbstractSyntaxName(name);
}
TransferSyntaxItem = function() {
this.type = C.ITEM_TYPE_TRANSFER_CONTEXT;
Item.call(this);
};
util.inherits(TransferSyntaxItem, Item);
TransferSyntaxItem.prototype.setTransferSyntaxName = function(name) {
this.transferSyntaxName = name;
}
TransferSyntaxItem.prototype.readBytes = function(stream, length) {
var transfer = stream.read(C.TYPE_ASCII, length);
this.setTransferSyntaxName(transfer);
}
TransferSyntaxItem.prototype.getFields = function() {
return TransferSyntaxItem.super_.prototype.getFields.call(this, [new StringField(this.transferSyntaxName)]);
}
TransferSyntaxItem.prototype.buffer = function() {
return TransferSyntaxItem.super_.prototype.buffer.call(this);
}
UserInformationItem = function() {
this.type = C.ITEM_TYPE_USER_INFORMATION;
Item.call(this);
};
util.inherits(UserInformationItem, Item);
UserInformationItem.prototype.setUserDataItems = function(items) {
this.userDataItems = items;
}
UserInformationItem.prototype.readBytes = function(stream, length) {
var items = [], pdu = this.load(stream);
do {
items.push(pdu);
} while (pdu = this.load(stream));
this.setUserDataItems(items);
}
UserInformationItem.prototype.getFields = function() {
var f = [];
this.userDataItems.forEach(function(userData){
f.push(userData);
});
return UserInformationItem.super_.prototype.getFields.call(this, f);
}
UserInformationItem.prototype.buffer = function() {
return UserInformationItem.super_.prototype.buffer.call(this);
}
ImplementationClassUIDItem = function() {
this.type = C.ITEM_TYPE_IMPLEMENTATION_UID;
Item.call(this);
}
util.inherits(ImplementationClassUIDItem, Item);
ImplementationClassUIDItem.prototype.setImplementationClassUID = function(id) {
this.implementationClassUID = id;
}
ImplementationClassUIDItem.prototype.readBytes = function(stream, length) {
var uid = stream.read(C.TYPE_ASCII, length);
this.setImplementationClassUID(uid);
}
ImplementationClassUIDItem.prototype.getFields = function() {
return ImplementationClassUIDItem.super_.prototype.getFields.call(this, [new StringField(this.implementationClassUID)]);
}
ImplementationClassUIDItem.prototype.buffer = function() {
return ImplementationClassUIDItem.super_.prototype.buffer.call(this);
}
ImplementationVersionNameItem = function() {
this.type = C.ITEM_TYPE_IMPLEMENTATION_VERSION;
Item.call(this);
}
util.inherits(ImplementationVersionNameItem, Item);
ImplementationVersionNameItem.prototype.setImplementationVersionName = function(name) {
this.implementationVersionName = name;
}
ImplementationVersionNameItem.prototype.readBytes = function(stream, length) {
var name = stream.read(C.TYPE_ASCII, length);
this.setImplementationVersionName(name);
}
ImplementationVersionNameItem.prototype.getFields = function() {
return ImplementationVersionNameItem.super_.prototype.getFields.call(this, [new StringField(this.implementationVersionName)]);
}
ImplementationVersionNameItem.prototype.buffer = function() {
return ImplementationVersionNameItem.super_.prototype.buffer.call(this);
}
MaximumLengthItem = function() {
this.type = C.ITEM_TYPE_MAXIMUM_LENGTH;
this.maximumLengthReceived = 32768;
Item.call(this);
}
util.inherits(MaximumLengthItem, Item);
MaximumLengthItem.prototype.setMaximumLengthReceived = function(length) {
this.maximumLengthReceived = length;
}
MaximumLengthItem.prototype.readBytes = function(stream, length) {
var l = stream.read(C.TYPE_UINT32);
this.setMaximumLengthReceived(l);
}
MaximumLengthItem.prototype.getFields = function() {
return MaximumLengthItem.super_.prototype.getFields.call(this, [new UInt32Field(this.maximumLengthReceived)]);
}
MaximumLengthItem.prototype.buffer = function() {
return MaximumLengthItem.super_.prototype.buffer.call(this);
}

View File

@ -1,239 +0,0 @@
var isString = function(type) {
if (type === C.TYPE_ASCII || type === C.TYPE_HEX) {
return true;
} else {
return false;
}
};
calcLength = function(type, value) {
var size = NaN;
switch (type) {
case C.TYPE_HEX : size = Buffer.byteLength(value, 'hex'); break;
case C.TYPE_ASCII : size = Buffer.byteLength(value, 'ascii'); break;
case C.TYPE_UINT8 : size = 1; break;
case C.TYPE_UINT16 : size = 2; break;
case C.TYPE_UINT32 : size = 4; break;
case C.TYPE_FLOAT : size = 4; break;
case C.TYPE_DOUBLE : size = 8; break;
case C.TYPE_INT8 : size = 1; break;
case C.TYPE_INT16 : size = 2; break;
case C.TYPE_INT32 : size = 4; break;
default :break;
}
return size;
};
var RWStream = function() {
this.endian = C.BIG_ENDIAN;
};
RWStream.prototype.setEndian = function(endian) {
this.endian = endian;
};
RWStream.prototype.getEncoding = function(type) {
return RWStream.encodings[type];
};
RWStream.prototype.getWriteType = function(type) {
return RWStream.writes[this.endian][type];
};
RWStream.prototype.getReadType = function(type) {
return RWStream.reads[this.endian][type];
};
WriteStream = function() {
RWStream.call(this);
this.defaultBufferSize = 512; //512 bytes
this.rawBuffer = Buffer.alloc(this.defaultBufferSize);
this.offset = 0;
this.contentSize = 0;
};
util.inherits(WriteStream, RWStream);
WriteStream.prototype.increment = function(add) {
this.offset += add;
if (this.offset > this.contentSize) {
this.contentSize = this.offset;
}
};
WriteStream.prototype.size = function() {
return this.contentSize;
};
WriteStream.prototype.skip = function(amount) {
this.increment(amount);
};
WriteStream.prototype.checkSize = function(length) {
if (this.offset + length > this.rawBuffer.length) {
// we need more size, copying old one to new buffer
var oldLength = this.rawBuffer.length,
newBuffer = Buffer.alloc(oldLength + length + (oldLength / 2));
this.rawBuffer.copy(newBuffer, 0, 0, this.contentSize);
this.rawBuffer = newBuffer;
}
};
WriteStream.prototype.writeToBuffer = function(type, value, length) {
if (value === '' || value === null) return;
this.checkSize(length);
this.rawBuffer[this.getWriteType(type)](value, this.offset);
this.increment(length);
};
WriteStream.prototype.writeRawBuffer = function(source, start, length) {
if (!source) return;
this.checkSize(length);
source.copy(this.rawBuffer, this.offset, start, length);
this.increment(length);
};
WriteStream.prototype.write = function(type, value) {
if (isString(type)) {
this.writeString(value, type);
} else {
this.writeToBuffer(type, value, calcLength(type));
}
};
WriteStream.prototype.writeString = function(string, type) {
var encoding = this.getEncoding(type),
length = Buffer.byteLength(string, encoding);
this.rawBuffer.write(string, this.offset, length, encoding);
this.increment(length);
};
WriteStream.prototype.buffer = function() {
return this.rawBuffer.slice(0, this.contentSize);
};
WriteStream.prototype.toReadBuffer = function() {
return new ReadStream(this.buffer());
};
WriteStream.prototype.concat = function(newStream) {
var newSize = this.size() + newStream.size();
this.rawBuffer = Buffer.concat([this.buffer(), newStream.buffer()], newSize);
this.contentSize = newSize;
this.offset = newSize;
};
ReadStream = function(buffer) {
RWStream.call(this);
this.rawBuffer = buffer;
this.offset = 0;
};
util.inherits(ReadStream, RWStream);
ReadStream.prototype.size = function() {
return this.rawBuffer.length;
};
ReadStream.prototype.increment = function(add) {
this.offset += add;
};
ReadStream.prototype.more = function(length) {
var newBuf = this.rawBuffer.slice(this.offset, this.offset + length);
this.increment(length);
return new ReadStream(newBuf);
};
ReadStream.prototype.reset = function() {
this.offset = 0;
return this;
};
ReadStream.prototype.end = function() {
return this.offset >= this.size();
};
ReadStream.prototype.readFromBuffer = function(type, length) {
//this.checkSize(length);
//if (this.offset + length > this.rawBuffer.length) throw ("out of bound " + this.offset + "," + length + "," + this.rawBuffer.length);
var value = this.rawBuffer[this.getReadType(type)](this.offset);
this.increment(length);
return value;
};
ReadStream.prototype.read = function(type, length) {
var value = null;
if (isString(type)) {
value = this.readString(length, type);
} else {
value = this.readFromBuffer(type, calcLength(type));
}
return value;
};
ReadStream.prototype.readString = function(length, type) {
var encoding = this.getEncoding(type),
str = this.rawBuffer.toString(encoding, this.offset, this.offset + length);
this.increment(length);
return str;
};
ReadStream.prototype.buffer = function() {
return this.rawBuffer;
};
ReadStream.prototype.concat = function(newStream) {
var newSize = this.size() + newStream.size();
this.rawBuffer = Buffer.concat([this.buffer(), newStream.buffer()], newSize);
this.contentSize = newSize;
this.offset = newSize;
};
RWStream.writes = {};
RWStream.writes[C.BIG_ENDIAN] = {};
RWStream.writes[C.BIG_ENDIAN][C.TYPE_UINT8] = 'writeUInt8';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_UINT16] = 'writeUInt16BE';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_UINT32] = 'writeUInt32BE';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_INT8] = 'writeInt8';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_INT16] = 'writeInt16BE';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_INT32] = 'writeInt32BE';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_FLOAT] = 'writeFloatBE';
RWStream.writes[C.BIG_ENDIAN][C.TYPE_DOUBLE] = 'writeDoubleBE';
RWStream.writes[C.LITTLE_ENDIAN] = {};
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_UINT8] = 'writeUInt8';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_UINT16] = 'writeUInt16LE';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_UINT32] = 'writeUInt32LE';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_INT8] = 'writeInt8';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_INT16] = 'writeInt16LE';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_INT32] = 'writeInt32LE';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_FLOAT] = 'writeFloatLE';
RWStream.writes[C.LITTLE_ENDIAN][C.TYPE_DOUBLE] = 'writeDoubleLE';
RWStream.reads = {};
RWStream.reads[C.BIG_ENDIAN] = {};
RWStream.reads[C.BIG_ENDIAN][C.TYPE_UINT8] = 'readUInt8';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_UINT16] = 'readUInt16BE';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_UINT32] = 'readUInt32BE';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_INT8] = 'readInt8';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_INT16] = 'readInt16BE';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_INT32] = 'readInt32BE';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_FLOAT] = 'readFloatBE';
RWStream.reads[C.BIG_ENDIAN][C.TYPE_DOUBLE] = 'readDoubleBE';
RWStream.reads[C.LITTLE_ENDIAN] = {};
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_UINT8] = 'readUInt8';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_UINT16] = 'readUInt16LE';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_UINT32] = 'readUInt32LE';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_INT8] = 'readInt8';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_INT16] = 'readInt16LE';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_INT32] = 'readInt32LE';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_FLOAT] = 'readFloatLE';
RWStream.reads[C.LITTLE_ENDIAN][C.TYPE_DOUBLE] = 'readDoubleLE';
RWStream.encodings = {};
RWStream.encodings[C.TYPE_HEX] = 'hex';
RWStream.encodings[C.TYPE_ASCII] = 'ascii';

View File

@ -1,100 +0,0 @@
C = {
IMPLEM_UID : "1.2.840.0.1.3680045.8.641",
IMPLEM_VERSION : "OHIF-DCM-0.1",
DEFAULT_MAX_PACKAGE_SIZE : 32768,
APPLICATION_CONTEXT_NAME : "1.2.840.10008.3.1.1.1",
PROTOCOL_VERSION : "0001",
ITEM_TYPE_RESERVED : "00",
ITEM_TYPE_APPLICATION_CONTEXT : "10",
ITEM_TYPE_PDU_ASSOCIATE_RQ : "01",
ITEM_TYPE_PDU_ASSOCIATE_AC : "02",
ITEM_TYPE_PDU_PDATA : "04",
ITEM_TYPE_PDU_RELEASE_RQ : "05",
ITEM_TYPE_PDU_RELEASE_RP : "06",
ITEM_TYPE_PDU_AABORT : "07",
ITEM_TYPE_PRESENTATION_CONTEXT : "20",
ITEM_TYPE_PRESENTATION_CONTEXT_AC : "21",
ITEM_TYPE_ABSTRACT_CONTEXT : "30",
ITEM_TYPE_TRANSFER_CONTEXT : "40",
ITEM_TYPE_USER_INFORMATION : "50",
ITEM_TYPE_MAXIMUM_LENGTH : "51",
ITEM_TYPE_IMPLEMENTATION_UID : "52",
ITEM_TYPE_IMPLEMENTATION_VERSION : "55",
IMPLICIT_LITTLE_ENDIAN : "1.2.840.10008.1.2",
EXPLICIT_LITTLE_ENDIAN : "1.2.840.10008.1.2.1",
EXPLICIT_BIG_ENDIAN : "1.2.840.10008.1.2.2",
SOP_PATIENT_ROOT_FIND : "1.2.840.10008.5.1.4.1.2.1.1",
SOP_PATIENT_ROOT_MOVE : "1.2.840.10008.5.1.4.1.2.1.2",
SOP_PATIENT_ROOT_GET : "1.2.840.10008.5.1.4.1.2.1.3",
SOP_STUDY_ROOT_FIND : "1.2.840.10008.5.1.4.1.2.2.1",
SOP_STUDY_ROOT_MOVE : "1.2.840.10008.5.1.4.1.2.2.2",
SOP_STUDY_ROOT_GET : "1.2.840.10008.5.1.4.1.2.2.3",
SOP_VERIFICATION : "1.2.840.10008.1.1",
SOP_HANGING_PROTOCOL_FIND : "1.2.840.10008.5.1.4.38.2",
SOP_MR_IMAGE_STORAGE : "1.2.840.10008.5.1.4.1.1.4",
TYPE_ASCII : 1,
TYPE_HEX : 2,
TYPE_UINT8 : 3,
TYPE_UINT16 : 4,
TYPE_UINT32 : 5,
TYPE_COMPOSITE : 6,
TYPE_FLOAT : 7,
TYPE_DOUBLE : 8,
TYPE_INT8 : 9,
TYPE_INT16 : 10,
TYPE_INT32 : 11,
TYPE_BUFFER : 12,
RESULT_REASON_ACCEPTANCE : 0,
RESULT_REASON_USER_REJECTION : 1,
RESULT_REASON_NO_REASON :2,
RESULT_REASON_ABSTRACT_NOT_SUPPORTED : 3,
RESULT_REASON_TRANSFER_NOT_SUPPORTED : 4,
DEFAULT_MESSAGE_ID : 1,
LITTLE_ENDIAN : 1,
BIG_ENDIAN : 2,
VM_SINGLE :1,
VM_TWO : 3,
VM_THREE : 4,
VM_FOUR : 5,
VM_1N : 6,
VM_2N :7,
VM_3N :8,
VM_6N :9,
VM_3_3N : 10,
VM_2_2N : 11,
VM_16 : 12,
VM_1_2 : 13,
VM_1_3 : 18,
VM_SIX : 14,
VM_NINE : 15,
VM_1_32 : 16,
VM_1_99 : 17,
PRIORITY_LOW : 0x2,
PRIORITY_MEDIUM : 0x0,
PRIORITY_HIGH : 0x1,
DATA_SET_PRESENT : 1,
DATE_SET_ABSENCE : 0x0101,
DATA_TYPE_COMMAND : 1,
DATA_TYPE_DATA : 0,
DATA_IS_LAST : 1,
DATA_NOT_LAST : 0,
SOURCE_SERVICE_USER : 0,
SOURCE_SERVICE_PROVIDER : 2,
QUERY_RETRIEVE_LEVEL_PATIENT : "PATIENT",
QUERY_RETRIEVE_LEVEL_STUDY : "STUDY",
QUERY_RETRIEVE_LEVEL_SERIES : "SERIES",
QUERY_RETRIEVE_LEVEL_IMAGE : "IMAGE",
VALUE_LENGTH_UNDEFINED : 0xffffffff,
STATUS_SUCCESS : 0x0000,
STATUS_CANCEL : 0xfe00,
STATUS_CFIND_CONT_OK : 0xff00,
STATUS_CFIND_CONT_WARN : 0xff01,
COMMAND_C_GET_RSP : 0x8010,
COMMAND_C_MOVE_RSP : 0x8021,
COMMAND_C_GET_RQ : 0x10,
COMMAND_C_STORE_RQ : 0x01,
COMMAND_C_FIND_RSP : 0x8020,
COMMAND_C_MOVE_RQ : 0x21,
COMMAND_C_FIND_RQ : 0x20,
COMMAND_C_STORE_RSP : 0x8001
};

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
util = Npm.require("util");
fs = Npm.require('fs');
EventEmitter = Npm.require('events').EventEmitter;
quitWithError = function(message, callback) {
return callback(new Error(message), null);
};

View File

@ -1,22 +0,0 @@
Package.describe({
name: 'ohif:dicomweb-client',
summary: 'DICOM Services: DICOMWeb',
version: '0.0.1'
});
Npm.depends({
'url-parse': '1.4.1',
'isomorphic-fetch': '2.2.1',
'isomorphic-base64': '1.0.2'
});
Package.onUse(function(api) {
api.versionsFrom('1.6');
api.use('ecmascript');
// DICOMWeb functions
api.mainModule('src/index.js');
api.export('DICOMWeb');
});

View File

@ -1,33 +0,0 @@
import makeRequest from "./makeRequest";
/**
* Make a request to the URL given a set of options.
* This function will add optional timing, request, and respone logging.
*
* @param {String} url
* @param {Object} options
* @return {Promise<*>}
*/
const get = async function get(url, options) {
if (options.logRequests) {
console.log(url);
}
if (options.logTiming) {
console.time(url);
}
const result = await makeRequest(url, options);
if (options.logTiming) {
console.timeEnd(url);
}
if (options.logResponses) {
console.info(result);
}
return result;
}
export default get;

View File

@ -1,14 +0,0 @@
import { OHIF } from 'meteor/ohif:core';
export default function getAccessToken() {
if (!global.window || !window.sessionStorage || !sessionStorage) {
return;
}
const userAccessToken = OHIF.user.getAccessToken();
if (userAccessToken) {
return userAccessToken;
}
return sessionStorage.token;
}

View File

@ -1,133 +0,0 @@
import get from './get.js';
const ASCII = 'ascii';
function getMultipartContentInfo(headers) {
const multipartRegex = /^\s*multipart\/[^;]+/g;
const contentType = headers.get('content-type');
let dict = null;
if (typeof contentType === 'string' && multipartRegex.test(contentType)) {
let match;
let pairRegex = /;\s*([^=]+)=([^;\r\n]+)/g;
pairRegex.lastIndex = multipartRegex.lastIndex;
while ((match = pairRegex.exec(contentType)) !== null) {
let key = match[1]
let value = match[2];
if (dict === null) {
dict = {};
}
dict[key] = value;
}
}
return dict;
}
function parseContentHeader(data, offset) {
const endOfHeader = data.indexOf('\r\n\r\n', offset);
if (endOfHeader < 0 || endOfHeader <= offset || endOfHeader > data.length) {
throw new Error('End of content header cannot be determined...');
}
const header = {
start: offset,
end: endOfHeader + 4,
fields: {}
};
const headerRegex = /([\w\-]+):\s*([^\r\n]+)(?:\r\n)?/g;
const headerContentRegex = /\t([^\r\n]+)(?:\r\n)?/g;
const headerString = data.slice(offset, endOfHeader);
let match;
while ((match = headerRegex.exec(headerString)) !== null) {
const key = match[1].toLowerCase(), value = match[2];
while (headerString.charAt(headerRegex.lastIndex) === '\t') {
headerContentRegex.lastIndex = headerRegex.lastIndex;
if ((match = headerContentRegex.exec(headerString)) !== null) {
headerRegex.lastIndex = headerContentRegex.lastIndex;
value += ' ' + match[1];
continue;
}
break;
}
header.fields[key] = value;
}
return header;
}
function toBytes(input) {
const data = [];
for (let i = 0; i < input.length; i++){
data.push(input.charCodeAt(i));
}
return data;
}
function parseResponse(headers, data) {
const contentInfo = getMultipartContentInfo(headers);
if (!contentInfo || !contentInfo.boundary) {
throw new Error('Content boundary not specified...');
}
const boundary = contentInfo.boundary;
const delimiter = '--' + boundary + '\r\n';
let index = data.indexOf(delimiter, 0, ASCII);
if (index < 0) {
throw new Error('DICOMWeb: The specified boundary could not be found...');
}
let closingIndex
let closingDelimiter = '\r\n--' + boundary + '--';
index += delimiter.length;
if (data[index] !== 0x0D || data[index + 1] !== 0x0A) {
// multipart content headers are present, so let's parse them...
let contentHeader = parseContentHeader(data, index);
if (contentHeader && contentHeader.end > index) {
if (contentHeader.fields['content-length'] > 0) {
let endOfData = contentHeader.end + parseInt(contentHeader.fields['content-length'], 10);
if (endOfData === data.indexOf(closingDelimiter, endOfData)) {
// content-length is valid...
return data.slice(contentHeader.end, endOfData);
}
}
index = contentHeader.end;
}
} else {
// no headers, the content comes right after...
index += 2;
}
closingIndex = data.indexOf(closingDelimiter, index);
if (closingIndex < 0 || closingIndex < index) {
throw new Error('DICOMWeb: The end of the content could not be determined...')
}
return toBytes(data.slice(index, closingIndex));
}
const getBulkData = async function(url, options = {}) {
options.headers = options.headers || {};
options.headers.Accept = 'multipart/related; type=application/octet-stream';
const response = await get(url, options);
const data = await response.text();
return parseResponse(response.headers, data);
}
export default getBulkData;

View File

@ -1,16 +0,0 @@
import get from './get.js';
import getAttribute from "./getAttribute";
const getJSON = async function (url, options) {
options.headers = options.headers || {};
options.headers.Accept = 'application/json';
return get(url, options).then(response => {
if (!(response instanceof Response)) {
return '';
}
return response.json();
});
};
export default getJSON;

View File

@ -1,69 +0,0 @@
import { Meteor } from "meteor/meteor";
import URL from 'url-parse';
import 'isomorphic-fetch';
import { btoa } from 'isomorphic-base64';
import getAccessToken from './getAccessToken.js';
async function makeRequest(url, options) {
const parsed = new URL(url);
let requestOpt = {
method: 'GET',
headers: {}
};
const accessToken = getAccessToken();
if (accessToken) {
requestOpt.headers = {
Authorization: `Bearer ${accessToken}`
};
} else if (options.auth) {
requestOpt.headers = {
Authorization: `Basic ${btoa(options.auth)}`
};
}
if (options.headers) {
Object.keys(options.headers).forEach(key => {
requestOpt.headers[key] = options.headers[key];
});
}
if(options.method) {
requestOpt.method = options.method;
}
if (options.method === 'POST' && options.body) {
requestOpt.body = options.body;
}
return new Promise((resolve, reject) => {
// TODO: Kept getting weird build errors from RegExp
const isAbsolute = parsed.href.indexOf('http://') === 0 || parsed.href.indexOf('https://') === 0;
let url = parsed.href;
if (isAbsolute === false) {
url = Meteor.absoluteUrl(parsed.href);
}
fetch(url, requestOpt).then((response) => {
if (response.status >= 400) {
reject(new Error(response.status));
}
if (response.status === 204) {
resolve([]);
} else {
// TODO: Handle 204 no content
resolve(response);
}
}, (error) => {
console.error('There was an error in the DICOMWeb Server');
reject(new Error(error));
});
});
}
export default makeRequest;

View File

@ -1,39 +1,39 @@
import {validate as v} from './lib/validate.js';
v.validators.equals = function(value, options, key, attributes) {
if (options && value !== options.value) {
return key + 'must equal ' + options.value;
}
};
v.validators.doesNotEqual = function(value, options, key) {
if (options && value === options.value) {
return key + 'cannot equal ' + options.value;
}
};
v.validators.contains = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) === -1) {
return key + 'must contain ' + options.value;
}
};
v.validators.doesNotContain = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) !== -1) {
return key + 'cannot contain ' + options.value;
}
};
v.validators.startsWith = function(value, options, key) {
if (options && value.startsWith && !value.startsWith(options.value)) {
return key + 'must start with ' + options.value;
}
};
v.validators.endsWith = function(value, options, key) {
if (options && value.endsWith && !value.endsWith(options.value)) {
return key + 'must end with ' + options.value;
}
};
validate = v;
import { validate } from 'validate.js';
validate.validators.equals = function(value, options, key, attributes) {
if (options && value !== options.value) {
return key + 'must equal ' + options.value;
}
};
validate.validators.doesNotEqual = function(value, options, key) {
if (options && value === options.value) {
return key + 'cannot equal ' + options.value;
}
};
validate.validators.contains = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) === -1) {
return key + 'must contain ' + options.value;
}
};
validate.validators.doesNotContain = function(value, options, key) {
if (options && value.indexOf && value.indexOf(options.value) !== -1) {
return key + 'cannot contain ' + options.value;
}
};
validate.validators.startsWith = function(value, options, key) {
if (options && value.startsWith && !value.startsWith(options.value)) {
return key + 'must start with ' + options.value;
}
};
validate.validators.endsWith = function(value, options, key) {
if (options && value.endsWith && !value.endsWith(options.value)) {
return key + 'must end with ' + options.value;
}
};
export { validate };

View File

@ -2,6 +2,7 @@
import { Viewerbase } from 'meteor/ohif:viewerbase';
// Local imports
import { validate } from '../lib/validate.js';
import '../customAttributes';
/**
@ -102,7 +103,8 @@ const match = (metadataInstance, rules) => {
return {
score,
details
details,
requiredFailed
};
};

View File

@ -274,8 +274,6 @@ HP.ProtocolEngine = class ProtocolEngine {
let highestStudyMatchingScore = 0;
let highestSeriesMatchingScore = 0;
let highestImageMatchingScore = 0;
let bestMatch;
// Set custom attribute for study metadata and it's first instance
currentStudy.setCustomAttribute(ABSTRACT_PRIOR_VALUE, 0);
@ -349,8 +347,9 @@ HP.ProtocolEngine = class ProtocolEngine {
this.studies.forEach(study => {
const studyMatchDetails = HPMatcher.match(study.getFirstInstance(), studyMatchingRules);
if ((studyMatchingRules.length && !studyMatchDetails.score) ||
studyMatchDetails.score < highestStudyMatchingScore) {
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (studyMatchDetails.requiredFailed === true || studyMatchDetails.score < highestStudyMatchingScore) {
return;
}
@ -358,8 +357,9 @@ HP.ProtocolEngine = class ProtocolEngine {
study.forEachSeries(series => {
const seriesMatchDetails = HPMatcher.match(series.getFirstInstance(), seriesMatchingRules);
if ((seriesMatchingRules.length && !seriesMatchDetails.score) ||
seriesMatchDetails.score < highestSeriesMatchingScore) {
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (seriesMatchDetails.requiredFailed === true || seriesMatchDetails.score < highestSeriesMatchingScore) {
return;
}
@ -377,6 +377,11 @@ HP.ProtocolEngine = class ProtocolEngine {
const instanceMatchDetails = HPMatcher.match(instance, instanceMatchingRules);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
if (instanceMatchDetails.requiredFailed === true) {
return;
}
const matchDetails = {
passed: [],
failed: []
@ -417,11 +422,6 @@ HP.ProtocolEngine = class ProtocolEngine {
imageDetails.imageId = instance.getImageId();
}
if ((totalMatchScore > highestImageMatchingScore) || !bestMatch) {
highestImageMatchingScore = totalMatchScore;
bestMatch = imageDetails;
}
matchingScores.push(imageDetails);
});
});
@ -441,6 +441,8 @@ HP.ProtocolEngine = class ProtocolEngine {
});
matchingScores.sort((a, b) => sortingFunction(a.sortingInfo, b.sortingInfo));
const bestMatch = matchingScores[0];
OHIF.log.info('ProtocolEngine::matchImages bestMatch', bestMatch);
return {

View File

@ -4,8 +4,12 @@ Package.describe({
version: '0.0.1'
});
Npm.depends({
'validate.js': '0.9.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('standard-app-packages');
@ -16,7 +20,6 @@ Package.onUse(function(api) {
api.use('natestrauser:select2@4.0.1', 'client');
api.use('clinical:router@2.0.19');
api.use('momentjs:moment');
api.use('validatejs');
// Our custom packages
api.use('ohif:core');

View File

@ -5,7 +5,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2.3');
api.versionsFrom('1.7');
// Meteor packages
api.use('ecmascript');

View File

@ -36,7 +36,7 @@ export class HotkeysManager {
return new Promise((resolve, reject) => {
if (this.storeFunction) {
this.storeFunction.call(this, storageKey, definitions).then(resolve).catch(reject);
} else if (Meteor.userId()) {
} else if (OHIF.user.userLoggedIn()) {
OHIF.user.setData(storageKey, definitions).then(resolve).catch(reject);
} else {
Session.setPersistent(storageKey, definitions);
@ -50,7 +50,7 @@ export class HotkeysManager {
return new Promise((resolve, reject) => {
if (this.retrieveFunction) {
this.retrieveFunction(contextName).then(resolve).catch(reject);
} else if (OHIF.user) {
} else if (OHIF.user.userLoggedIn()) {
try {
resolve(OHIF.user.getData(storageKey));
} catch(error) {

View File

@ -1,6 +1,6 @@
<template name="hotkeysConfirmReplacementPopover">
{{#popoverForm (extend this confirmLabel='Yes' cancelLabel='No' confirmClass='btn-danger')}}
<p><b>{{this.conflictedFunctionName}}</b> is already using the <b>{{this.hotkeyCombination}}</b> shortcut.</p>
<p>Do you want to use the shortcut to the <b>{{this.newFunctionName}}</b> function instead?</p>
<p>Do you want to use the shortcut for the <b>{{this.newFunctionName}}</b> function instead?</p>
{{/popoverForm}}
</template>

View File

@ -1,2 +1 @@
import './components';
import './lib';

View File

@ -1 +0,0 @@
import './routes';

View File

@ -1,14 +0,0 @@
import { Router } from 'meteor/clinical:router';
import { Session } from 'meteor/session';
import { hotkeys } from 'meteor/ohif:hotkeys';
Router.onBeforeAction(function() {
const lastRoute = Session.get('lastRoute');
const currentRoute = this.router.current().route.getName();
if (currentRoute !== lastRoute) {
hotkeys.switchToContext(null);
Session.set('lastRoute', currentRoute);
}
this.next();
});

View File

@ -9,7 +9,7 @@ Npm.depends({
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
// Meteor packages
api.use([

View File

@ -0,0 +1,32 @@
// Calculate the longest and shortest diameters for the given measurementData
export default function(eventData, measurementData) {
const { rowPixelSpacing, columnPixelSpacing } = eventData.image;
const { start, end, perpendicularStart, perpendicularEnd } = measurementData.handles;
// updatePerpendicularLineHandles(eventData, measurementData);
// Calculate the long axis length
const dx = (start.x - end.x) * (columnPixelSpacing || 1);
const dy = (start.y - end.y) * (rowPixelSpacing || 1);
let length = Math.sqrt(dx * dx + dy * dy);
// Calculate the short axis length
const wx = (perpendicularStart.x - perpendicularEnd.x) * (columnPixelSpacing || 1);
const wy = (perpendicularStart.y - perpendicularEnd.y) * (rowPixelSpacing || 1);
let width = Math.sqrt(wx * wx + wy * wy);
if (!width) {
width = 0;
}
// Length is always longer than width
if (width > length) {
const tempW = width;
const tempL = length;
length = tempW;
width = tempL;
}
// Set measurement text to show lesion table
measurementData.longestDiameter = length.toFixed(1);
measurementData.shortestDiameter = width.toFixed(1);
}

View File

@ -0,0 +1,42 @@
const swapAttribute = (a, b, attribute) => {
const originalA = a[attribute];
const originalB = b[attribute];
a[attribute] = originalB;
b[attribute] = originalA;
};
const swapHandles = (a, b) => {
swapAttribute(a, b, 'x');
swapAttribute(a, b, 'y');
swapAttribute(a, b, 'moving');
swapAttribute(a, b, 'hover');
swapAttribute(a, b, 'active');
swapAttribute(a, b, 'selected');
};
function invertHandles(eventData, measurementData, handle) {
const { rowPixelSpacing, columnPixelSpacing } = eventData.image;
const { handles } = measurementData;
const { start, end, perpendicularStart, perpendicularEnd } = handles;
// Calculate the long axis length
const dx = (start.x - end.x) * (columnPixelSpacing || 1);
const dy = (start.y - end.y) * (rowPixelSpacing || 1);
const length = Math.sqrt(dx * dx + dy * dy);
// Calculate the short axis length
const wx = (perpendicularStart.x - perpendicularEnd.x) * (columnPixelSpacing || 1);
const wy = (perpendicularStart.y - perpendicularEnd.y) * (rowPixelSpacing || 1);
const width = Math.sqrt(wx * wx + wy * wy) || 0;
if (width > length) {
swapHandles(start, end);
swapHandles(start, perpendicularStart);
swapHandles(end, perpendicularEnd);
return Object.values(handles).find(h => h.moving === true);
}
return handle;
}
export default invertHandles;

View File

@ -5,6 +5,7 @@ import { toolType, distanceThreshold } from './definitions';
import mouseMoveCallback from './mouseMoveCallback';
import pointNearTool from './pointNearTool';
import moveHandle from './moveHandle';
import invertHandles from './invertHandles';
// Clear the selected state for the given handles object
const unselectAllHandles = handles => {
@ -88,9 +89,14 @@ export default function(event) {
for (let i = 0; i < toolData.data.length; i++) {
data = toolData.data[i];
const handleParams = [element, data.handles, coords, distanceThreshold];
const handle = cornerstoneTools.getHandleNearImagePoint(...handleParams);
let handle = cornerstoneTools.getHandleNearImagePoint(...handleParams);
if (handle) {
handle.moving = true;
// Invert handles if needed
handle = invertHandles(eventData, data, handle);
// Hide the cursor to improve precision while resizing the line or set to move
// if dragging text box
$element.css('cursor', handle.hasBoundingBox ? 'move' : 'none');
@ -99,7 +105,6 @@ export default function(event) {
data.active = true;
unselectAllHandles(data.handles);
handle.moving = true;
moveHandle(eventData, toolType, data, handle, () => handleDoneMove(handle));
event.stopImmediatePropagation();
event.stopPropagation();

View File

@ -1,5 +1,6 @@
import { cornerstone } from 'meteor/ohif:cornerstone';
import setHandlesPosition from './setHandlesPosition';
import calculateLongestAndShortestDiameters from '../calculateLongestAndShortestDiameters';
export default function (mouseEventData, toolType, data, handle, doneMovingCallback, preventHandleOutsideImage) {
const element = mouseEventData.element;
@ -29,14 +30,23 @@ export default function (mouseEventData, toolType, data, handle, doneMovingCallb
cornerstone.updateImage(element);
const eventType = 'cornerstonetoolsmeasurementmodified';
const modifiedEventData = {
toolType,
element,
measurementData: data
const measurementModifiedHandler = () => {
const eventType = 'cornerstonetoolsmeasurementmodified';
const modifiedEventData = {
toolType,
element,
measurementData: data
};
calculateLongestAndShortestDiameters(mouseEventData, data);
cornerstone.triggerEvent(element, eventType, modifiedEventData);
element.removeEventListener('cornerstoneimagerendered', measurementModifiedHandler);
};
cornerstone.triggerEvent(element, eventType, modifiedEventData);
// Wait on image render before triggering the modified event
element.addEventListener('cornerstoneimagerendered', measurementModifiedHandler);
};
element.addEventListener('cornerstonetoolsmousedrag', mouseDragCallback);

View File

@ -2,11 +2,12 @@ import { cornerstone, cornerstoneMath, cornerstoneTools } from 'meteor/ohif:corn
import { OHIF } from 'meteor/ohif:core';
import { toolType } from '../definitions';
import drawHandles from './drawHandles';
import calculateLongestAndShortestDiameters from '../calculateLongestAndShortestDiameters';
import updatePerpendicularLineHandles from '../updatePerpendicularLineHandles';
import drawPerpendicularLine from './drawPerpendicularLine';
import drawSelectedMarker from './drawSelectedMarker';
export default function(event) {
export default function onImageRendered(event) {
const eventData = event.detail;
const { element, canvasContext } = eventData;
@ -41,9 +42,7 @@ export default function(event) {
for (let i = 0; i < toolData.data.length; i++) {
const data = toolData.data[i];
if (data.visible === false) {
continue;
}
if (data.visible === false) continue;
const { start, end, perpendicularStart, perpendicularEnd, textBox } = data.handles;
const strokeWidth = lineWidth;
@ -65,10 +64,16 @@ export default function(event) {
color = cornerstoneTools.toolColors.getToolColor();
}
// draw the line
const handleStartCanvas = cornerstone.pixelToCanvas(element, start);
const handleEndCanvas = cornerstone.pixelToCanvas(element, end);
const canvasTextLocation = cornerstone.pixelToCanvas(element, textBox);
// Update the perpendicular handles to draw it correctly
updatePerpendicularLineHandles(eventData, data);
// Draw the line
const { pixelToCanvas } = cornerstone;
const handleStartCanvas = pixelToCanvas(element, start);
const handleEndCanvas = pixelToCanvas(element, end);
const handlePerpendicularStartCanvas = pixelToCanvas(element, perpendicularStart);
const handlePerpendicularEndCanvas = pixelToCanvas(element, perpendicularEnd);
const canvasTextLocation = pixelToCanvas(element, textBox);
context.beginPath();
context.strokeStyle = color;
@ -78,7 +83,6 @@ export default function(event) {
context.stroke();
// Draw perpendicular line
updatePerpendicularLineHandles(eventData, data);
drawPerpendicularLine(context, element, data, color, strokeWidth);
// Draw the handles
@ -88,26 +92,8 @@ export default function(event) {
// Draw the selected marker
drawSelectedMarker(eventData, data.handles, '#FF9999');
// Calculate the long axis length
const dx = (start.x - end.x) * (colPixelSpacing || 1);
const dy = (start.y - end.y) * (rowPixelSpacing || 1);
let length = Math.sqrt(dx * dx + dy * dy);
// Calculate the short axis length
const wx = (perpendicularStart.x - perpendicularEnd.x) * (colPixelSpacing || 1);
const wy = (perpendicularStart.y - perpendicularEnd.y) * (rowPixelSpacing || 1);
let width = Math.sqrt(wx * wx + wy * wy);
if (!width) {
width = 0;
}
// Length is always longer than width
if (width > length) {
const tempW = width;
const tempL = length;
length = tempW;
width = tempL;
}
// Calculate the longest and shortest diameters, storing it in the respective attributes
calculateLongestAndShortestDiameters(eventData, data);
if (data.measurementNumber) {
// Draw the textbox
@ -116,9 +102,14 @@ export default function(event) {
suffix = ' pixels';
}
const lengthText = ' L ' + length.toFixed(1) + suffix;
const widthText = ' W ' + width.toFixed(1) + suffix;
const textLines = [`Target ${data.measurementNumber}`, lengthText, widthText];
const lengthText = ' L ' + data.longestDiameter + suffix;
const widthText = ' W ' + data.shortestDiameter + suffix;
let textLines = [`Target ${data.measurementNumber}`, lengthText, widthText];
// Append extra text lines when applies
if (data.additionalData && Array.isArray(data.additionalData.extraTextLines)) {
textLines = textLines.concat(data.additionalData.extraTextLines);
}
const boundingBox = cornerstoneTools.drawTextBox(
context,
@ -139,12 +130,39 @@ export default function(event) {
end: {}
};
const midpointCanvas = {
x: (handleStartCanvas.x + handleEndCanvas.x) / 2,
y: (handleStartCanvas.y + handleEndCanvas.y) / 2,
const longLine = {
start: handleStartCanvas,
end: handleEndCanvas
};
const points = [ handleStartCanvas, handleEndCanvas, midpointCanvas ];
const perpendicularLine = {
start: handlePerpendicularStartCanvas,
end: handlePerpendicularEndCanvas
};
// Check if the perpendicular line has some length (start and end are not equal)
// Note: this check is needed to prevent NaN value on the intersection result
const { distance } = cornerstoneMath.point;
const lineHasLength = distance(perpendicularLine.start, perpendicularLine.end) > 0;
// Define the lines intersection point
let linesIntersection;
if (lineHasLength) {
// As the line has length, define it as the intersection between the lines
const { intersectLine } = cornerstoneMath.lineSegment;
linesIntersection = intersectLine(longLine, perpendicularLine);
} else {
// As the line has no length, the tool is in its start position
linesIntersection = longLine.start;
}
const points = [
handleStartCanvas,
handleEndCanvas,
handlePerpendicularStartCanvas,
handlePerpendicularEndCanvas,
linesIntersection
];
link.end.x = canvasTextLocation.x;
link.end.y = canvasTextLocation.y;
@ -181,10 +199,6 @@ export default function(event) {
context.stroke();
}
// Set measurement text to show lesion table
data.longestDiameter = length.toFixed(1);
data.shortestDiameter = width.toFixed(1);
context.restore();
}
}
}

View File

@ -35,7 +35,13 @@ Template[defaultTemplate].onRendered(() => {
if (computation.firstRun) return;
computation.stop();
const imageIndex = instance.getImageIndex();
OHIF.studies.loadStudy(studyInstanceUid).then(studyMetadata => {
if (!studyInstanceUid || !seriesInstanceUid) {
return;
}
OHIF.studies.loadStudy(studyInstanceUid).then(study => {
const studyMetadata = OHIF.viewerbase.getStudyMetadata(study);
const seriesMetadata = studyMetadata.getSeriesByUID(seriesInstanceUid);
const instanceMetadata = seriesMetadata.getInstanceByIndex(imageIndex);
if (!instanceMetadata) return;

View File

@ -62,7 +62,7 @@ Template.timepointBrowserItem.onCreated(() => {
});
Template.timepointBrowserItem.events({
'ohif.lesiontracker.timepoint.load .timepoint-item'(event, instance) {
'ohif.measurements.timepoint.load .timepoint-item'(event, instance) {
instance.loadStudies();
},
@ -71,7 +71,7 @@ Template.timepointBrowserItem.events({
const $element = $(element);
const triggerClick = () => {
$element.trigger('ohif.lesiontracker.timepoint.click', instance.data.timepoint);
$element.trigger('ohif.measurements.timepoint.click', instance.data.timepoint);
};
if (!instance.studiesData.get()) {

View File

@ -72,7 +72,7 @@ Template.timepointBrowserQuickSwitch.onRendered(() => {
});
Template.timepointBrowserQuickSwitch.events({
'ohif.lesiontracker.timepoint.click'(event, instance) {
'ohif.measurements.timepoint.click'(event, instance) {
const $element = $(event.currentTarget);
$element.toggleClass('active');
instance.updateActiveStudy();

View File

@ -19,7 +19,7 @@ Template.timepointBrowserSidebar.onRendered(() => {
// Runs this computation every time the timepointViewType is changed
const type = instance.timepointViewType.get();
if (type !== instance.lastType) {
const eventKey = 'ohif.lesiontracker.timepoint.changeViewType';
const eventKey = 'ohif.measurements.timepoint.changeViewType';
instance.$browserList.trigger(eventKey, type);
}
@ -49,7 +49,7 @@ Template.timepointBrowserSidebar.events({
});
},
'ohif.lesiontracker.timepoint.click'(event, instance) {
'ohif.measurements.timepoint.click'(event, instance) {
const $element = $(event.currentTarget);
// Defer the active class toggling to wait for child template rendering

View File

@ -5,7 +5,7 @@ Package.describe({
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('standard-app-packages');
@ -13,8 +13,6 @@ Package.onUse(function(api) {
api.use('stylus');
api.use('random');
api.use('validatejs');
// Template overriding
api.use('aldeed:template-extension@4.0.0');

View File

@ -9,7 +9,7 @@ Npm.depends({
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.versionsFrom('1.7');
api.use('ecmascript');
api.use('standard-app-packages');

View File

@ -9,16 +9,12 @@ export const retrieveMeasurements = (patientId, timepointIds) => {
if(!latestSeries) return Promise.resolve({});
return retrieveMeasurementFromSR(latestSeries).then((value) => {
return {
length: value
}
});
return retrieveMeasurementFromSR(latestSeries);
};
export const storeMeasurements = (measurementData, timepointIds) => {
OHIF.log.info('storeMeasurements');
const server = OHIF.servers.getCurrentServer();
if (!server || server.type !== 'dicomWeb') {
return Promise.resolve({});
@ -28,6 +24,8 @@ export const storeMeasurements = (measurementData, timepointIds) => {
return stowSRFromMeasurements(measurementData).then( () => {
OHIF.studies.deleteStudyMetadataPromise(studyInstanceUid);
}, error => {
throw new Error(error);
});
};

Some files were not shown because too many files have changed in this diff Show More