Compare commits

..

14 Commits

Author SHA1 Message Date
mozzie
b31b0c422c feat: vite 2023-12-27 16:21:54 +08:00
mozzie
6b188b5354 feat: 完善了ts 2023-12-27 14:09:40 +08:00
mozzie
b291ce1216 feat: dcm转vtkVolume 2023-12-27 13:52:01 +08:00
mozzie
a34b2f725d feat: demo 2023-12-26 17:08:36 +08:00
mozzie
f1824ee928 feat: d 2023-12-22 16:57:25 +08:00
mozzie
2761357eac feat: dd 2023-12-22 13:20:48 +08:00
mozzie
f245d3c210 feat: mpr 2023-12-21 16:05:41 +08:00
mozzie
ae02206a60 feat: crosshair mpr 2023-12-21 12:49:50 +08:00
mozzie
c73fdb6a6d feat: mpr doing 2023-12-20 17:02:33 +08:00
mozzie
5008849d82 feat: 切换单个viewport的图片 2023-12-20 12:48:57 +08:00
mozzie
c04884ffd3 feat: 完善了demo ts约束 2023-12-20 10:24:54 +08:00
mozzie
42d18e116c feat: 打通了wadors 2023-12-19 16:56:25 +08:00
mozzie
3d1afd7a18 feat: test 2023-12-18 16:57:01 +08:00
mozzie
2ec9c401ba chore: docker-compose arm64 2023-10-11 08:59:59 +08:00
91 changed files with 5822 additions and 776 deletions

13
.vscode/tasks.json vendored
View File

@ -5,6 +5,7 @@
"label": "start-all-tasks", "label": "start-all-tasks",
"dependsOn": [ "dependsOn": [
"build:pkg", "build:pkg",
"phoenix-web",
"cert-web", "cert-web",
"aorta-web", "aorta-web",
"dmp-web", "dmp-web",
@ -36,6 +37,18 @@
"dev:logger" "dev:logger"
] ]
}, },
{
"label": "phoneix-web",
"type": "shell",
"command": "pnpm",
"args": [
"dev:phoenix"
],
"dependsOn": [
"build:pkg"
],
"problemMatcher": []
},
{ {
"label": "aorta-web", "label": "aorta-web",
"type": "shell", "type": "shell",

View File

@ -23,11 +23,22 @@
"js-cookie": "3.0.5", "js-cookie": "3.0.5",
"three": "0.156.1", "three": "0.156.1",
"path-to-regexp": "6.2.1", "path-to-regexp": "6.2.1",
"@cornerstonejs/core": "1.16.5",
"dicom-parser": "1.8.21", "dicom-parser": "1.8.21",
"cornerstone-wado-image-loader": "4.13.2",
"@msgpack/msgpack": "3.0.0-beta2", "@msgpack/msgpack": "3.0.0-beta2",
"pako": "2.1.0" "pako": "2.1.0",
"@kitware/vtk.js": "29.2.0",
"@cornerstonejs/dicom-image-loader": "1.41.0",
"@cornerstonejs/core": "1.41.0",
"dcmjs": "0.30.0",
"dicomweb-client": "0.10.3",
"@cornerstonejs/tools": "1.41.0",
"@cornerstonejs/streaming-image-volume-loader": "1.41.0",
"@cornerstonejs/calculate-suv": "1.1.0",
"vtk.js": "29.2.0",
"@itk-wasm/dicom": "5.0.2",
"itk-image-io": "^1.0.0-b.18",
"itk-mesh-io": "^1.0.0-b.18",
"web-workers": "0.9.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.21.8", "@babel/core": "^7.21.8",

View File

@ -0,0 +1,143 @@
[
"5.0.37",
[
"apple a14",
"14",
"a14 apple",
0,
[
[
2704,
1756,
120
]
]
],
[
"apple m1",
"1",
"apple m1",
0,
[
[
2880,
1800,
198
]
]
],
[
"apple m1 max",
"1",
"apple m1 max",
0,
[
[
3456,
2234,
556
]
]
],
[
"apple m1 pro",
"1",
"apple m1 pro",
0,
[
[
3024,
1964,
342
]
]
],
[
"apple m1 ultra",
"1",
"apple m1 ultra",
0,
[
[
5120,
2880,
437
]
]
],
[
"apple m2",
"2",
"apple m2",
0,
[
[
2880,
1800,
60
],
[
2940,
1912,
209
]
]
],
[
"apple m2 max",
"2",
"apple m2 max",
0,
[
[
3456,
2234,
120
]
]
],
[
"apple m2 pro",
"2",
"apple m2 pro",
0,
[
[
3024,
1964,
120
],
[
5120,
2880,
60
]
]
],
[
"apple m2 ultra",
"2",
"apple m2 ultra",
0,
[
[
5120,
2880,
60
]
]
],
[
"apple paravirtual device",
"",
"apple device paravirtual",
0,
[
[
1024,
768,
30
]
]
]
]

View File

@ -12,6 +12,11 @@ export const proxyMap: TProxyMap = {
changeOrigin: true, changeOrigin: true,
pathRewrite: { "^/dicom-web": "" }, pathRewrite: { "^/dicom-web": "" },
}, },
'/wado':{
target: "http://localhost:8042/wado",
changeOrigin: true,
pathRewrite: { "^/wado": "" },
},
"/cert": { "/cert": {
target: "http://localhost:12144/", target: "http://localhost:12144/",
changeOrigin: true, changeOrigin: true,
@ -26,5 +31,5 @@ export const proxyMap: TProxyMap = {
target: "http://localhost:5000/", target: "http://localhost:5000/",
changeOrigin: true, changeOrigin: true,
pathRewrite: { "^/py": "" }, pathRewrite: { "^/py": "" },
}, }
}; };

View File

@ -7,6 +7,7 @@ import jsonLoader from "./loaders/json.loader";
import imgLoader from "./loaders/img.loader"; import imgLoader from "./loaders/img.loader";
import babelLoader from "./loaders/babel.loader"; import babelLoader from "./loaders/babel.loader";
import { cssLoader, lessLoader } from "./loaders/style.loader"; import { cssLoader, lessLoader } from "./loaders/style.loader";
import CopyWebpackPlugin from "copy-webpack-plugin";
// 加载配置文件 // 加载配置文件
const envConfig = dotenv.config({ const envConfig = dotenv.config({
@ -40,11 +41,6 @@ const baseConfig: Configuration = {
"@": path.join(__dirname, "../src"), "@": path.join(__dirname, "../src"),
"@@": path.join(__dirname, "../core"), "@@": path.join(__dirname, "../core"),
}, },
// fallback: {
// crypto: require.resolve('crypto-browserify'),
// buffer: require.resolve("buffer/"),
// http: require.resolve("stream-http"),
// },
}, },
// plugins // plugins
plugins: [ plugins: [
@ -68,6 +64,22 @@ const baseConfig: Configuration = {
"process.env.BASE_ENV": JSON.stringify(process.env.BASE_ENV), "process.env.BASE_ENV": JSON.stringify(process.env.BASE_ENV),
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV), "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
}), }),
new CopyWebpackPlugin({
patterns: [
{
from: path.join(__dirname, "../", "node_modules", "web-workers"),
to: path.join(__dirname, "dist", "itk", "web-workers"),
},
{
from: path.join(__dirname, "../", "node_modules", "itk-image-io"),
to: path.join(__dirname, "dist", "itk", "image-io"),
},
{
from: path.join(__dirname, "../", "node_modules", "itk-mesh-io"),
to: path.join(__dirname, "dist", "itk", "mesh-io"),
},
],
}),
], ],
}; };

View File

@ -20,7 +20,7 @@ interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration; devServer?: WebpackDevServerConfiguration;
} }
const host = "127.0.0.1"; const host = "0.0.0.0";
const port = 9000; const port = 9000;
// 合并公共配置,并添加开发环境配置 // 合并公共配置,并添加开发环境配置

0
apps/aorta/src/global.d.ts vendored Normal file
View File

View File

@ -83,8 +83,8 @@ export const LoginForm = (props: LoginFormProps) => {
rules={[ rules={[
{ {
required: true, required: true,
pattern: REG.password, // pattern: REG.password,
min: 6, // min: 6,
max: 20, max: 20,
message: "6-20位包含 大写、小写、字母、特殊字符", message: "6-20位包含 大写、小写、字母、特殊字符",
}, },

View File

@ -14,8 +14,10 @@
position: relative; position: relative;
background-size: cover; background-size: cover;
background-position: center center; background-position: center center;
min-height: 6rem;
cursor: pointer; cursor: pointer;
img{
width: 100%;
}
&.active { &.active {
&::after { &::after {

View File

@ -38,18 +38,20 @@ export const ImageItem = (props: ImageItemProps) => {
const handleFileChange = (event: any) => { const handleFileChange = (event: any) => {
if (event.target.files && event.target.files[0]) { if (event.target.files && event.target.files[0]) {
const fd = new FormData();
fd.append("file", event.target.files[0]);
axios // const fd = new FormData();
.post("/api/report/upload", fd, { // fd.append("file", event.target.files[0]);
headers: { "Content-Type": "multipart/form-data" }, // axios
}) // .post("/api/report/upload", fd, {
.then((res) => { // headers: { "Content-Type": "multipart/form-data" },
const { objectName } = res.data; // })
setImgSrc(`/api/report/img/${objectName}`); // .then((res) => {
}); // const { objectName } = res.data;
// setImgSrc(`/api/report/img/${objectName}`);
// });
//TODO API接口上传THEN //TODO API接口上传THEN
setImgSrc(event.target.result); setImgSrc(URL.createObjectURL(event.target.files[0]));
} }
}; };
@ -63,8 +65,10 @@ export const ImageItem = (props: ImageItemProps) => {
onClick={() => setActionVisible(true)} onClick={() => setActionVisible(true)}
className={`img ${actionVisible ? "active" : ""}`} className={`img ${actionVisible ? "active" : ""}`}
ref={imgRef} ref={imgRef}
style={{ ...props.imgStyle, backgroundImage: `url(${imgSrc})` }} style={{ ...props.imgStyle }}
></div> >
<img src={imgSrc} />
</div>
)} )}
{actionVisible && ( {actionVisible && (
<section ref={actionRef}> <section ref={actionRef}>

View File

@ -1,13 +1,18 @@
.page-head { .page-head {
text-align: right; display: flex;
align-items: center;
justify-content: space-between;
line-height: 1; line-height: 1;
padding-bottom: 0.57rem; padding-bottom: 0.57rem;
border-bottom: 0.07rem solid var(--color-bg-primary); border-bottom: 0.07rem solid var(--color-bg-primary);
margin-bottom: 2rem; margin-bottom: 2rem;
>span{
color: red;
}
.logo-group { .logo-group {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
} }
} }

View File

@ -7,6 +7,7 @@ interface PaperHeadProps {
export const PaperHead = (props: PaperHeadProps) => { export const PaperHead = (props: PaperHeadProps) => {
return ( return (
<div className="page-head"> <div className="page-head">
<span>demo版本</span>
<div className="logo-group"> <div className="logo-group">
<svg <svg
viewBox="0 0 45 47" viewBox="0 0 45 47"

View File

@ -31,14 +31,14 @@ interface DoctorProps {
} }
export const ReportFullVersion = (props: DoctorProps) => { export const ReportFullVersion = (props: DoctorProps) => {
const [date, totalPageNum] = ["2023-06-14", 21]; const [date, totalPageNum] = ["2023-12-12", 18];
const [completed, setCompleted] = useState(0); const [completed, setCompleted] = useState(0);
useEffect(() => { // useEffect(() => {
axios.get("/api/aorta/report/root").then((res) => { // axios.get("/api/aorta/report/root").then((res) => {
console.log(res); // console.log(res);
}); // });
}, []); // }, []);
/** /**
* pdf * pdf

View File

@ -48,7 +48,6 @@ export const LeftCoronarySinus = (props: LeftCoronarySinusProps) => {
<ImageItem <ImageItem
title="左冠窦瓣叶长度" title="左冠窦瓣叶长度"
src={src} src={src}
imgStyle={{ height: "6.43rem" }}
/> />
<Reference <Reference
style={{ position: "absolute", bottom: "3rem" }} style={{ position: "absolute", bottom: "3rem" }}

View File

@ -31,7 +31,6 @@ export const NoCoronarySinus = (props: NoCoronarySinusProps) => {
<ImageItem <ImageItem
title="无冠窦瓣叶长度" title="无冠窦瓣叶长度"
src={src} src={src}
imgStyle={{ height: "6.43rem" }}
/> />
</div> </div>
); );

View File

@ -32,7 +32,6 @@ export const RightCoronarySinus = (props: RightCoronarySinusProps) => {
<ImageItem <ImageItem
title="左冠窦瓣叶长度" title="左冠窦瓣叶长度"
src={src} src={src}
imgStyle={{ height: "6.43rem" }}
/> />
</div> </div>
); );

View File

@ -0,0 +1,72 @@
import { metaData } from "@cornerstonejs/core";
import cornerstoneDICOMImageLoader from "@cornerstonejs/dicom-image-loader";
/**
* Preloads imageIds metadata in memory
**/
export const prefetchMetadataInformation = async (
imageIdsToPrefetch: string[]
): Promise<void> => {
for (let i = 0; i < imageIdsToPrefetch.length; i++) {
await cornerstoneDICOMImageLoader.wadouri.loadImage(imageIdsToPrefetch[i])
.promise;
}
};
interface FrameInformation {
frameIndex: number;
imageIdFrameless: string;
}
export const getFrameInformation = (imageId: string): FrameInformation => {
if (imageId.includes("wadors:")) {
const frameIndex = imageId.indexOf("/frames/");
const imageIdFrameless =
frameIndex > 0 ? imageId.slice(0, frameIndex + 8) : imageId;
return {
frameIndex,
imageIdFrameless,
};
} else {
const frameIndex = imageId.indexOf("&frame=");
let imageIdFrameless =
frameIndex > 0 ? imageId.slice(0, frameIndex + 7) : imageId;
if (!imageIdFrameless.includes("&frame=")) {
imageIdFrameless += "&frame=";
}
return {
frameIndex,
imageIdFrameless,
};
}
};
/**
* Converts a list of imageids possibly referring to multiframe dicom images
* into a list of imageids where each imageid refers to one frame.
* For each imageId representing a multiframe image with n frames,
* it creates n new imageids, one for each frame, and returns the new list of imageids.
* If a particular imageid does not refer to a multiframe image data, it will be just copied into the new list.
* @returns new list of imageids where each imageid represents a frame
*/
export const convertMultiframeImageIds = (imageIds: string[]): string[] => {
const newImageIds: string[] = [];
imageIds.forEach((imageId) => {
const { imageIdFrameless } = getFrameInformation(imageId);
const instanceMetaData = metaData.get("multiframeModule", imageId);
if (
instanceMetaData &&
instanceMetaData.NumberOfFrames &&
instanceMetaData.NumberOfFrames > 1
) {
const numberOfFrames = instanceMetaData.NumberOfFrames;
for (let i = 0; i < numberOfFrames; i++) {
const newImageId = imageIdFrameless + (i + 1);
newImageIds.push(newImageId);
}
} else {
newImageIds.push(imageId);
}
});
return newImageIds;
};

View File

@ -0,0 +1,139 @@
import { api } from "dicomweb-client";
import dcmjs from "dcmjs";
import { utilities } from "@cornerstonejs/core";
import cornerstoneDICOMImageLoader from "@cornerstonejs/dicom-image-loader";
import { getPixelSpacingInformation } from "./getPixelSpacingInformation";
import { convertMultiframeImageIds } from "./convertMultiframeImageIds";
import { removeInvalidTags } from "./removeInvalidTags";
import getPTImageIdInstanceMetadata from "./getPTImageIdInstanceMetadata";
import { calculateSUVScalingFactors } from "@cornerstonejs/calculate-suv";
import ptScalingMetaDataProvider from "./ptScalingMetaDataProvider";
const { DicomMetaDictionary } = dcmjs.data;
const { calibratedPixelSpacingMetadataProvider } = utilities;
const SOP_INSTANCE_UID = "00080018";
const SERIES_INSTANCE_UID = "0020000E";
const MODALITY = "00080060";
interface CreateImageIdsAndCacheMetaDataOptions {
StudyInstanceUID: string;
SeriesInstanceUID: string;
SOPInstanceUID?: string | null;
wadoRsRoot: string;
client?: api.DICOMwebClient | null;
}
/**
* DICOMweb ID
*
* @param options - DICOMweb
* @returns ID
*/
export const createImageIdsAndCacheMetaData = async (
options: CreateImageIdsAndCacheMetaDataOptions
): Promise<string[]> => {
const client =
options.client ||
new api.DICOMwebClient({ url: options.wadoRsRoot, singlepart: true });
try {
const instances = await client.retrieveSeriesMetadata({
studyInstanceUID: options.StudyInstanceUID,
seriesInstanceUID: options.SeriesInstanceUID,
});
const modality = (instances[0] as unknown as any)[MODALITY].Value[0];
console.log("modality", modality);
let imageIds = instances.map((instanceMetaData: any) => {
const SeriesInstanceUID = instanceMetaData[SERIES_INSTANCE_UID].Value[0];
const SOPInstanceUIDToUse =
options.SOPInstanceUID || instanceMetaData[SOP_INSTANCE_UID].Value[0];
const prefix = "wadors:";
const imageId =
prefix +
options.wadoRsRoot +
"/studies/" +
options.StudyInstanceUID +
"/series/" +
SeriesInstanceUID +
"/instances/" +
SOPInstanceUIDToUse +
"/frames/1";
cornerstoneDICOMImageLoader.wadors.metaDataManager.add(
imageId,
instanceMetaData
);
return imageId;
});
imageIds = convertMultiframeImageIds(imageIds);
imageIds.forEach((imageId) => {
let instanceMetaData =
cornerstoneDICOMImageLoader.wadors.metaDataManager.get(imageId);
instanceMetaData = removeInvalidTags(instanceMetaData);
if (instanceMetaData) {
const metadata =
DicomMetaDictionary.naturalizeDataset(instanceMetaData);
const pixelSpacing = getPixelSpacingInformation(metadata) as Number[];
if (pixelSpacing) {
// FIXME: cornerstone类型定义有问题这里.add方法缺少type属性
calibratedPixelSpacingMetadataProvider.add(imageId, {
// @ts-ignore
rowPixelSpacing: pixelSpacing[0],
// @ts-ignore
columnPixelSpacing: pixelSpacing[1],
});
}
}
});
if (modality === "PT") {
const InstanceMetadataArray: any = [];
imageIds.forEach((imageId) => {
const instanceMetadata = getPTImageIdInstanceMetadata(imageId);
// TODO: Temporary fix because static-wado is producing a string, not an array of values
// (or maybe dcmjs isn't parsing it correctly?)
// It's showing up like 'DECY\\ATTN\\SCAT\\DTIM\\RAN\\RADL\\DCAL\\SLSENS\\NORM'
// but calculate-suv expects ['DECY', 'ATTN', ...]
if (typeof instanceMetadata.CorrectedImage === "string") {
instanceMetadata.CorrectedImage =
instanceMetadata.CorrectedImage.split("\\");
}
if (instanceMetadata) {
InstanceMetadataArray.push(instanceMetadata);
}
});
if (InstanceMetadataArray.length) {
try {
const suvScalingFactors = calculateSUVScalingFactors(
InstanceMetadataArray
);
InstanceMetadataArray.forEach((instanceMetadata, index) => {
ptScalingMetaDataProvider.addInstance(
imageIds[index],
suvScalingFactors[index]
);
});
} catch (error) {
console.log(error);
}
}
}
return imageIds;
} catch (error) {
console.log(error);
throw new Error("PACS 中数据不存在");
}
};

View File

@ -0,0 +1,211 @@
import { metaData } from "@cornerstonejs/core";
import type { InstanceMetadata } from "@cornerstonejs/calculate-suv";
export default function getPTImageIdInstanceMetadata(
imageId: string
): InstanceMetadata {
const petSequenceModule = metaData.get("petIsotopeModule", imageId);
const generalSeriesModule = metaData.get("generalSeriesModule", imageId);
const patientStudyModule = metaData.get("patientStudyModule", imageId);
const ptSeriesModule = metaData.get("petSeriesModule", imageId);
const ptImageModule = metaData.get("petImageModule", imageId);
if (!petSequenceModule) {
throw new Error("petSequenceModule metadata is required");
}
const radiopharmaceuticalInfo = petSequenceModule.radiopharmaceuticalInfo;
const { seriesDate, seriesTime, acquisitionDate, acquisitionTime } =
generalSeriesModule;
const { patientWeight } = patientStudyModule;
const { correctedImage, units, decayCorrection } = ptSeriesModule;
if (
seriesDate === undefined ||
seriesTime === undefined ||
patientWeight === undefined ||
acquisitionDate === undefined ||
acquisitionTime === undefined ||
correctedImage === undefined ||
units === undefined ||
decayCorrection === undefined ||
radiopharmaceuticalInfo.radionuclideTotalDose === undefined ||
radiopharmaceuticalInfo.radionuclideHalfLife === undefined ||
(radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime === undefined &&
seriesDate === undefined &&
radiopharmaceuticalInfo.radiopharmaceuticalStartTime === undefined)
//
) {
throw new Error("required metadata are missing");
}
const instanceMetadata: InstanceMetadata = {
CorrectedImage: correctedImage,
Units: units,
RadionuclideHalfLife: radiopharmaceuticalInfo.radionuclideHalfLife,
RadionuclideTotalDose: radiopharmaceuticalInfo.radionuclideTotalDose,
DecayCorrection: decayCorrection,
PatientWeight: patientWeight,
SeriesDate: seriesDate,
SeriesTime: seriesTime,
AcquisitionDate: acquisitionDate,
AcquisitionTime: acquisitionTime,
};
if (
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime &&
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== undefined &&
typeof radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime === "string"
) {
instanceMetadata.RadiopharmaceuticalStartDateTime =
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime;
}
if (
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime &&
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== undefined &&
typeof radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== "string"
) {
const dateString = convertInterfaceDateToString(
radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime
);
instanceMetadata.RadiopharmaceuticalStartDateTime = dateString;
}
if (
instanceMetadata.AcquisitionDate &&
instanceMetadata.AcquisitionDate !== undefined &&
typeof instanceMetadata.AcquisitionDate !== "string"
) {
const dateString = convertInterfaceDateToString(
instanceMetadata.AcquisitionDate
);
instanceMetadata.AcquisitionDate = dateString;
}
if (
instanceMetadata.SeriesDate &&
instanceMetadata.SeriesDate !== undefined &&
typeof instanceMetadata.SeriesDate !== "string"
) {
const dateString = convertInterfaceDateToString(
instanceMetadata.SeriesDate
);
instanceMetadata.SeriesDate = dateString;
}
if (
radiopharmaceuticalInfo.radiopharmaceuticalStartTime &&
radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== undefined &&
typeof radiopharmaceuticalInfo.radiopharmaceuticalStartTime === "string"
) {
instanceMetadata.RadiopharmaceuticalStartTime =
radiopharmaceuticalInfo.radiopharmaceuticalStartTime;
}
if (
radiopharmaceuticalInfo.radiopharmaceuticalStartTime &&
radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== undefined &&
typeof radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== "string"
) {
const timeString = convertInterfaceTimeToString(
radiopharmaceuticalInfo.radiopharmaceuticalStartTime
);
instanceMetadata.RadiopharmaceuticalStartTime = timeString;
}
if (
instanceMetadata.AcquisitionTime &&
instanceMetadata.AcquisitionTime !== undefined &&
typeof instanceMetadata.AcquisitionTime !== "string"
) {
const timeString = convertInterfaceTimeToString(
instanceMetadata.AcquisitionTime
);
instanceMetadata.AcquisitionTime = timeString;
}
if (
instanceMetadata.SeriesTime &&
instanceMetadata.SeriesTime !== undefined &&
typeof instanceMetadata.SeriesTime !== "string"
) {
const timeString = convertInterfaceTimeToString(
instanceMetadata.SeriesTime
);
instanceMetadata.SeriesTime = timeString;
}
if (
ptImageModule.frameReferenceTime &&
ptImageModule.frameReferenceTime !== undefined
) {
instanceMetadata.FrameReferenceTime = ptImageModule.frameReferenceTime;
}
if (
ptImageModule.actualFrameDuration &&
ptImageModule.actualFrameDuration !== undefined
) {
instanceMetadata.ActualFrameDuration = ptImageModule.actualFrameDuration;
}
if (
patientStudyModule.patientSex &&
patientStudyModule.patientSex !== undefined
) {
instanceMetadata.PatientSex = patientStudyModule.patientSex;
}
if (
patientStudyModule.patientSize &&
patientStudyModule.patientSize !== undefined
) {
instanceMetadata.PatientSize = patientStudyModule.patientSize;
}
// Todo: add private tags
// if (
// dicomMetaData['70531000'] ||
// dicomMetaData['70531000'] !== undefined ||
// dicomMetaData['70531009'] ||
// dicomMetaData['70531009'] !== undefined
// ) {
// const philipsPETPrivateGroup: PhilipsPETPrivateGroup = {
// SUVScaleFactor: dicomMetaData['70531000'],
// ActivityConcentrationScaleFactor: dicomMetaData['70531009'],
// };
// instanceMetadata.PhilipsPETPrivateGroup = philipsPETPrivateGroup;
// }
// if (dicomMetaData['0009100d'] && dicomMetaData['0009100d'] !== undefined) {
// instanceMetadata.GEPrivatePostInjectionDateTime = dicomMetaData['0009100d'];
// }
return instanceMetadata;
}
function convertInterfaceTimeToString(time): string {
const hours = `${time.hours || "00"}`.padStart(2, "0");
const minutes = `${time.minutes || "00"}`.padStart(2, "0");
const seconds = `${time.seconds || "00"}`.padStart(2, "0");
const fractionalSeconds = `${time.fractionalSeconds || "000000"}`.padEnd(
6,
"0"
);
const timeString = `${hours}${minutes}${seconds}.${fractionalSeconds}`;
return timeString;
}
function convertInterfaceDateToString(date): string {
const month = `${date.month}`.padStart(2, "0");
const day = `${date.day}`.padStart(2, "0");
const dateString = `${date.year}${month}${day}`;
return dateString;
}
export { getPTImageIdInstanceMetadata };

View File

@ -0,0 +1,139 @@
interface DICOMInstance {
PixelSpacing?: number[];
ImagerPixelSpacing?: number[];
SOPClassUID?: string;
PixelSpacingCalibrationType?: string;
PixelSpacingCalibrationDescription?: string;
EstimatedRadiographicMagnificationFactor?: number;
SequenceOfUltrasoundRegions?: {
PhysicalDeltaX: number;
PhysicalDeltaY: number;
}[]; // 根据实际需要调整类型
}
interface PixelSpacingResult {
PixelSpacing?: number[];
type?: string;
isProjection?: boolean;
PixelSpacingCalibrationType?: string;
PixelSpacingCalibrationDescription?: string;
}
/**
*
* DICOM
*
* @param instance - DICOM
* @returns
*/
export const getPixelSpacingInformation = (
instance: DICOMInstance
): PixelSpacingResult | number[] | undefined => {
const projectionRadiographSOPClassUIDs: string[] = [
"1.2.840.10008.5.1.4.1.1.1", // CR Image Storage
"1.2.840.10008.5.1.4.1.1.1.1", // Digital X-Ray Image Storage for Presentation
"1.2.840.10008.5.1.4.1.1.1.1.1", // Digital X-Ray Image Storage for Processing
"1.2.840.10008.5.1.4.1.1.1.2", // Digital Mammography X-Ray Image Storage for Presentation
"1.2.840.10008.5.1.4.1.1.1.2.1", // Digital Mammography X-Ray Image Storage for Processing
"1.2.840.10008.5.1.4.1.1.1.3", // Digital Intra oral X-Ray Image Storage for Presentation
"1.2.840.10008.5.1.4.1.1.1.3.1", // Digital Intra oral X-Ray Image Storage for Processing
"1.2.840.10008.5.1.4.1.1.12.1", // X-Ray Angiographic Image Storage
"1.2.840.10008.5.1.4.1.1.12.1.1", // Enhanced XA Image Storage
"1.2.840.10008.5.1.4.1.1.12.2", // X-Ray Radiofluoroscopic Image Storage
"1.2.840.10008.5.1.4.1.1.12.2.1", // Enhanced XRF Image Storage
"1.2.840.10008.5.1.4.1.1.12.3", // X-Ray Angiographic Bi-plane Image Storage Retired
];
const {
PixelSpacing,
ImagerPixelSpacing,
SOPClassUID,
PixelSpacingCalibrationType,
PixelSpacingCalibrationDescription,
EstimatedRadiographicMagnificationFactor,
SequenceOfUltrasoundRegions,
} = instance;
const isProjection = SOPClassUID
? projectionRadiographSOPClassUIDs.includes(SOPClassUID)
: false;
const TYPES = {
NOT_APPLICABLE: "NOT_APPLICABLE",
UNKNOWN: "UNKNOWN",
CALIBRATED: "CALIBRATED",
DETECTOR: "DETECTOR",
};
if (!isProjection) {
return PixelSpacing;
}
if (isProjection && !ImagerPixelSpacing) {
return {
PixelSpacing,
type: TYPES.UNKNOWN,
isProjection,
};
} else if (
PixelSpacing &&
ImagerPixelSpacing &&
PixelSpacing.join() === ImagerPixelSpacing.join()
) {
return {
PixelSpacing,
type: TYPES.DETECTOR,
isProjection,
};
} else if (
PixelSpacing &&
ImagerPixelSpacing &&
PixelSpacing.join() !== ImagerPixelSpacing.join()
) {
return {
PixelSpacing,
type: TYPES.CALIBRATED,
isProjection,
PixelSpacingCalibrationType,
PixelSpacingCalibrationDescription,
};
} else if (!PixelSpacing && ImagerPixelSpacing) {
let CorrectedImagerPixelSpacing = ImagerPixelSpacing;
if (EstimatedRadiographicMagnificationFactor) {
CorrectedImagerPixelSpacing = ImagerPixelSpacing.map(
(pixelSpacing) =>
pixelSpacing / EstimatedRadiographicMagnificationFactor
);
} else {
console.warn(
"EstimatedRadiographicMagnificationFactor was not present. Unable to correct ImagerPixelSpacing."
);
}
return {
PixelSpacing: CorrectedImagerPixelSpacing,
isProjection,
};
} else if (
SequenceOfUltrasoundRegions &&
Array.isArray(SequenceOfUltrasoundRegions) &&
SequenceOfUltrasoundRegions.length > 0
) {
const { PhysicalDeltaX, PhysicalDeltaY } = SequenceOfUltrasoundRegions[0];
const USPixelSpacing = [PhysicalDeltaX * 10, PhysicalDeltaY * 10];
return {
PixelSpacing: USPixelSpacing,
};
} else if (isProjection && !ImagerPixelSpacing) {
return {
PixelSpacing,
type: TYPES.NOT_APPLICABLE,
isProjection,
};
}
console.warn(
"Unknown combination of PixelSpacing and ImagerPixelSpacing identified. Unable to determine spacing."
);
};

View File

@ -0,0 +1,10 @@
import { initCornerstoneDICOMImageLoader } from "./initCornerstoneDicomImageLoader";
import initVolumeLoader from "./initVolumeLoader";
import { init as csRenderInit } from "@cornerstonejs/core";
// 入口
export const initCornerstone = async () => {
initCornerstoneDICOMImageLoader();
initVolumeLoader();
await csRenderInit();
};

View File

@ -0,0 +1,46 @@
import dicomParser from "dicom-parser";
import * as cornerstone from "@cornerstonejs/core";
import cornerstoneDICOMImageLoader from "@cornerstonejs/dicom-image-loader";
window.cornerstone = cornerstone;
export const initCornerstoneDICOMImageLoader = () => {
const { preferSizeOverAccuracy, useNorm16Texture } =
cornerstone.getConfiguration().rendering;
cornerstone.setConfiguration({
detectGPUConfig: {
benchmarksURL: "http://localhost:9000",
},
rendering: cornerstone.getConfiguration().rendering,
});
cornerstoneDICOMImageLoader.external.cornerstone = cornerstone;
cornerstoneDICOMImageLoader.external.dicomParser = dicomParser;
cornerstoneDICOMImageLoader.configure({
useWebWorkers: true,
decodeConfig: {
convertFloatPixelDataToInt: false,
use16BitDataType: preferSizeOverAccuracy || useNorm16Texture,
},
});
let maxWebWorkers = 1;
if (navigator.hardwareConcurrency) {
maxWebWorkers = Math.min(navigator.hardwareConcurrency, 7);
}
const config = {
maxWebWorkers,
startWebWorkersOnDemand: false,
taskConfiguration: {
decodeTask: {
initializeCodecsOnStartup: false,
strict: false,
},
},
};
cornerstoneDICOMImageLoader.webWorkerManager.initialize(config);
};

View File

@ -0,0 +1,17 @@
import * as cornerstone from "@cornerstonejs/core";
import ptScalingMetaDataProvider from "./ptScalingMetaDataProvider";
const { calibratedPixelSpacingMetadataProvider } = cornerstone.utilities;
export default function initProviders() {
cornerstone.metaData.addProvider(
ptScalingMetaDataProvider.get.bind(ptScalingMetaDataProvider),
10000
);
cornerstone.metaData.addProvider(
calibratedPixelSpacingMetadataProvider.get.bind(
calibratedPixelSpacingMetadataProvider
),
11000
);
}

View File

@ -0,0 +1,19 @@
import { volumeLoader } from "@cornerstonejs/core";
import {
cornerstoneStreamingImageVolumeLoader,
cornerstoneStreamingDynamicImageVolumeLoader,
} from "@cornerstonejs/streaming-image-volume-loader";
export default function initVolumeLoader() {
volumeLoader.registerUnknownVolumeLoader(
cornerstoneStreamingImageVolumeLoader
);
volumeLoader.registerVolumeLoader(
"cornerstoneStreamingImageVolume",
cornerstoneStreamingImageVolumeLoader
);
volumeLoader.registerVolumeLoader(
"cornerstoneStreamingDynamicImageVolume",
cornerstoneStreamingDynamicImageVolumeLoader
);
}

View File

@ -0,0 +1,17 @@
import { utilities as csUtils } from "@cornerstonejs/core";
const scalingPerImageId = {};
function addInstance(imageId, scalingMetaData) {
const imageURI = csUtils.imageIdToURI(imageId);
scalingPerImageId[imageURI] = scalingMetaData;
}
function get(type, imageId) {
if (type === "scalingModule") {
const imageURI = csUtils.imageIdToURI(imageId);
return scalingPerImageId[imageURI];
}
}
export default { addInstance, get };

View File

@ -0,0 +1,33 @@
/**
* Removes invalid tags from a metadata object and returns a new object.
*
* This function currently removes tags that have `null` or `undefined` values.
* Removing these values is important to prevent errors when processing
* the metadata, such as when calling `naturalizeDataset(...)`.
*
* The performance of this function has been considered. Validating each
* tag ID with a regex significantly reduces the function's speed, so this
* approach is avoided. The function is designed to be efficient, with an
* average runtime of around +12ms per 1000 images, though this can vary
* depending on the machine.
*
* @param srcMetadata - The source metadata object containing the tags.
* @returns A new metadata object with invalid tags removed.
*/
export const removeInvalidTags = (
srcMetadata: Record<string, any>
): Record<string, any> => {
const dstMetadata: Record<string, any> = Object.create(null);
const tagIds = Object.keys(srcMetadata);
let tagValue: any;
tagIds.forEach((tagId) => {
tagValue = srcMetadata[tagId];
if (tagValue !== undefined && tagValue !== null) {
dstMetadata[tagId] = tagValue;
}
});
return dstMetadata;
};

View File

@ -0,0 +1,243 @@
import { useEffect, useRef } from "react";
import initDemo from "./util/initDemo.js";
import {
RenderingEngine,
Types,
Enums,
setVolumesForViewports,
volumeLoader,
getRenderingEngine,
} from "@cornerstonejs/core";
import * as cornerstoneTools from "@cornerstonejs/tools";
import createImageIdsAndCacheMetaData from "./util/createImageIdsAndCacheMetaData";
import { PublicViewportInput } from "@cornerstonejs/core/dist/types/types/IViewport.js";
import setCtTransferFunctionForVolumeActor from "./util/setCtTransferFunctionForVolumeActor";
import * as cornerstone from "@cornerstonejs/core";
const {
ToolGroupManager,
Enums: csToolsEnums,
CrosshairsTool,
StackScrollMouseWheelTool,
} = cornerstoneTools;
const { ViewportType } = Enums;
interface CrosshairMprProps {
children?: JSX.Element;
}
const viewportId1 = "CT_AXIAL";
const viewportId2 = "CT_SAGITTAL";
const viewportId3 = "CT_CORONAL";
const toolGroupId = "group";
const viewportColors = {
[viewportId1]: "rgb(200, 0, 0)",
[viewportId2]: "rgb(200, 200, 0)",
[viewportId3]: "rgb(0, 200, 0)",
};
const viewportReferenceLineControllable = [
viewportId1,
viewportId2,
viewportId3,
];
const viewportReferenceLineDraggableRotatable = [
viewportId1,
viewportId2,
viewportId3,
];
const viewportReferenceLineSlabThicknessControlsOn = [
viewportId1,
viewportId2,
viewportId3,
];
// Define a unique id for the volume
const volumeName = "CT_VOLUME_ID"; // Id of the volume less loader prefix
const volumeLoaderScheme = "cornerstoneStreamingImageVolume"; // Loader id which defines which volume loader to use
const volumeId = `${volumeLoaderScheme}:${volumeName}`; // VolumeId with loader id + volume id
function getReferenceLineColor(viewportId) {
return viewportColors[viewportId];
}
function getReferenceLineControllable(viewportId) {
const index = viewportReferenceLineControllable.indexOf(viewportId);
return index !== -1;
}
function getReferenceLineDraggableRotatable(viewportId) {
const index = viewportReferenceLineDraggableRotatable.indexOf(viewportId);
return index !== -1;
}
function getReferenceLineSlabThicknessControlsOn(viewportId) {
const index =
viewportReferenceLineSlabThicknessControlsOn.indexOf(viewportId);
return index !== -1;
}
const renderingEngineId = "myRenderingEngine";
export const CrosshairMpr = (props: CrosshairMprProps) => {
const viewportId1Ref = useRef(null);
const viewportId2Ref = useRef(null);
const viewportId3Ref = useRef(null);
const renderingEngine = useRef<RenderingEngine>();
const imageIds = useRef<string[]>();
const run = async () => {
initDemo();
// Get Cornerstone imageIds for the source data and fetch metadata into RAM
imageIds.current = await createImageIdsAndCacheMetaData({
StudyInstanceUID:
"1.2.840.113564.345049290535.9692.637552042156233117.433089",
SeriesInstanceUID:
"1.3.12.2.1107.5.1.4.76315.30000021042706150001900118311",
wadoRsRoot: "/dicom-web",
});
// Define a volume in memory
const volume = await volumeLoader.createAndCacheVolume(volumeId, {
imageIds: imageIds.current ?? [],
});
// Instantiate a rendering engine
renderingEngine.current = new RenderingEngine(renderingEngineId);
// Create the viewports
const viewportInputArray: PublicViewportInput[] = [
{
viewportId: viewportId1,
type: ViewportType.ORTHOGRAPHIC,
element: viewportId1Ref.current!,
defaultOptions: {
orientation: Enums.OrientationAxis.AXIAL,
background: [0, 0, 0],
},
},
{
viewportId: viewportId2,
type: ViewportType.ORTHOGRAPHIC,
element: viewportId2Ref.current!,
defaultOptions: {
orientation: Enums.OrientationAxis.SAGITTAL,
background: [0, 0, 0],
},
},
{
viewportId: viewportId3,
type: ViewportType.ORTHOGRAPHIC,
element: viewportId3Ref.current!,
defaultOptions: {
orientation: Enums.OrientationAxis.CORONAL,
background: [0, 0, 0],
},
},
];
renderingEngine.current.setViewports(viewportInputArray);
console.log(volume);
// Set the volume to load
volume.load();
// Set volumes on the viewports
await setVolumesForViewports(
renderingEngine.current,
[
{
volumeId,
callback: setCtTransferFunctionForVolumeActor,
},
],
[viewportId1, viewportId2, viewportId3]
);
// Define tool groups to add the segmentation display tool to
const toolGroup = ToolGroupManager.createToolGroup(toolGroupId);
if (toolGroup) {
// For the crosshairs to operate, the viewports must currently be
// added ahead of setting the tool active. This will be improved in the future.
toolGroup.addViewport(viewportId1, renderingEngineId);
toolGroup.addViewport(viewportId2, renderingEngineId);
toolGroup.addViewport(viewportId3, renderingEngineId);
// Manipulation Tools
toolGroup.addTool(StackScrollMouseWheelTool.toolName);
// Add Crosshairs tool and configure it to link the three viewports
// These viewports could use different tool groups. See the PET-CT example
// for a more complicated used case.
toolGroup.addTool(CrosshairsTool.toolName, {
getReferenceLineColor,
getReferenceLineControllable,
getReferenceLineDraggableRotatable,
getReferenceLineSlabThicknessControlsOn,
});
toolGroup.setToolActive(CrosshairsTool.toolName, {
bindings: [{ mouseButton: 1 }],
});
// As the Stack Scroll mouse wheel is a tool using the `mouseWheelCallback`
// hook instead of mouse buttons, it does not need to assign any mouse button.
toolGroup.setToolActive(StackScrollMouseWheelTool.toolName);
}
renderingEngine.current.renderViewports([
viewportId1,
viewportId2,
viewportId3,
]);
};
useEffect(() => {
cornerstoneTools.addTool(StackScrollMouseWheelTool);
cornerstoneTools.addTool(CrosshairsTool);
console.log("添加tool1");
run();
return () => {
// TODO: 是否需要写在组件,根据页面需要
console.log("卸载tool2");
cornerstoneTools.removeTool(StackScrollMouseWheelTool);
cornerstoneTools.removeTool(CrosshairsTool);
};
}, []);
useEffect(() => {
window.addEventListener("resize", () => {
renderingEngine.current?.resize();
});
}, []);
const test = () => {
// console.log(volumeLoader)
console.log(cornerstone.cache.getVolume(volumeId).getScalarData());
};
useEffect(() => {
document.addEventListener(Enums.Events.VOLUME_CACHE_VOLUME_ADDED, () => {
console.log(111);
});
}, []);
return (
<div>
<div style={{ display: "flex", gap: 20 }}>
<div style={{ width: 300, height: 300 }} ref={viewportId1Ref}></div>
<div style={{ width: 300, height: 300 }} ref={viewportId2Ref}></div>
<div style={{ width: 300, height: 300 }} ref={viewportId3Ref}></div>
</div>
<button onClick={test}></button>
</div>
);
};

View File

@ -0,0 +1,65 @@
import { metaData } from '@cornerstonejs/core';
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
/**
* preloads imageIds metadata in memory
**/
async function prefetchMetadataInformation(imageIdsToPrefetch) {
for (let i = 0; i < imageIdsToPrefetch.length; i++) {
await cornerstoneDICOMImageLoader.wadouri.loadImage(imageIdsToPrefetch[i])
.promise;
}
}
function getFrameInformation(imageId) {
if (imageId.includes('wadors:')) {
const frameIndex = imageId.indexOf('/frames/');
const imageIdFrameless =
frameIndex > 0 ? imageId.slice(0, frameIndex + 8) : imageId;
return {
frameIndex,
imageIdFrameless,
};
} else {
const frameIndex = imageId.indexOf('&frame=');
let imageIdFrameless =
frameIndex > 0 ? imageId.slice(0, frameIndex + 7) : imageId;
if (!imageIdFrameless.includes('&frame=')) {
imageIdFrameless = imageIdFrameless + '&frame=';
}
return {
frameIndex,
imageIdFrameless,
};
}
}
/**
* Receives a list of imageids possibly referring to multiframe dicom images
* and returns a list of imageid where each imageid referes to one frame.
* For each imageId representing a multiframe image with n frames,
* it will create n new imageids, one for each frame, and returns the new list of imageids
* If a particular imageid no refer to a mutiframe image data, it will be just copied into the new list
* @returns new list of imageids where each imageid represents a frame
*/
function convertMultiframeImageIds(imageIds) {
const newImageIds = [];
imageIds.forEach((imageId) => {
const { imageIdFrameless } = getFrameInformation(imageId);
const instanceMetaData = metaData.get('multiframeModule', imageId);
if (
instanceMetaData &&
instanceMetaData.NumberOfFrames &&
instanceMetaData.NumberOfFrames > 1
) {
const NumberOfFrames = instanceMetaData.NumberOfFrames;
for (let i = 0; i < NumberOfFrames; i++) {
const newImageId = imageIdFrameless + (i + 1);
newImageIds.push(newImageId);
}
} else {
newImageIds.push(imageId);
}
});
return newImageIds;
}
export { convertMultiframeImageIds, prefetchMetadataInformation };

View File

@ -0,0 +1,101 @@
import { api } from 'dicomweb-client';
import dcmjs from 'dcmjs';
import { utilities } from '@cornerstonejs/core';
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
import getPixelSpacingInformation from './getPixelSpacingInformation';
import { convertMultiframeImageIds } from './convertMultiframeImageIds';
import removeInvalidTags from './removeInvalidTags';
const { DicomMetaDictionary } = dcmjs.data;
const { calibratedPixelSpacingMetadataProvider } = utilities;
/**
/**
* Uses dicomweb-client to fetch metadata of a study, cache it in cornerstone,
* and return a list of imageIds for the frames.
*
* Uses the app config to choose which study to fetch, and which
* dicom-web server to fetch it from.
*
* @returns {string[]} An array of imageIds for instances in the study.
*/
export default async function createImageIdsAndCacheMetaData({
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID = null,
wadoRsRoot,
client = null,
}) {
const SOP_INSTANCE_UID = '00080018';
const SERIES_INSTANCE_UID = '0020000E';
const MODALITY = '00080060';
const studySearchOptions = {
studyInstanceUID: StudyInstanceUID,
seriesInstanceUID: SeriesInstanceUID,
};
client = client || new api.DICOMwebClient({ url: wadoRsRoot });
let instances = await client.retrieveSeriesMetadata(studySearchOptions);
// if sop instance is provided we should filter the instances to only include the one we want
if (SOPInstanceUID) {
instances = instances.filter((instance) => {
return instance[SOP_INSTANCE_UID].Value[0] === SOPInstanceUID;
});
}
const modality = instances[0][MODALITY].Value[0];
let imageIds = instances.map((instanceMetaData) => {
const SeriesInstanceUID = instanceMetaData[SERIES_INSTANCE_UID].Value[0];
const SOPInstanceUIDToUse =
SOPInstanceUID || instanceMetaData[SOP_INSTANCE_UID].Value[0];
const prefix = 'wadors:';
const imageId =
prefix +
wadoRsRoot +
'/studies/' +
StudyInstanceUID +
'/series/' +
SeriesInstanceUID +
'/instances/' +
SOPInstanceUIDToUse +
'/frames/1';
cornerstoneDICOMImageLoader.wadors.metaDataManager.add(
imageId,
instanceMetaData
);
return imageId;
});
// if the image ids represent multiframe information, creates a new list with one image id per frame
// if not multiframe data available, just returns the same list given
imageIds = convertMultiframeImageIds(imageIds);
imageIds.forEach((imageId) => {
let instanceMetaData =
cornerstoneDICOMImageLoader.wadors.metaDataManager.get(imageId);
// It was using JSON.parse(JSON.stringify(...)) before but it is 8x slower
instanceMetaData = removeInvalidTags(instanceMetaData);
if (instanceMetaData) {
// Add calibrated pixel spacing
const metadata = DicomMetaDictionary.naturalizeDataset(instanceMetaData);
const pixelSpacing = getPixelSpacingInformation(metadata);
if (pixelSpacing) {
calibratedPixelSpacingMetadataProvider.add(imageId, {
rowPixelSpacing: parseFloat(pixelSpacing[0]),
columnPixelSpacing: parseFloat(pixelSpacing[1]),
});
}
}
});
return imageIds;
}

View File

@ -0,0 +1,136 @@
// See https://github.com/OHIF/Viewers/blob/94a9067fe3d291d30e25a1bda5913511388edea2/platform/core/src/utils/metadataProvider/getPixelSpacingInformation.js
export default function getPixelSpacingInformation(instance) {
// See http://gdcm.sourceforge.net/wiki/index.php/Imager_Pixel_Spacing
// TODO: Add Ultrasound region spacing
// TODO: Add manual calibration
// TODO: Use ENUMS from dcmjs
const projectionRadiographSOPClassUIDs = [
'1.2.840.10008.5.1.4.1.1.1', // CR Image Storage
'1.2.840.10008.5.1.4.1.1.1.1', // Digital X-Ray Image Storage for Presentation
'1.2.840.10008.5.1.4.1.1.1.1.1', // Digital X-Ray Image Storage for Processing
'1.2.840.10008.5.1.4.1.1.1.2', // Digital Mammography X-Ray Image Storage for Presentation
'1.2.840.10008.5.1.4.1.1.1.2.1', // Digital Mammography X-Ray Image Storage for Processing
'1.2.840.10008.5.1.4.1.1.1.3', // Digital Intra oral X-Ray Image Storage for Presentation
'1.2.840.10008.5.1.4.1.1.1.3.1', // Digital Intra oral X-Ray Image Storage for Processing
'1.2.840.10008.5.1.4.1.1.12.1', // X-Ray Angiographic Image Storage
'1.2.840.10008.5.1.4.1.1.12.1.1', // Enhanced XA Image Storage
'1.2.840.10008.5.1.4.1.1.12.2', // X-Ray Radiofluoroscopic Image Storage
'1.2.840.10008.5.1.4.1.1.12.2.1', // Enhanced XRF Image Storage
'1.2.840.10008.5.1.4.1.1.12.3', // X-Ray Angiographic Bi-plane Image Storage Retired
];
const {
PixelSpacing,
ImagerPixelSpacing,
SOPClassUID,
PixelSpacingCalibrationType,
PixelSpacingCalibrationDescription,
EstimatedRadiographicMagnificationFactor,
SequenceOfUltrasoundRegions,
} = instance;
const isProjection = projectionRadiographSOPClassUIDs.includes(SOPClassUID);
const TYPES = {
NOT_APPLICABLE: 'NOT_APPLICABLE',
UNKNOWN: 'UNKNOWN',
CALIBRATED: 'CALIBRATED',
DETECTOR: 'DETECTOR',
};
if (!isProjection) {
return PixelSpacing;
}
if (isProjection && !ImagerPixelSpacing) {
// If only Pixel Spacing is present, and this is a projection radiograph,
// PixelSpacing should be used, but the user should be informed that
// what it means is unknown
return {
PixelSpacing,
type: TYPES.UNKNOWN,
isProjection,
};
} else if (
PixelSpacing &&
ImagerPixelSpacing &&
PixelSpacing === ImagerPixelSpacing
) {
// If Imager Pixel Spacing and Pixel Spacing are present and they have the same values,
// then the user should be informed that the measurements are at the detector plane
return {
PixelSpacing,
type: TYPES.DETECTOR,
isProjection,
};
} else if (
PixelSpacing &&
ImagerPixelSpacing &&
PixelSpacing !== ImagerPixelSpacing
) {
// If Imager Pixel Spacing and Pixel Spacing are present and they have different values,
// then the user should be informed that these are "calibrated"
// (in some unknown manner if Pixel Spacing Calibration Type and/or
// Pixel Spacing Calibration Description are absent)
return {
PixelSpacing,
type: TYPES.CALIBRATED,
isProjection,
PixelSpacingCalibrationType,
PixelSpacingCalibrationDescription,
};
} else if (!PixelSpacing && ImagerPixelSpacing) {
let CorrectedImagerPixelSpacing = ImagerPixelSpacing;
if (EstimatedRadiographicMagnificationFactor) {
// Note that in IHE Mammo profile compliant displays, the value of Imager Pixel Spacing is required to be corrected by
// Estimated Radiographic Magnification Factor and the user informed of that.
// TODO: should this correction be done before all of this logic?
CorrectedImagerPixelSpacing = ImagerPixelSpacing.map(
(pixelSpacing) =>
pixelSpacing / EstimatedRadiographicMagnificationFactor
);
} else {
console.warn(
'EstimatedRadiographicMagnificationFactor was not present. Unable to correct ImagerPixelSpacing.'
);
}
return {
PixelSpacing: CorrectedImagerPixelSpacing,
isProjection,
};
} else if (
SequenceOfUltrasoundRegions &&
typeof SequenceOfUltrasoundRegions === 'object'
) {
const { PhysicalDeltaX, PhysicalDeltaY } = SequenceOfUltrasoundRegions;
const USPixelSpacing = [PhysicalDeltaX * 10, PhysicalDeltaY * 10];
return {
PixelSpacing: USPixelSpacing,
};
} else if (
SequenceOfUltrasoundRegions &&
Array.isArray(SequenceOfUltrasoundRegions) &&
SequenceOfUltrasoundRegions.length > 1
) {
console.warn(
'Sequence of Ultrasound Regions > one entry. This is not yet implemented, all measurements will be shown in pixels.'
);
} else if (isProjection === false && !ImagerPixelSpacing) {
// If only Pixel Spacing is present, and this is not a projection radiograph,
// we can stop here
return {
PixelSpacing,
type: TYPES.NOT_APPLICABLE,
isProjection,
};
}
console.warn(
'Unknown combination of PixelSpacing and ImagerPixelSpacing identified. Unable to determine spacing.'
);
}

View File

@ -0,0 +1,41 @@
import dicomParser from 'dicom-parser';
import * as cornerstone from '@cornerstonejs/core';
import * as cornerstoneTools from '@cornerstonejs/tools';
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
window.cornerstone = cornerstone;
window.cornerstoneTools = cornerstoneTools;
const { preferSizeOverAccuracy, useNorm16Texture } =
cornerstone.getConfiguration().rendering;
export default function initCornerstoneDICOMImageLoader() {
// TODO: 此处非常的蛇皮
cornerstone.setUseSharedArrayBuffer(false)
cornerstone.setConfiguration({
detectGPUConfig: {
benchmarksURL: "http://localhost:9000"
}
})
cornerstoneDICOMImageLoader.external.cornerstone = cornerstone;
cornerstoneDICOMImageLoader.external.dicomParser = dicomParser;
cornerstoneDICOMImageLoader.configure({
useWebWorkers: true,
decodeConfig: {
convertFloatPixelDataToInt: false,
use16BitDataType: preferSizeOverAccuracy || useNorm16Texture,
},
});
const config = {
maxWebWorkers: navigator.hardwareConcurrency ? Math.min(navigator.hardwareConcurrency, 7) : 1,
startWebWorkersOnDemand: false,
taskConfiguration: {
decodeTask: {
initializeCodecsOnStartup: false,
strict: false,
},
},
};
cornerstoneDICOMImageLoader.webWorkerManager.initialize(config);
}

View File

@ -0,0 +1,13 @@
import initProviders from './initProviders.js';
import initCornerstoneDICOMImageLoader from './initCornerstoneDICOMImageLoader';
import initVolumeLoader from './initVolumeLoader';
import { init as csRenderInit } from '@cornerstonejs/core';
import { init as csToolsInit } from '@cornerstonejs/tools';
export default async function initDemo() {
initProviders();
initCornerstoneDICOMImageLoader();
initVolumeLoader();
await csRenderInit();
await csToolsInit();
}

View File

@ -0,0 +1,17 @@
import * as cornerstone from '@cornerstonejs/core';
import ptScalingMetaDataProvider from './ptScalingMetaDataProvider';
const { calibratedPixelSpacingMetadataProvider } = cornerstone.utilities;
export default function initProviders() {
cornerstone.metaData.addProvider(
ptScalingMetaDataProvider.get.bind(ptScalingMetaDataProvider),
10000
);
cornerstone.metaData.addProvider(
calibratedPixelSpacingMetadataProvider.get.bind(
calibratedPixelSpacingMetadataProvider
),
11000
);
}

View File

@ -0,0 +1,19 @@
import { volumeLoader } from '@cornerstonejs/core';
import {
cornerstoneStreamingImageVolumeLoader,
cornerstoneStreamingDynamicImageVolumeLoader,
} from '@cornerstonejs/streaming-image-volume-loader';
export default function initVolumeLoader() {
volumeLoader.registerUnknownVolumeLoader(
cornerstoneStreamingImageVolumeLoader
);
volumeLoader.registerVolumeLoader(
'cornerstoneStreamingImageVolume',
cornerstoneStreamingImageVolumeLoader
);
volumeLoader.registerVolumeLoader(
'cornerstoneStreamingDynamicImageVolume',
cornerstoneStreamingDynamicImageVolumeLoader
);
}

View File

@ -0,0 +1,17 @@
import { utilities as csUtils } from '@cornerstonejs/core';
const scalingPerImageId = {};
function addInstance(imageId, scalingMetaData) {
const imageURI = csUtils.imageIdToURI(imageId);
scalingPerImageId[imageURI] = scalingMetaData;
}
function get(type, imageId) {
if (type === 'scalingModule') {
const imageURI = csUtils.imageIdToURI(imageId);
return scalingPerImageId[imageURI];
}
}
export default { addInstance, get };

View File

@ -0,0 +1,33 @@
/**
* Remove invalid tags from a metadata and return a new object.
*
* At this time it is only removing tags that has `null` or `undefined` values
* which is our main goal because that breaks when `naturalizeDataset(...)` is
* called.
*
* Validating the tag id using regex like /^[a-fA-F0-9]{8}$/ make it run
* +50% slower and looping through all characteres (split+every+Set or simple
* FOR+Set) double the time it takes to run. It is currently taking +12ms/1k
* images on average which can change depending on the machine.
*
* @param srcMetadata - source metadata
* @returns new metadata object without invalid tags
*/
function removeInvalidTags(srcMetadata) {
// Object.create(null) make it ~9% faster
const dstMetadata = Object.create(null);
const tagIds = Object.keys(srcMetadata);
let tagValue;
tagIds.forEach((tagId) => {
tagValue = srcMetadata[tagId];
if (tagValue !== undefined && tagValue !== null) {
dstMetadata[tagId] = tagValue;
}
});
return dstMetadata;
}
export { removeInvalidTags as default, removeInvalidTags };

View File

@ -0,0 +1,16 @@
const windowWidth = 400;
const windowCenter = 40;
const lower = windowCenter - windowWidth / 2.0;
const upper = windowCenter + windowWidth / 2.0;
const ctVoiRange = { lower, upper };
export default function setCtTransferFunctionForVolumeActor({ volumeActor }) {
volumeActor
.getProperty()
.getRGBTransferFunction(0)
.setMappingRange(lower, upper);
}
export { ctVoiRange };

View File

@ -0,0 +1,87 @@
import macro from "@kitware/vtk.js/macro";
import Helper from "@kitware/vtk.js/Common/DataModel/ITKHelper";
const { convertItkToVtkImage } = Helper;
import readImageDICOMFileSeries from "itk/readImageDICOMFileSeries";
function getArrayName(filename) {
const idx = filename.lastIndexOf(".");
const name = idx > -1 ? filename.substring(0, idx) : filename;
return `Scalars ${name}`;
}
// ----------------------------------------------------------------------------
// vtkITKDicomImageReader methods
// ----------------------------------------------------------------------------
function vtkITKDicomImageReader(publicAPI, model) {
// Set our className
model.classHierarchy.push("vtkITKDicomImageReader");
// Returns a promise to signal when image is ready
publicAPI.readFileSeries = (files, fileName) => {
if (!files || !files.length || files === model.files) {
return Promise.resolve();
}
if (fileName && fileName !== model.fileName) {
model.fileName = fileName;
}
model.files = files;
return readImageDICOMFileSeries(null, files)
.then(({ webWorker, image }) => {
webWorker.terminate();
return image;
})
.then(itkImage => {
const imageData = convertItkToVtkImage(itkImage, {
scalarArrayName: model.arrayName || getArrayName(model.fileName)
});
model.output[0] = imageData;
publicAPI.modified();
return imageData;
});
};
publicAPI.requestData = (/* inData, outData */) => {
publicAPI.readFileSeries(model.files, model.fileName);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
fileName: "",
// If null/undefined a unique array will be generated
arrayName: null
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
macro.obj(publicAPI, model);
macro.algo(publicAPI, model, 0, 1);
macro.setGet(publicAPI, model, ["fileName", "arrayName"]);
// vtkITKDicomImageReader methods
vtkITKDicomImageReader(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = macro.newInstance(extend, "vtkITKDicomImageReader");
// ----------------------------------------------------------------------------
export default { newInstance, extend };

View File

@ -0,0 +1,74 @@
import { useRef, useState } from "react";
import dicomParser from "dicom-parser";
import vtkVolume from "@kitware/vtk.js/Rendering/Core/Volume";
import vtkVolumeMapper from "@kitware/vtk.js/Rendering/Core/VolumeMapper";
import vtkFullScreenRenderWindow from "@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow";
import vtkITKHelper from "@kitware/vtk.js/Common/DataModel/ITKHelper";
// import readImageDICOMFileSeries from "itk/readImageDICOMFileSeries";
import { readImageDicomFileSeries } from "@itk-wasm/dicom";
// import { readImageDicomFileSeries } from 'itk-wasm'
// import { readImageDICOMFileSeries } from "itk-wasm";
interface LocalMprProps {
children?: JSX.Element;
}
export const LocalMpr = (props: LocalMprProps) => {
const containerRef = useRef(null);
const handleFolderUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
if (event.target.files) {
const files = event.target.files;
if (!files.length) {
return;
}
const fileList: File[] = [];
for (let i = 0; i < files.length; i++) {
fileList.push(files[i]);
}
const image = await readImageDicomFileSeries(null, {
inputImages: fileList,
});
const vtkImage = vtkITKHelper.convertItkToVtkImage(image);
const volume = vtkVolume.newInstance();
const mapper = vtkVolumeMapper.newInstance();
volume.setMapper(mapper);
mapper.setInputData(vtkImage);
// 创建 vtk 的全屏渲染窗口
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
background: [0, 0, 0],
container: containerRef.current!,
});
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
// 将 volume 添加到渲染器
renderer.addVolume(volume);
// 设置相机位置等
renderer.resetCamera();
renderWindow.render();
}
};
return (
<div>
<div>
<input
type="file"
webkitdirectory="true"
directory=""
onChange={handleFolderUpload}
/>
</div>
<div style={{ width: 400, height: 400 }} ref={containerRef}></div>
</div>
);
};

View File

@ -0,0 +1,133 @@
import { relative } from "path";
import React, { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
type ThreeJSComponentProps = {
// 你可以在这里添加任何需要的props
};
export const MprViewer: React.FC<ThreeJSComponentProps> = () => {
const mountRef = useRef<HTMLDivElement>(null);
const [imageSrc, setImageSrc] = useState<string>("");
useEffect(() => {
const width = window.innerWidth - 300;
const height = window.innerHeight;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x808080);
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
// 添加一个可移动和旋转的平面
const planeGeometry = new THREE.PlaneGeometry(200, 200);
const planeMaterial = new THREE.MeshBasicMaterial({
color: 0xffff00,
side: THREE.DoubleSide,
});
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.position.set(0, 0, 0); // 初始位置
scene.add(plane);
// 创建一个与平面对齐的剪裁平面
const clipPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
renderer.clippingPlanes = [clipPlane];
// 使剪裁平面跟随你的移动平面
const updateClipPlane = () => {
clipPlane.normal.copy(plane.position).normalize();
};
// 添加多个3D物体
const geometry1 = new THREE.BoxGeometry(100, 100, 100);
const material1 = new THREE.MeshPhongMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.5,
});
const cube = new THREE.Mesh(geometry1, material1);
cube.position.x = -50; // 调整位置以确保重叠
scene.add(cube);
const geometry2 = new THREE.SphereGeometry(50, 32, 32);
const material2 = new THREE.MeshPhongMaterial({
color: 0xff0000,
transparent: true,
opacity: 0.5,
});
const sphere = new THREE.Mesh(geometry2, material2);
sphere.position.x = 0; // 调整位置以确保重叠
scene.add(sphere);
const geometry3 = new THREE.ConeGeometry(50, 100, 32);
const material3 = new THREE.MeshPhongMaterial({
color: 0x0000ff,
transparent: true,
opacity: 0.5,
});
const cone = new THREE.Mesh(geometry3, material3);
cone.position.x = 50; // 调整位置以确保重叠
scene.add(cone);
camera.position.set(0, 0, 500);
camera.lookAt(scene.position);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const mount = mountRef.current;
if (mount) {
mount.appendChild(renderer.domElement);
}
const controls = new TrackballControls(camera, renderer.domElement);
const animate = () => {
requestAnimationFrame(animate);
controls.update(); // 只有在使用 TrackballControls 时才需要
// camera.position.y += 5;
camera.updateMatrixWorld();
updateClipPlane(); // 更新剪裁平面的位置和方向
renderer.render(scene, camera);
// 从渲染器的 canvas 中获取图像
const canvas = renderer.domElement;
canvas.toBlob((blob) => {
if (blob) {
const imageUrl = URL.createObjectURL(blob);
setImageSrc(imageUrl);
}
}, "image/jpeg");
};
animate();
return () => {
controls.dispose();
mount?.removeChild(renderer.domElement);
URL.revokeObjectURL(imageSrc);
};
}, []);
return (
<div style={{ position: "relative" }}>
<div ref={mountRef} />
<img
style={{
position: "absolute",
right: 0,
top: 0,
width: "200px",
height: "200px",
}}
src={imageSrc}
alt="Rendered Scene"
/>
</div>
);
};

View File

@ -0,0 +1,67 @@
import { useEffect, useRef } from "react";
import { Enums, RenderingEngine, cache } from "@cornerstonejs/core";
import { initCornerstone } from "../CornerstoneDicomLoader/init";
import { createImageIdsAndCacheMetaData } from "../CornerstoneDicomLoader/createImageIdsAndCacheMetaData";
import {
IStackViewport,
PublicViewportInput,
} from "@cornerstonejs/core/dist/types/types";
interface StackViewerProps {
children?: JSX.Element;
}
const renderingEngineId = "myRenderingEngine";
const viewportId = "CT_STACK";
const { ViewportType } = Enums;
const StudyInstanceUID =
"1.2.840.113564.345049290535.9692.637552042156233117.433089";
const SeriesInstanceUID =
"1.3.12.2.1107.5.1.4.76315.30000021042706150001900118311";
export const StackViewer = (props: StackViewerProps) => {
const dicomRef = useRef(null);
const run = async () => {
await initCornerstone();
// Get Cornerstone imageIds and fetch metadata into RAM
const imageIds = await createImageIdsAndCacheMetaData({
StudyInstanceUID,
SeriesInstanceUID,
wadoRsRoot: "/dicom-web",
});
const renderingEngine = new RenderingEngine(renderingEngineId);
const viewportInput = {
viewportId,
type: ViewportType.STACK,
element: dicomRef.current,
} as unknown as PublicViewportInput;
renderingEngine.enableElement(viewportInput);
const viewport = renderingEngine.getViewport(viewportId) as IStackViewport;
const stack = imageIds;
await viewport.setStack(stack);
const currentImageIdIndex = viewport.getCurrentImageIdIndex();
const numImages = viewport.getImageIds().length;
let newImageIdIndex = currentImageIdIndex + 1;
newImageIdIndex = Math.min(newImageIdIndex, numImages - 1);
viewport.setImageIdIndex(newImageIdIndex);
};
useEffect(() => {
run();
}, []);
return (
<div>
<div ref={dicomRef} style={{ width: 400, height: 400 }}></div>
</div>
);
};

View File

@ -0,0 +1,2 @@
declare module "@cornerstonejs/dicom-image-loader";
declare module "dcmjs";

View File

@ -1,4 +1,8 @@
import { CrosshairMpr } from "./Crosshair";
import { DiffViewer } from "./DiffViewer"; import { DiffViewer } from "./DiffViewer";
import { LocalMpr } from "./LocalMpr";
import { MprViewer } from "./MprViewer";
import { StackViewer } from "./StackViewer";
interface RootViewerProps { interface RootViewerProps {
children?: JSX.Element; children?: JSX.Element;
@ -7,7 +11,9 @@ interface RootViewerProps {
export const RootViewer = (props: RootViewerProps) => { export const RootViewer = (props: RootViewerProps) => {
return ( return (
<div> <div>
<DiffViewer /> <LocalMpr />
{/* <CrosshairMpr /> */}
{/* <StackViewer /> */}
</div> </div>
); );
}; };

View File

@ -1,106 +0,0 @@
import React, { useEffect, useRef } from "react";
import * as THREE from "three";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import {
autoScale,
createEnclosedGeometry,
getOffsetTriangles,
getTriangleVertexs,
} from "./util";
export const STLViewer: React.FC = () => {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (containerRef.current) {
const width = containerRef.current.clientWidth;
const height = containerRef.current.clientHeight;
// 创建场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
containerRef.current.appendChild(renderer.domElement);
// 加载STL文件
const loader = new STLLoader();
loader.load("/1.stl", (geometry) => {
const s = autoScale(geometry);
// geometry.center();
// const material = new THREE.MeshPhongMaterial({
// color: "lightgrey", // 使用更亮的颜色
// shininess: 100, // 增加亮度
// specular: 0x222222, // 调整镜面高光的颜色
// // side: THREE.DoubleSide,
// // wireframe: true,
// });
// const mesh = new THREE.Mesh(geometry, material);
// mesh.scale.set(scale, scale, scale);
// scene.add(mesh);
// 输出三角形顶点信息
const triangles = getTriangleVertexs(geometry);
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
const newTriangles = getOffsetTriangles(triangles, -2);
console.log("newTriangles", newTriangles);
// 使用上面定义的函数
const enclosedGeometry = createEnclosedGeometry(
triangles,
newTriangles
);
enclosedGeometry.center();
const material = new THREE.MeshBasicMaterial({
color: "lightgrey",
side: THREE.DoubleSide,
});
const mesh = new THREE.Mesh(enclosedGeometry, material);
mesh.scale.set(s, s, s);
scene.add(mesh);
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
});
// 添加环境光源
const ambientLight = new THREE.AmbientLight(0xffffff, 1); // 第二个参数为强度
scene.add(ambientLight);
// 添加方向光源
const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// 添加XYZ轴
const axesHelper = new THREE.AxesHelper(2);
scene.add(axesHelper);
// 添加OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
// 渲染函数
const animate = () => {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
}
}, []);
return <div ref={containerRef} style={{ width: "100vw", height: "100vh" }} />;
};

View File

@ -1,13 +0,0 @@
import { STLViewer } from "./STLViewer";
interface RootViewerProps {
children?: JSX.Element;
}
export const RootViewer = (props: RootViewerProps) => {
return (
<div>
123
</div>
);
};

View File

@ -1,202 +0,0 @@
import * as THREE from "three";
export const autoScale = (geometry: THREE.BufferGeometry) => {
// 计算模型的边界
geometry.computeBoundingBox();
// 获取模型的大小
const modelSize = geometry.boundingBox!.getSize(new THREE.Vector3());
const maxSize = Math.max(modelSize.x, modelSize.y, modelSize.z);
// 根据模型的大小设置一个缩放因子
const scaleFactor = 2 / maxSize; // 假设我们希望模型最大为2单位
return scaleFactor;
};
export const getTriangleVertexs = (
geometry: THREE.BufferGeometry
): THREE.Vector3[][] => {
const positions = geometry.attributes.position;
const triangles: THREE.Vector3[][] = [];
const getTriangleVertices = (
index1: number,
index2: number,
index3: number
) => [
new THREE.Vector3(
positions.getX(index1),
positions.getY(index1),
positions.getZ(index1)
),
new THREE.Vector3(
positions.getX(index2),
positions.getY(index2),
positions.getZ(index2)
),
new THREE.Vector3(
positions.getX(index3),
positions.getY(index3),
positions.getZ(index3)
),
];
if (geometry.index) {
const indices = geometry.index.array;
for (let i = 0; i < indices.length; i += 3) {
triangles.push(
getTriangleVertices(indices[i], indices[i + 1], indices[i + 2])
);
}
} else {
for (let i = 0; i < positions.count; i += 3) {
triangles.push(getTriangleVertices(i, i + 1, i + 2));
}
}
return triangles;
};
export const getOffsetTriangles = (
triangles: THREE.Vector3[][],
offset: number
): THREE.Vector3[][] => {
const newTriangles: THREE.Vector3[][] = [];
triangles.forEach((triangle) => {
// 计算三角形的法线
const normal = new THREE.Vector3();
const edge1 = new THREE.Vector3().subVectors(triangle[1], triangle[0]);
const edge2 = new THREE.Vector3().subVectors(triangle[2], triangle[0]);
normal.crossVectors(edge1, edge2).normalize();
// 使用法线和偏移量计算新的三角形顶点
const offsetNormal = normal.clone().multiplyScalar(offset);
const newTriangle = triangle.map((vertex) =>
vertex.clone().sub(offsetNormal)
);
newTriangles.push(newTriangle);
});
return newTriangles;
};
export const createEnclosedGeometry = (
triangles: THREE.Vector3[][],
newTriangles: THREE.Vector3[][]
): THREE.BufferGeometry => {
const geometry = new THREE.BufferGeometry();
const vertices: THREE.Vector3[] = [];
const indices: number[] = [];
const processedEdges: Set<string> = new Set();
function edgeId(v1: THREE.Vector3, v2: THREE.Vector3): string {
return `${v1.x},${v1.y},${v1.z}->${v2.x},${v2.y},${v2.z}`;
}
triangles.forEach((triangle, index) => {
const innerTriangle = newTriangles[index];
triangle.forEach((vertex) => {
vertices.push(vertex);
});
innerTriangle.forEach((vertex) => {
vertices.push(vertex);
});
// Process the three edges for each triangle
for (let i = 0; i < 3; i++) {
const next = (i + 1) % 3;
const edge = edgeId(triangle[i], triangle[next]);
if (!processedEdges.has(edge)) {
processedEdges.add(edge);
// Add the vertices for the quad (two triangles)
const quadVertices = [
triangle[i],
triangle[next],
innerTriangle[i],
innerTriangle[next],
];
quadVertices.forEach((vertex) => {
vertices.push(vertex);
});
const baseIndex = vertices.length - 4;
// First triangle of the quad
indices.push(baseIndex, baseIndex + 2, baseIndex + 1);
// Second triangle of the quad
indices.push(baseIndex + 1, baseIndex + 2, baseIndex + 3);
}
}
});
geometry.setFromPoints(vertices);
geometry.setIndex(indices);
return geometry;
};
// export const createEnclosedGeometry = (
// triangles: THREE.Vector3[][],
// newTriangles: THREE.Vector3[][]
// ): THREE.BufferGeometry => {
// const geometry = new THREE.BufferGeometry();
// const vertices: number[] = [];
// const indices: number[] = [];
// // 添加原始三角形和新三角形的顶点到vertices数组
// triangles.forEach((triangle) => {
// triangle.forEach((v) => {
// vertices.push(v.x, v.y, v.z);
// });
// });
// newTriangles.forEach((triangle) => {
// triangle.forEach((v) => {
// vertices.push(v.x, v.y, v.z);
// });
// });
// const totalTriangles = triangles.length;
// // 创建索引来连接triangles和newTriangles中的三角形
// for (let i = 0; i < totalTriangles; i++) {
// const offset = totalTriangles * 3; // newTriangles在vertices中的偏移量
// const a1 = i * 3;
// const b1 = a1 + 1;
// const c1 = a1 + 2;
// const a2 = offset + i * 3;
// const b2 = a2 + 1;
// const c2 = a2 + 2;
// // 添加原始和新三角形的索引
// indices.push(a1, b1, c1);
// indices.push(a2, c2, b2);
// // 为每一对相邻的三角形添加边的索引
// indices.push(a1, b1, a2);
// indices.push(b1, b2, a2);
// indices.push(b1, c1, b2);
// indices.push(c1, c2, b2);
// indices.push(c1, a1, c2);
// indices.push(a1, a2, c2);
// }
// geometry.setIndex(indices);
// geometry.setAttribute(
// "position",
// new THREE.Float32BufferAttribute(vertices, 3)
// );
// geometry.computeVertexNormals(); // 计算顶点法线
// return geometry;
// };

View File

@ -17,6 +17,10 @@ export const baseRoutes: (RouteObject & ExpandRouteProps)[] = [
element: <Login />, element: <Login />,
title: "登录 - CVPILOT Viewer", title: "登录 - CVPILOT Viewer",
}, },
{
path: "root/report/full",
element: <ReportFullVersion />,
},
]; ];
export const commonRoutes: (RouteObject & ExpandRouteProps)[] = [ export const commonRoutes: (RouteObject & ExpandRouteProps)[] = [
@ -41,10 +45,7 @@ export const commonRoutes: (RouteObject & ExpandRouteProps)[] = [
path: "root/viewer", path: "root/viewer",
element: <RootViewer />, element: <RootViewer />,
}, },
{
path: "root/report/full",
element: <ReportFullVersion />,
},
{ {
path: "peripheral/viewer", path: "peripheral/viewer",
element: <PeripheralViewer />, element: <PeripheralViewer />,

View File

@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

24
apps/phoenix/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

30
apps/phoenix/README.md Normal file
View File

@ -0,0 +1,30 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
}
```
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list

13
apps/phoenix/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

33
apps/phoenix/package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "@tavi/phoenix",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@kitware/vtk.js": "29.3.0",
"@itk-wasm/image-io": "0.5.2",
"@itk-wasm/mesh-io": "0.2.2",
"@itk-wasm/dicom": "5.0.2"
},
"devDependencies": {
"@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17",
"@typescript-eslint/eslint-plugin": "^6.14.0",
"@typescript-eslint/parser": "^6.14.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.55.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"typescript": "^5.2.2",
"vite": "^5.0.8",
"vite-plugin-static-copy": "1.0.0"
}
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

128
apps/phoenix/src/App.tsx Normal file
View File

@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from "react";
import { readImageDicomFileSeries } from "@itk-wasm/dicom";
import vtkITKHelper from "@kitware/vtk.js/Common/DataModel/ITKHelper";
import vtkVolume from "@kitware/vtk.js/Rendering/Core/Volume";
import vtkFullScreenRenderWindow from "@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow";
import "@kitware/vtk.js/Rendering/Profiles/Volume";
import vtkRenderer from "@kitware/vtk.js/Rendering/Core/Renderer";
import vtkVolumeMapper from "@kitware/vtk.js/Rendering/Core/VolumeMapper";
import vtkRenderWindow from "@kitware/vtk.js/Rendering/Core/RenderWindow";
import "./app.css";
import {
checkExistenceInIndexedDB,
loadImageFromIndexedDB,
saveImageToIndexedDB,
} from "./util";
import { extractAxialSliceAsImage } from "./extract";
function App() {
const [files, setFiles] = useState<File[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
const axialRef = useRef<HTMLElement | null>(null);
const sagittalRef = useRef<HTMLElement | null>(null);
const coronalRef = useRef<HTMLElement | null>(null);
const rendererRef = useRef<vtkRenderer>();
const mapperRef = useRef<vtkVolumeMapper>();
const actorRef = useRef<vtkVolume>();
const renderWindowRef = useRef<vtkRenderWindow>();
const [image, setImage] = useState();
useEffect(() => {
if (inputRef.current) inputRef.current.webkitdirectory = true;
}, []);
useEffect(() => {
checkExistenceInIndexedDB("outputImageKey").then((exist) => {
if (exist) {
console.time("start load from cache");
loadImageFromIndexedDB().then((outputImage) => {
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
container: axialRef.current,
});
rendererRef.current = fullScreenRenderer.getRenderer();
renderWindowRef.current = fullScreenRenderer.getRenderWindow();
actorRef.current = vtkVolume.newInstance();
mapperRef.current = vtkVolumeMapper.newInstance({
sampleDistance: 1.1,
});
const vtkImage = vtkITKHelper.convertItkToVtkImage(outputImage);
mapperRef.current?.setInputData(vtkImage);
mapperRef.current && actorRef.current?.setMapper(mapperRef.current);
actorRef.current && rendererRef.current?.addVolume(actorRef.current);
rendererRef.current?.resetCamera();
renderWindowRef.current?.render();
console.timeEnd("start load from cache");
const imgSource = extractAxialSliceAsImage(vtkImage, 1);
setImage(imgSource);
});
}
});
}, []);
useEffect(() => {
if (files.length > 0) {
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
container: axialRef.current,
});
rendererRef.current = fullScreenRenderer.getRenderer();
renderWindowRef.current = fullScreenRenderer.getRenderWindow();
actorRef.current = vtkVolume.newInstance();
mapperRef.current = vtkVolumeMapper.newInstance({ sampleDistance: 1.1 });
console.time("itk-wasm parse vtkVolumeImageData");
readImageDicomFileSeries(null, {
inputImages: files,
}).then((image) => {
const vtkImage = vtkITKHelper.convertItkToVtkImage(image.outputImage);
console.timeEnd("itk-wasm parse vtkVolumeImageData");
saveImageToIndexedDB(image.outputImage);
mapperRef.current?.setInputData(vtkImage);
mapperRef.current && actorRef.current?.setMapper(mapperRef.current);
actorRef.current && rendererRef.current?.addVolume(actorRef.current);
rendererRef.current?.resetCamera();
renderWindowRef.current?.render();
});
return () => {
actorRef.current = undefined;
mapperRef.current = undefined;
rendererRef.current = undefined;
renderWindowRef.current = undefined;
};
}
}, [files]);
const handleFolderUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
const target = event.target as HTMLInputElement;
if (!target.files) return;
const files = [...target.files].filter((file) =>
file.name.endsWith(".dcm")
);
setFiles(files);
};
return (
<>
<input
type="file"
onChange={handleFolderUpload}
ref={inputRef}
style={{ position: "fixed", zIndex: 100 }}
/>
<div className="mpr">
<div ref={axialRef} style={{ width: 500, height: 500 }}></div>
{/* <div ref={sagittalRef} style={{ width: 300, height: 300 }}></div>
<div ref={coronalRef} style={{ width: 300, height: 300 }}></div> */}
</div>
<img src={image} style={{ width: 200, height: 200 }} />
</>
);
}
export default App;

8
apps/phoenix/src/app.css Normal file
View File

@ -0,0 +1,8 @@
.mpr {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,38 @@
import vtkImageData from "@kitware/vtk.js/Common/DataModel/ImageData";
export const extractAxialSliceAsImage = (
volumeData: vtkImageData,
sliceIndex: number
): string => {
const dimensions = volumeData.getDimensions();
if (sliceIndex < 0 || sliceIndex >= dimensions[2]) {
throw new Error("Invalid slice index");
}
const scalars = volumeData.getPointData().getScalars();
const slice = scalars
.getData()
.slice(
sliceIndex * dimensions[0] * dimensions[1],
(sliceIndex + 1) * dimensions[0] * dimensions[1]
);
const canvas = document.createElement("canvas");
canvas.width = dimensions[0];
canvas.height = dimensions[1];
const context = canvas.getContext("2d")!;
const imageDataObj = context.createImageData(dimensions[0], dimensions[1]);
for (let i = 0; i < slice.length; i++) {
const value = slice[i];
imageDataObj.data[i * 4] = value;
imageDataObj.data[i * 4 + 1] = value;
imageDataObj.data[i * 4 + 2] = value;
imageDataObj.data[i * 4 + 3] = 255;
}
context.putImageData(imageDataObj, 0, 0);
return canvas.toDataURL();
};

View File

@ -0,0 +1,5 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(<App />);

91
apps/phoenix/src/util.ts Normal file
View File

@ -0,0 +1,91 @@
const dbName = "myDatabase";
const storeName = "images";
export const openDatabase = async (): Promise<IDBDatabase> => {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName);
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
const db = request.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
}
};
request.onerror = (event) => reject(request.error);
request.onsuccess = (event) => resolve(request.result);
});
};
export const saveImageToIndexedDB = async (outputImage: any) => {
try {
const db = await openDatabase();
const transaction = db.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
const request = store.put(outputImage, "outputImageKey");
request.onerror = (event) =>
console.error("Error saving to IndexedDB", request.error);
request.onsuccess = (event) => console.log("Image saved to IndexedDB");
} catch (error) {
console.error("Error with IndexedDB operation", error);
}
};
export const loadImageFromIndexedDB = async (): Promise<any> => {
try {
const db = await openDatabase();
const transaction = db.transaction(storeName, "readonly");
const store = transaction.objectStore(storeName);
const request = store.get("outputImageKey");
return new Promise((resolve, reject) => {
request.onerror = (event) => {
console.error("Error fetching from IndexedDB", request.error);
reject(request.error);
};
request.onsuccess = (event) => {
if (request.result) {
console.log("Image loaded from IndexedDB");
resolve(request.result);
} else {
console.log("No data found in IndexedDB");
resolve(null);
}
};
});
} catch (error) {
console.error("Error with IndexedDB operation", error);
throw error;
}
};
export const checkExistenceInIndexedDB = async (
key: string
): Promise<boolean> => {
try {
const dbName = "myDatabase";
const storeName = "images";
const db = await openDatabase();
const transaction = db.transaction(storeName, "readonly");
const store = transaction.objectStore(storeName);
const request = store.get(key);
return new Promise((resolve, reject) => {
request.onerror = (event) => {
console.error("Error fetching from IndexedDB", request.error);
reject(request.error);
};
request.onsuccess = (event) => {
resolve(request.result !== undefined);
};
});
} catch (error) {
console.error("Error with IndexedDB operation", error);
throw error;
}
};

1
apps/phoenix/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,25 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { viteStaticCopy } from "vite-plugin-static-copy";
// https://vitejs.dev/config/
export default defineConfig({
worker: {
format: "es",
},
optimizeDeps: {
exclude: ["itk-wasm", "@itk-wasm/image-io"],
},
plugins: [
react(),
viteStaticCopy({
targets: [
{ src: "../../../dist/pipelines/*", dest: "pipelines" },
{
src: "../../../node_modules/@itk-wasm/image-io/dist/pipelines/*.{js,wasm,wasm.zst}",
dest: "pipelines",
},
],
}),
],
});

View File

@ -27,13 +27,11 @@ import { ForbiddenExceptionFilter } from './filter/forbid.filter';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -21,10 +21,11 @@ export class AuthController {
@Res({ passthrough: true }) res: Response, @Res({ passthrough: true }) res: Response,
) { ) {
const { username, password, phoneNumber } = userLoginDto; const { username, password, phoneNumber } = userLoginDto;
// TODO: isEnabled、phoneNumber用于后续验证 //* Step1: 询问认证中心服务,用户是否合法
const { isLegal, data, msg } = await firstValueFrom( const { isLegal, data, msg } = await firstValueFrom(
this.client.send('cert.user.account', { username, password }), this.client.send('cert.user.account', { username, password }),
); );
//* Step2: 上报登录日志
await firstValueFrom( await firstValueFrom(
this.client.send('logger.user.signIn', { this.client.send('logger.user.signIn', {
platform: 'dmp', platform: 'dmp',
@ -35,10 +36,11 @@ export class AuthController {
}), }),
); );
if (isLegal) { if (isLegal) {
// 签发token //* Step3: 签发token
const { token } = await firstValueFrom( const { token } = await firstValueFrom(
this.client.send('cert.token.create', { username }), this.client.send('cert.token.create', { username }),
); );
//* Step4: 询问认证中心token存在cookie中的key统一个业务的token的key以及过期时间
const { tokenKeyInCookie, expires } = await firstValueFrom( const { tokenKeyInCookie, expires } = await firstValueFrom(
this.client.send('cert.token.config', []), this.client.send('cert.token.config', []),
); );

View File

@ -8,13 +8,11 @@ import { ClientsModule, Transport } from '@nestjs/microservices';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -1,12 +1,12 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import { getFileExt } from './app.util'; import { getFileExt } from './app.util';
import { clientConfig } from './app.config'; import { clientConfig } from './app.config';
import { MinioOSS } from '@tavi/oss'; import { MinioOSS } from '@tavi/oss';
@Controller() @Controller()
export class AppController { export class AppController {
@MessagePattern('report-upload-image') @EventPattern('report-upload-image')
async uploadImageHandler({ buffer, originalName }) { async uploadImageHandler({ buffer, originalName }) {
const objectName = Date.now() + '.' + getFileExt(originalName); const objectName = Date.now() + '.' + getFileExt(originalName);
const { bucketName, ...config } = clientConfig; const { bucketName, ...config } = clientConfig;

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -1,4 +1,4 @@
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import { RedisService } from './redis/redis.service'; import { RedisService } from './redis/redis.service';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
@ -16,7 +16,7 @@ export class AppController {
* token签发, * token签发,
* @description redis的EXcookie的maxAge(ms)jwt的expiresIn * @description redis的EXcookie的maxAge(ms)jwt的expiresIn
*/ */
@MessagePattern('cert.token.create') @EventPattern('cert.token.create')
async createToken(payload) { async createToken(payload) {
const { username } = payload; const { username } = payload;
const token = await this.jwtService.sign(payload); const token = await this.jwtService.sign(payload);
@ -28,7 +28,7 @@ export class AppController {
* token有效性 && token * token有效性 && token
* @description guard对请求token进行拦截token是否合法&redis中 * @description guard对请求token进行拦截token是否合法&redis中
*/ */
@MessagePattern('cert.token.decode') @EventPattern('cert.token.decode')
async decodeToken( async decodeToken(
token: string, token: string,
): Promise<{ tokenValid: boolean; payload: unknown; error?: unknown }> { ): Promise<{ tokenValid: boolean; payload: unknown; error?: unknown }> {
@ -47,7 +47,7 @@ export class AppController {
* token在cookie中存储的key * token在cookie中存储的key
* @description cookie的maxAge单位是毫秒cookie使用expires需要 x1000 * @description cookie的maxAge单位是毫秒cookie使用expires需要 x1000
*/ */
@MessagePattern('cert.token.config') @EventPattern('cert.token.config')
async tokenConfig() { async tokenConfig() {
return { return {
tokenResignIn: this.configService.get('TOKEN_RESIGN_IN'), tokenResignIn: this.configService.get('TOKEN_RESIGN_IN'),
@ -56,7 +56,7 @@ export class AppController {
}; };
} }
@MessagePattern('cert.token.deprecated') @EventPattern('cert.token.deprecated')
async removeToken(payload) { async removeToken(payload) {
const { username } = payload; const { username } = payload;
console.log('username', username); console.log('username', username);

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -1,6 +1,6 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import { RbacService } from './rbac/rbac.service'; import { RbacService } from './rbac/rbac.service';
@Controller() @Controller()
@ -10,59 +10,59 @@ export class AppController {
private readonly rbacService: RbacService, private readonly rbacService: RbacService,
) {} ) {}
@MessagePattern('cert.authorize') @EventPattern('cert.authorize')
async authorize(payload) { async authorize(payload) {
console.log('获取user的token进行payload权限的验证', payload); console.log('获取user的token进行payload权限的验证', payload);
return false; return false;
} }
@MessagePattern('cert.init.role.admin') @EventPattern('cert.init.role.admin')
async initRole() { async initRole() {
await this.rbacService.initSuperAdminRole(); await this.rbacService.initSuperAdminRole();
await this.rbacService.initSuperAdminAccount(); await this.rbacService.initSuperAdminAccount();
} }
@MessagePattern('cert.create.role') @EventPattern('cert.create.role')
async createRole(payload) { async createRole(payload) {
return await this.rbacService.createRole(payload); return await this.rbacService.createRole(payload);
} }
@MessagePattern('cert.remove.role') @EventPattern('cert.remove.role')
async removeRole(payload) { async removeRole(payload) {
return await this.rbacService.removeRole(payload); return await this.rbacService.removeRole(payload);
} }
@MessagePattern('cert.find.role.all') @EventPattern('cert.find.role.all')
async findAllRole() { async findAllRole() {
return await this.rbacService.findAllRole(); return await this.rbacService.findAllRole();
} }
@MessagePattern('cert.init.permission.resource') @EventPattern('cert.init.permission.resource')
async initPermission(payload) { async initPermission(payload) {
await this.rbacService.initPermission(payload); await this.rbacService.initPermission(payload);
} }
@MessagePattern('cert.find.role.permission') @EventPattern('cert.find.role.permission')
async findRolePermission(payload) { async findRolePermission(payload) {
return await this.rbacService.findRolePermission(payload); return await this.rbacService.findRolePermission(payload);
} }
@MessagePattern('cert.update.role.permissions') @EventPattern('cert.update.role.permissions')
async updateRolePermissions(payload) { async updateRolePermissions(payload) {
return await this.rbacService.updateRolePermissions(payload); return await this.rbacService.updateRolePermissions(payload);
} }
@MessagePattern('cert.update.role') @EventPattern('cert.update.role')
async updateRole(payload) { async updateRole(payload) {
return await this.rbacService.updateRole(payload); return await this.rbacService.updateRole(payload);
} }
@MessagePattern('cert.find.all.user') @EventPattern('cert.find.all.user')
async findAllUser() { async findAllUser() {
return await this.rbacService.findAllUser(); return await this.rbacService.findAllUser();
} }
@MessagePattern('cert.role.authorize') @EventPattern('cert.role.authorize')
async roleAuthorize({ user, url }) { async roleAuthorize({ user, url }) {
const allow = await this.rbacService.roleAuthorize(user, url); const allow = await this.rbacService.roleAuthorize(user, url);
return { allow }; return { allow };

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -1,5 +1,5 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import { UserService } from './user.service'; import { UserService } from './user.service';
import { BcryptService } from '../bcrypt/bcrypt.service'; import { BcryptService } from '../bcrypt/bcrypt.service';
@ -12,7 +12,7 @@ export class UserController {
/** /**
* *
*/ */
@MessagePattern('cert.user.account') @EventPattern('cert.user.account')
async findUser( async findUser(
payload, payload,
): Promise<{ isLegal: boolean; msg?: string; data?: any }> { ): Promise<{ isLegal: boolean; msg?: string; data?: any }> {
@ -28,22 +28,22 @@ export class UserController {
return { isLegal: true, data: user }; return { isLegal: true, data: user };
} }
@MessagePattern('cert.user.encrypt') @EventPattern('cert.user.encrypt')
async encrypt(plainText: string) { async encrypt(plainText: string) {
return await this.bcryptService.hashPassword(plainText); return await this.bcryptService.hashPassword(plainText);
} }
@MessagePattern('cert.encrypt.compare') @EventPattern('cert.encrypt.compare')
async compare(plainText: string, hash: string) { async compare(plainText: string, hash: string) {
return await this.bcryptService.comparePassword(plainText, hash); return await this.bcryptService.comparePassword(plainText, hash);
} }
@MessagePattern('cert.user.create') @EventPattern('cert.user.create')
async createUser(payload) { async createUser(payload) {
return await this.userService.create(payload); return await this.userService.create(payload);
} }
@MessagePattern('cert.user.update') @EventPattern('cert.user.update')
async updateUser(payload) { async updateUser(payload) {
const { password, ...rest } = payload; const { password, ...rest } = payload;
const updateFields = password const updateFields = password
@ -52,12 +52,12 @@ export class UserController {
return await this.userService.update(updateFields); return await this.userService.update(updateFields);
} }
@MessagePattern('cert.user.delete') @EventPattern('cert.user.delete')
async deleteUser(userIds: number[]) { async deleteUser(userIds: number[]) {
return await this.userService.delete(userIds); return await this.userService.delete(userIds);
} }
@MessagePattern('cert.user.find.annotator') @EventPattern('cert.user.find.annotator')
async findAnnotators() { async findAnnotators() {
const annotators = await this.userService.findAnnotators(); const annotators = await this.userService.findAnnotators();
return { data: annotators }; return { data: annotators };

View File

@ -8,13 +8,11 @@ import { ClientsModule, Transport } from '@nestjs/microservices';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -21,14 +21,11 @@ import { AdminModule } from './admin/admin.module';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
]), ]),

View File

@ -1,6 +1,6 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import axios from 'axios'; import axios from 'axios';
@ -75,7 +75,7 @@ export class AppController {
private readonly configService: ConfigService, private readonly configService: ConfigService,
) {} ) {}
@MessagePattern('dicom.find') @EventPattern('dicom.find')
async findDicoms() { async findDicoms() {
const pacsUrl = this.configService.get('PACS_URL'); const pacsUrl = this.configService.get('PACS_URL');
try { try {
@ -118,7 +118,7 @@ export class AppController {
} }
} }
@MessagePattern('dicom.archive.url') @EventPattern('dicom.archive.url')
async archiveUrl({ ID, Type }: { ID: string; Type: string }) { async archiveUrl({ ID, Type }: { ID: string; Type: string }) {
const pacsUrl = this.configService.get('PACS_URL'); const pacsUrl = this.configService.get('PACS_URL');
const mapping = { const mapping = {

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -1,17 +1,17 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
@Controller() @Controller()
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@MessagePattern('archive.task.create') @EventPattern('archive.task.create')
async createArchiveTask(payload) { async createArchiveTask(payload) {
return await this.appService.createArchiveTask(payload); return await this.appService.createArchiveTask(payload);
} }
@MessagePattern('archive.task.find') @EventPattern('archive.task.find')
async findArchiveTask(payload) { async findArchiveTask(payload) {
return await this.appService.findArchiveTask(payload); return await this.appService.findArchiveTask(payload);
} }

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -7,13 +7,11 @@ import { ClientsModule, Transport } from '@nestjs/microservices';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -7,13 +7,11 @@ import { ClientsModule, Transport } from '@nestjs/microservices';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -21,13 +21,11 @@ import * as cookieParser from 'cookie-parser';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -15,10 +15,11 @@ export class AuthController {
@Res({ passthrough: true }) res: Response, @Res({ passthrough: true }) res: Response,
) { ) {
const { username, password } = userLoginDto; const { username, password } = userLoginDto;
//* Step1: 询问认证中心服务,用户是否合法
const { isLegal, data, msg } = await firstValueFrom( const { isLegal, data, msg } = await firstValueFrom(
this.client.send('cert.user.account', { username, password }), this.client.send('cert.user.account', { username, password }),
); );
// 日志 //* Step2: 上报登录日志
await firstValueFrom( await firstValueFrom(
this.client.send('logger.user.signIn', { this.client.send('logger.user.signIn', {
platform: 'dmp', platform: 'dmp',
@ -29,11 +30,12 @@ export class AuthController {
}), }),
); );
if (isLegal) { if (isLegal) {
// 签发token,签用户的角色,前端UI路由鉴权 //* Step3: 签发token,签用户的角色,前端UI路由鉴权
const { roles } = data; const { roles } = data;
const { token } = await firstValueFrom( const { token } = await firstValueFrom(
this.client.send('cert.token.create', { username, roles }), this.client.send('cert.token.create', { username, roles }),
); );
//* Step4: 询问认证中心token存在cookie中的key统一个业务的token的key以及过期时间
const { tokenKeyInCookie, expires } = await firstValueFrom( const { tokenKeyInCookie, expires } = await firstValueFrom(
this.client.send('cert.token.config', []), this.client.send('cert.token.config', []),
); );

View File

@ -7,13 +7,11 @@ import { ClientsModule, Transport } from '@nestjs/microservices';
ClientsModule.register([ ClientsModule.register([
{ {
name: 'Client', name: 'Client',
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'],
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
}, },
}, },
]), ]),

View File

@ -1,6 +1,6 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { EventPattern, MessagePattern } from '@nestjs/microservices'; import { EventPattern } from '@nestjs/microservices';
import * as dayjs from 'dayjs'; import * as dayjs from 'dayjs';
import { SymmetricCrypto } from '@tavi/util'; import { SymmetricCrypto } from '@tavi/util';
@ -16,7 +16,7 @@ interface UserSignLoggerDto {
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@MessagePattern('logger.user.signIn') @EventPattern('logger.user.signIn')
async userSignIn(payload: UserSignLoggerDto) { async userSignIn(payload: UserSignLoggerDto) {
const dateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); const dateTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
const { finger2, ...rest } = payload; const { finger2, ...rest } = payload;
@ -25,12 +25,12 @@ export class AppController {
return 1; return 1;
} }
@MessagePattern('logger.save') @EventPattern('logger.save')
async saveLogger(payload: UserSignLoggerDto) { async saveLogger(payload: UserSignLoggerDto) {
return 'ok'; return 'ok';
} }
@MessagePattern('alg.test') @EventPattern('alg.test')
async algTest(payload) { async algTest(payload) {
console.log('来自: alg.test', payload); console.log('来自: alg.test', payload);
return payload; return payload;

View File

@ -6,14 +6,11 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>( const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule, AppModule,
{ {
transport: Transport.RMQ, transport: Transport.NATS,
options: { options: {
urls: ['amqp://localhost:5672'], servers: ['nats://localhost:4222'], // 可以指定链接到多个nats的消息队列
queue: 'cats_queue', maxReconnectAttempts: 5,
queueOptions: { reconnectTimeWait: 1000,
durable: false,
},
maxConnectionAttempts: 10,
}, },
}, },
); );

View File

@ -14,7 +14,7 @@ async getHello(): Promise<any> {
} }
// 服务 // 服务
@MessagePattern('sum') @EventPattern('sum')
sum(data: number[]): number { sum(data: number[]): number {
return (data || []).reduce((a, b) => a + b); return (data || []).reduce((a, b) => a + b);
} }

View File

@ -4,12 +4,43 @@ services:
image: nats image: nats
container_name: tavi-nats container_name: tavi-nats
restart: always restart: always
command: -m 5000 command: -m 8222
ports: ports:
- "4222:4222" - "4222:4222"
- "6222:6222" - "6222:6222"
- "8222:8222" - "8222:8222"
nats_exporter:
image: noenv/nats-exporter:latest
command: -varz "http://nats:8222"
ports:
- "9999:7777"
container_name: tavi-nats-exporter
restart: always
depends_on:
- nats
prometheus:
image: prom/prometheus:latest
restart: always
container_name: tavi-prometheus
volumes:
- ./Prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- "9090:9090"
depends_on:
- nats_exporter
grafana:
image: grafana/grafana:latest
container_name: tavi-grafana
ports:
- "9091:3000"
depends_on:
- prometheus
mongodb: mongodb:
image: mongo:5.0 image: mongo:5.0
container_name: tavi-mongo container_name: tavi-mongo
@ -69,7 +100,7 @@ services:
- POSTGRES_DB=postgres - POSTGRES_DB=postgres
pacs: pacs:
image: osimis/orthanc:20.11.2 image: osimis/orthanc:master-full
container_name: tavi-orthanc container_name: tavi-orthanc
depends_on: depends_on:
- postgres - postgres

View File

@ -11,13 +11,6 @@ services:
environment: environment:
- RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_USER=guest
- RABBITMQ_DEFAULT_PASS=guest - RABBITMQ_DEFAULT_PASS=guest
- TZ=Asia/Shanghai # 将此值设置为您所在的时区
# volumes:
# - rabbitmq-data:/var/lib/rabbitmq
command: >
bash -c "rabbitmq-plugins enable rabbitmq_management &&
rabbitmq-plugins enable rabbitmq_tracing &&
rabbitmq-server"
mongodb: mongodb:
image: mongo:5.0 image: mongo:5.0

View File

@ -2,8 +2,8 @@
"name": "@tavi-universe", "name": "@tavi-universe",
"version": "1.0.0", "version": "1.0.0",
"scripts": { "scripts": {
"dev:all": "chmod 777 ./terminal.sh && ./terminal.sh",
"mock": "pnpm run --filter @tavi/mock mock", "mock": "pnpm run --filter @tavi/mock mock",
"dev:phoenix": "pnpm run --filter @tavi/phoenix dev",
"dev:dicom": "pnpm run --filter @tavi/dicom start:dev", "dev:dicom": "pnpm run --filter @tavi/dicom start:dev",
"dev:logger": "pnpm run --filter @tavi/logger start:dev", "dev:logger": "pnpm run --filter @tavi/logger start:dev",
"dev:dmp-web": "pnpm run --filter @tavi/dmp-web dev", "dev:dmp-web": "pnpm run --filter @tavi/dmp-web dev",

File diff suppressed because it is too large Load Diff