Work on refactoring measurements out of Lesion Tracker package

- Removed AssociatedStudies Collection
- Measurement API is generated from configuration files
- Data exchange methods are defined in configuration
This commit is contained in:
Erik Ziegler committed 2016-11-15 08:21:46 +01:00
1 parent c511edd419
commit ab4d4c9008
537 files changed
+5122 -3545

No files matched your search

@@ -0,0 +1,115 @@
var exportFailed;
/**
* Exports requested studies
* @param studiesToExport Studies to export
*/
exportStudies = function(studiesToExport) {
if (studiesToExport.length < 1) {
return;
}
queryStudies(studiesToExport, exportQueriedStudies);
};
function exportQueriedStudies(studiesToExport) {
var numberOfFilesToExport = 0;
studiesToExport.forEach(function(study) {
numberOfFilesToExport += getNumberOfFilesInStudy(study);
});
progressDialog.show("Exporting Studies...", numberOfFilesToExport);
try {
exportQueriedStudiesInternal(studiesToExport, numberOfFilesToExport);
} catch (err) {
progressDialog.close();
console.error("Failed to export studies: " + err.message);
}
}
function exportQueriedStudiesInternal(studiesToExport, numberOfFilesToExport) {
var zip = new JSZip();
exportFailed = false;
var numberOfFilesExported = 0;
studiesToExport.forEach(function(study) {
sortStudy(study);
var studyFolder = zip.folder(study.studyInstanceUid);
study.seriesList.forEach(function(series) {
var seriesFolder = studyFolder.folder(series.seriesInstanceUid);
series.instances.forEach(function(instance) {
if (!instance.wadouri) {
return;
}
// If failed to download a dicom file, skip others
if (exportFailed) {
return;
}
// Download and Zip the dicom file
var xhr = new XMLHttpRequest();
xhr.open("GET", instance.wadouri, true);
xhr.responseType = "blob";
// Downloaded the dicom file completely
xhr.onload = function(e) {
// If failed to download a dicom file, skip others
if (exportFailed) {
return;
}
// Failed to export a file
if (xhr.readyState === 4 && xhr.status !== 200) {
onExportFailed("File not downloaded: " + instance.wadouri);
return;
}
var blobFile = new Blob([xhr.response], {type: 'application/dicom'});
var fileReader = new FileReader();
fileReader.onload = function() {
try {
seriesFolder.file(instance.sopInstanceUid + ".dcm", fileReader.result, { binary: true });
} catch(err) {
onExportFailed(err.message);
return;
}
numberOfFilesExported++;
if (numberOfFilesExported === numberOfFilesToExport) {
var zipContent = zip.generate({ type: "blob" });
saveAs(zipContent, "studies.zip");
}
progressDialog.update(numberOfFilesExported);
};
fileReader.readAsArrayBuffer(blobFile);
};
// Failed to download the dicom file
xhr.onerror = function() {
onExportFailed("File not downloaded: " + instance.wadouri);
};
xhr.send();
});
});
});
}
function onExportFailed(err) {
exportFailed = true;
progressDialog.close();
//TODO: Export failed and dialog closed, so let user know
console.error("Failed to export studies!", err);
}
@@ -0,0 +1,58 @@
/**
* Retrieves metaData for multiple studies at once.
*
* This function calls getStudyMetadata several times, asynchronously,
* and waits for all of the results to be returned.
*
* @param studyInstanceUids The UIDs of the Studies to be retrieved
* @param doneCallback The callback function to be executed when the study retrieval has finished
* @param failCallback The callback function to be executed when the study retrieval has failed
*/
getStudiesMetadata = function(studyInstanceUids, doneCallback, failCallback) {
// Check to make sure studyInstanceUids were actually input
if (!studyInstanceUids || !studyInstanceUids.length) {
if (failCallback && typeof failCallback === 'function') {
failCallback('No studyInstanceUids were input');
}
return;
}
// Create an empty array to store the Promises for each metaData
// retrieval call
var promises = [];
// Loop through the array of studyInstanceUids
studyInstanceUids.forEach(function(studyInstanceUid) {
// Create a new Deferred to monitor the progress of the asynchronous
// metaData retrieval
var deferred = new $.Deferred();
// Send the call, and attach doneCallbacks and failCallbacks
// which can resolve or reject the related promise based on its outcome
getStudyMetadata(studyInstanceUid, function(study) {
deferred.resolve(study);
}, function(error) {
deferred.reject(error);
});
// Add the current promise to the array of promises
promises.push(deferred.promise());
});
// When all of the promises are complete, this callback runs
$.when.apply($, promises).done(function() {
// Convert the Arguments Array-like Object to an actual array
var studies = $.makeArray(arguments);
// Pass the studies array to the doneCallback, if one exists
if (doneCallback && typeof doneCallback === 'function') {
doneCallback(studies);
}
}).fail(function(error) {
log.warn(error);
if (failCallback && typeof failCallback === 'function') {
failCallback(error);
}
});
};
@@ -0,0 +1,75 @@
// Define the StudyMetaData object. This is used as a cache
// to store study meta data information to prevent unnecessary
// calls to the server
var StudyMetaData = {};
/**
* Retrieves study metadata using a server call, and fires a callback
* when completed.
*
* @params {string} studyInstanceUid The UID of the Study to be retrieved
* @params {function} doneCallback The callback function to be executed when the study retrieval has finished
* @param failCallback The callback function to be executed when the study retrieval has failed
*/
getStudyMetadata = function(studyInstanceUid, doneCallback, failCallback) {
// If the StudyMetaData cache already has data related to this
// studyInstanceUid, then we should fire the doneCallback with this data
// and stop here.
var study = StudyMetaData[studyInstanceUid];
if (study) {
doneCallback(study);
return;
}
console.time('getStudyMetadata');
// If no study metadata is in the cache variable, we need to retrieve it from
// the server with a call.
Meteor.call('GetStudyMetadata', studyInstanceUid, function(error, study) {
console.timeEnd('getStudyMetadata');
if (Meteor.user && Meteor.user()) {
var hipaaEvent = {
eventType: 'viewed',
userId: Meteor.userId(),
userName: Meteor.user().profile.fullName,
collectionName: 'Study',
recordId: studyInstanceUid,
patientId: study.patientId,
patientName: study.patientName
};
HipaaLogger.logEvent(hipaaEvent);
}
if (error) {
log.warn(error);
failCallback(error);
return;
}
if (!study) {
throw "GetStudyMetadata: No study data returned from server";
}
// Once we have retrieved the data, we sort the series' by series
// and instance number in ascending order
sortStudy(study);
// Add additional metadata to our study from the studylist
var studylistStudy = StudyListStudies.findOne({
studyInstanceUid: study.studyInstanceUid
});
if (!studylistStudy) {
return;
}
$.extend(study, studylistStudy);
// Then we store this data in the cache variable
StudyMetaData[studyInstanceUid] = study;
// Finally, we fire the doneCallback with this study meta data
doneCallback(study);
});
};
@@ -0,0 +1,131 @@
/**
* Imports selected studies from local into studylist
* @param filesToImport Files located in the client machine to import
*/
importStudies = function(filesToImport, importCallback) {
if (filesToImport.length < 1) {
return;
}
var fileUploadStatus = {
numberOfFilesUploaded: 0,
numberOfFilesFailed: 0
};
var numberOfFilesToUpload = filesToImport.length;
var studiesToImport = [];
progressDialog.show({
title: "Uploading Files...",
numberOfCompleted: 0,
numberOfTotal: numberOfFilesToUpload
});
// Upload files to the server
filesToImport.forEach(function(fileToUpload) {
var xhr = new XMLHttpRequest();
xhr.open('POST', "/uploadFilesToImport", true);
xhr.setRequestHeader("filename", fileToUpload.name);
xhr.onload = function() {
// Failed to upload a file
if (xhr.readyState === 4 && xhr.status !== 200) {
updateFileUploadStatus(fileUploadStatus, false);
return;
}
studiesToImport.push(xhr.responseText);
updateFileUploadStatus(fileUploadStatus, true);
var numberOfFilesProcessedToUpload = fileUploadStatus.numberOfFilesUploaded + fileUploadStatus.numberOfFilesFailed;
progressDialog.update(numberOfFilesProcessedToUpload);
if (numberOfFilesToUpload === numberOfFilesProcessedToUpload) {
// The upload is completed, so import files
importStudiesInternal(studiesToImport, importCallback);
if (fileUploadStatus.numberOfFilesFailed > 0) {
//TODO: Some files failed to upload, so let user know
log.info("Failed to upload " + fileUploadStatus.numberOfFilesFailed + " of " + numberOfFilesToUpload + " files");
}
}
};
// Failed to upload a file
xhr.onerror = function() {
updateFileUploadStatus(fileUploadStatus, false);
};
xhr.send(fileToUpload);
});
};
function updateFileUploadStatus(fileUploadStatus, isSuccess) {
if (!isSuccess) {
fileUploadStatus.numberOfFilesFailed++;
} else {
fileUploadStatus.numberOfFilesUploaded++;
}
}
function importStudiesInternal(studiesToImport, importCallback) {
if (!studiesToImport) {
return;
}
var numberOfStudiesToImport = studiesToImport.length;
progressDialog.show({
title: "Importing Studies...",
numberOfCompleted: 0,
numberOfTotal: numberOfStudiesToImport
});
// Create/Insert a new study import status item
Meteor.call("createStudyImportStatus", function(err, studyImportStatusId) {
if (err) {
// Hide dialog
progressDialog.close();
console.log(err.message);
return;
}
// Handle when StudyImportStatus collection is updated
StudyImportStatus.find(studyImportStatusId).observe({
changed: function(studyImportStatus) {
if (!studyImportStatus) {
return;
}
var numberOfStudiesProcessedToImport = studyImportStatus.numberOfStudiesImported + studyImportStatus.numberOfStudiesFailed;
// Show number of imported files
var successMessage = 'Imported '+studyImportStatus.numberOfStudiesImported+' of '+numberOfStudiesToImport;
progressDialog.setMessage({
message: successMessage,
messageType: 'success'
});
progressDialog.update(numberOfStudiesProcessedToImport);
// Show number of failed files if there is at least one failed file
if (studyImportStatus.numberOfStudiesFailed > 0) {
var successMessage = 'Failed '+studyImportStatus.numberOfStudiesFailed+' of '+numberOfStudiesToImport;
progressDialog.setMessage({
message: successMessage,
messageType: 'warning'
});
}
if (numberOfStudiesProcessedToImport == numberOfStudiesToImport) {
// The entire import operation is completed, so remove the study import status item
Meteor.call("removeStudyImportStatus", studyImportStatus._id);
// Let the caller know that import operation is completed
if (importCallback) {
importCallback();
}
}
}
});
// Import studies with study import status id to get callbacks
Meteor.call("importStudies", studiesToImport, studyImportStatusId);
});
}
@@ -0,0 +1,9 @@
/*
* jQuery Bootstrap Pagination v1.3.1
* https://github.com/esimakin/twbs-pagination
*
* Copyright 2014-2015 Eugene Simakin <eugenesimakin@mail.ru>
* Released under Apache 2.0 license
* http://apache.org/licenses/LICENSE-2.0.html
*/
!function(a,b,c,d){"use strict";var e=a.fn.twbsPagination,f=function(c,d){if(this.$element=a(c),this.options=a.extend({},a.fn.twbsPagination.defaults,d),this.options.startPage<1||this.options.startPage>this.options.totalPages)throw new Error("Start page option is incorrect");if(this.options.totalPages=parseInt(this.options.totalPages),isNaN(this.options.totalPages))throw new Error("Total pages option is not correct!");if(this.options.visiblePages=parseInt(this.options.visiblePages),isNaN(this.options.visiblePages))throw new Error("Visible pages option is not correct!");if(this.options.totalPages<this.options.visiblePages&&(this.options.visiblePages=this.options.totalPages),this.options.onPageClick instanceof Function&&this.$element.first().on("page",this.options.onPageClick),this.options.href){var e,f=this.options.href.replace(/[-\/\\^$*+?.|[\]]/g,"\\$&");f=f.replace(this.options.hrefVariable,"(\\d+)"),null!=(e=new RegExp(f,"i").exec(b.location.href))&&(this.options.startPage=parseInt(e[1],10))}var g="function"==typeof this.$element.prop?this.$element.prop("tagName"):this.$element.attr("tagName");return"UL"===g?this.$listContainer=this.$element:this.$listContainer=a("<ul></ul>"),this.$listContainer.addClass(this.options.paginationClass),"UL"!==g&&this.$element.append(this.$listContainer),this.render(this.getPages(this.options.startPage)),this.setupEvents(),this.options.initiateStartPageClick&&this.$element.trigger("page",this.options.startPage),this};f.prototype={constructor:f,destroy:function(){return this.$element.empty(),this.$element.removeData("twbs-pagination"),this.$element.off("page"),this},show:function(a){if(1>a||a>this.options.totalPages)throw new Error("Page is incorrect.");return this.render(this.getPages(a)),this.setupEvents(),this.$element.trigger("page",a),this},buildListItems:function(a){var b=[];if(this.options.first&&b.push(this.buildItem("first",1)),this.options.prev){var c=a.currentPage>1?a.currentPage-1:this.options.loop?this.options.totalPages:1;b.push(this.buildItem("prev",c))}for(var d=0;d<a.numeric.length;d++)b.push(this.buildItem("page",a.numeric[d]));if(this.options.next){var e=a.currentPage<this.options.totalPages?a.currentPage+1:this.options.loop?1:this.options.totalPages;b.push(this.buildItem("next",e))}return this.options.last&&b.push(this.buildItem("last",this.options.totalPages)),b},buildItem:function(b,c){var d=a("<li></li>"),e=a("<a></a>"),f=null;switch(b){case"page":f=c,d.addClass(this.options.pageClass);break;case"first":f=this.options.first,d.addClass(this.options.firstClass);break;case"prev":f=this.options.prev,d.addClass(this.options.prevClass);break;case"next":f=this.options.next,d.addClass(this.options.nextClass);break;case"last":f=this.options.last,d.addClass(this.options.lastClass)}return d.data("page",c),d.data("page-type",b),d.append(e.attr("href",this.makeHref(c)).html(f)),d},getPages:function(a){var b=[],c=Math.floor(this.options.visiblePages/2),d=a-c+1-this.options.visiblePages%2,e=a+c;0>=d&&(d=1,e=this.options.visiblePages),e>this.options.totalPages&&(d=this.options.totalPages-this.options.visiblePages+1,e=this.options.totalPages);for(var f=d;e>=f;)b.push(f),f++;return{currentPage:a,numeric:b}},render:function(b){var c=this;this.$listContainer.children().remove(),this.$listContainer.append(this.buildListItems(b)),this.$listContainer.children().each(function(){var d=a(this),e=d.data("page-type");switch(e){case"page":d.data("page")===b.currentPage&&d.addClass(c.options.activeClass);break;case"first":d.toggleClass(c.options.disabledClass,1===b.currentPage);break;case"last":d.toggleClass(c.options.disabledClass,b.currentPage===c.options.totalPages);break;case"prev":d.toggleClass(c.options.disabledClass,!c.options.loop&&1===b.currentPage);break;case"next":d.toggleClass(c.options.disabledClass,!c.options.loop&&b.currentPage===c.options.totalPages)}})},setupEvents:function(){var b=this;this.$listContainer.find("li").each(function(){var c=a(this);return c.off(),c.hasClass(b.options.disabledClass)||c.hasClass(b.options.activeClass)?void c.on("click",!1):void c.click(function(a){!b.options.href&&a.preventDefault(),b.show(parseInt(c.data("page")))})})},makeHref:function(a){return this.options.href?this.options.href.replace(this.options.hrefVariable,a):"#"}},a.fn.twbsPagination=function(b){var c,e=Array.prototype.slice.call(arguments,1),g=a(this),h=g.data("twbs-pagination"),i="object"==typeof b&&b;return h||g.data("twbs-pagination",h=new f(this,i)),"string"==typeof b&&(c=h[b].apply(h,e)),c===d?g:c},a.fn.twbsPagination.defaults={totalPages:0,startPage:1,visiblePages:5,initiateStartPageClick:!0,href:!1,hrefVariable:"{{number}}",first:"First",prev:"Previous",next:"Next",last:"Last",loop:!1,onPageClick:null,paginationClass:"pagination",nextClass:"next",prevClass:"prev",lastClass:"last",firstClass:"first",pageClass:"page",activeClass:"active",disabledClass:"disabled"},a.fn.twbsPagination.Constructor=f,a.fn.twbsPagination.noConflict=function(){return a.fn.twbsPagination=e,tLine truncated
@@ -0,0 +1,26 @@
/**
* Opens a new tab in the tabbed studylist environment using
* a given study and new tab title.
*
* @param studyInstanceUid The UID of the Study to be opened
* @param title The title to be used for the tab heading
*/
openNewTab = function(studyInstanceUid, title) {
console.log('openNewTab');
// Generate a unique ID to represent this tab
// We can't just use the Mongo entry ID because
// then it will change after hot-reloading.
var contentid = Random.id();
// Update the ViewerData global object
ViewerData = window.ViewerData || ViewerData;
ViewerData[contentid] = {
title: title,
contentid: contentid,
studyInstanceUids: [studyInstanceUid]
};
// Switch to the new tab
switchToTab(contentid);
};
@@ -0,0 +1,48 @@
/**
* Queries requested studies to get their metadata from PACS
* @param studiesToQuery Studies to query
* @param doneCallback Callback to call when the query is done
*/
queryStudies = function(studiesToQuery, doneCallback) {
if (studiesToQuery.length < 1) {
return;
}
var studiesQueried = [];
var numberOfStudiesToQuery = studiesToQuery.length;
progressDialog.show("Querying Studies...", numberOfStudiesToQuery);
studiesToQuery.forEach(function(studyToQuery) {
getStudyMetadata(studyToQuery.studyInstanceUid, function(study) {
studiesQueried.push(study);
var numberOfStudiesQueried = studiesQueried.length;
progressDialog.update(numberOfStudiesQueried);
if (numberOfStudiesQueried === numberOfStudiesToQuery) {
doneCallback(studiesQueried);
}
});
});
};
/**
* Returns the total number of dicom files in a study
* @param study Queried study (includes metadata)
* @returns {number}
*/
getNumberOfFilesInStudy = function(study) {
var numberOFFilesToExport = 0;
study.seriesList.forEach(function(series) {
series.instances.forEach(function(instance) {
if (instance.wadouri) {
numberOFFilesToExport++;
}
});
});
return numberOFFilesToExport;
};
@@ -0,0 +1,28 @@
StudyList = {
functions: {},
callbacks: {}
};
StudyList.callbacks.dblClickOnStudy = dblClickOnStudy;
StudyList.callbacks.middleClickOnStudy = dblClickOnStudy;
function dblClickOnStudy(data) {
// Use the formatPN template helper to clean up the patient name
var title = formatPN(data.patientName);
openNewTab(data.studyInstanceUid, title);
}
let currentServerChangeHandlerFirstRun = true;
const currentServerChangeHandler = () => {
if (currentServerChangeHandlerFirstRun) {
currentServerChangeHandlerFirstRun = false;
return;
}
switchToTab('worklistTab');
};
CurrentServer.find().observe({
added: currentServerChangeHandler,
changed: currentServerChangeHandler
});
@@ -0,0 +1,135 @@
/**
* Switches to a new tab in the tabbed studylist container
* This function renders either the StudyList or the Viewer template with new data.
*
* @param contentId The unique ID of the tab to be switched to
*/
switchToTab = function(contentId) {
if (!contentId) {
return;
}
log.info('Switching to tab: ' + contentId);
$('.tabTitle').removeClass('active');
$('.tabTitle a[data-target="#' + contentId + '"]').addClass('active');
$('.tab-content .tab-pane').removeClass('active');
if (contentId !== 'studylistTab') {
$('.tab-content .tab-pane#viewerTab').addClass('active');
} else {
$('.tab-content .tab-pane#' + contentId).addClass('active');
}
// Remove any previous Viewers from the DOM
$('.viewerContainer').remove();
$('.studylistContainer').remove();
// Update the 'activeContentId' variable in Session
Session.set('activeContentId', contentId);
// If we are switching to the StudyList tab, reset any CSS styles
// that have been applied to prevent scrolling in the Viewer.
// Then stop here, since nothing needs to be re-rendered.
var container;
if (contentId === 'studylistTab') {
container = $('.tab-content').find('#studylistTab').get(0);
if (!container) {
return;
}
var studylistContainer = document.createElement('div');
studylistContainer.classList.add('studylistContainer');
container.appendChild(studylistContainer);
// Use Blaze to render the StudyListResult Template into the container
Blaze.render(Template.studylistResult, studylistContainer);
document.body.style.overflow = null;
document.body.style.height = null;
document.body.style.minWidth = null;
document.body.style.position = null;
return;
}
// Tab was closed at some point, stop here
ViewerData = window.ViewerData || ViewerData;
if (!ViewerData[contentId]) {
return;
}
var studies = ViewerData[contentId].studies;
if (studies) {
// ViewerData already has the meta data (in cases when studylist is launched externally)
viewStudiesInTab(contentId, studies);
} else {
// Use the stored ViewerData global object to retrieve the studyInstanceUid
// related to this tab
var studyInstanceUids = ViewerData[contentId].studyInstanceUids;
// Attempt to retrieve the meta data (it might be cached)
getStudiesMetadata(studyInstanceUids, function(studies) {
viewStudiesInTab(contentId, studies);
});
}
};
function viewStudiesInTab(contentId, studies) {
// Tab closed while study data was being retrieved, stop here
if (!ViewerData[contentId]) {
log.warn('Tab closed while study data was being retrieved');
return;
}
// Once we have the study data, store it in a structure with
// any other saved data about this tab (e.g. layout structure)
var data = jQuery.extend({}, ViewerData[contentId]);
data.studies = studies;
data.contentId = contentId;
if (ViewerData[contentId].studies && ViewerData[contentId].studies.length) {
data.studies = ViewerData[contentId].studies;
}
// Add additional metadata to our study from the studylist
data.studies.forEach(function(study) {
var studylistStudy = StudyListStudies.findOne({
studyInstanceUid: study.studyInstanceUid
});
if (!studylistStudy) {
return;
}
$.extend(study, studylistStudy);
});
// Get tab content container given the contentId string
// If no such container exists, stop here because something is wrong
var container = $('.tab-content').find('#viewerTab').get(0);
// Remove the loading text template that is inside the tab container by default
var viewerContainer = document.createElement('div');
viewerContainer.classList.add('viewerContainer');
container.innerHTML = '';
container.appendChild(viewerContainer);
// Use Blaze to render the Viewer Template into the container
Blaze.renderWithData(Template.viewer, data, viewerContainer);
// Retrieve the DOM element of the viewer
var imageViewer = $('#viewer');
// If it is present in the DOM (it should be), then apply
// styles to prevent page scrolling and overscrolling on mobile devices
if (imageViewer) {
document.body.style.overflow = 'hidden';
document.body.style.height = '100%';
document.body.style.width = '100%';
document.body.style.minWidth = 0;
// Prevent overscroll on mobile devices
document.body.style.position = 'fixed';
}
}