All files / extensions/default/src/DicomWebDataSource/utils fixMultipart.ts

0% Statements 0/34
0% Branches 0/11
0% Functions 0/4
0% Lines 0/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                                                                                                                             
import findIndexOfString from './findIndexOfString';
 
/**
 * Fix multipart data coming back from the retrieve bulkdata request, but
 * incorrectly tagged as application/octet-stream.  Some servers don't handle
 * the response type correctly, and this method is relatively robust about
 * detecting multipart data correctly.  It will only extract one value.
 */
export default function fixMultipart(arrayData) {
  const data = new Uint8Array(arrayData[0]);
  // Don't know the exact minimum length, but it is at least 25 to encode multipart
  Iif (data.length < 25) {
    return arrayData;
  }
  const dashIndex = findIndexOfString(data, '--');
  Iif (dashIndex > 6) {
    return arrayData;
  }
  const tokenIndex = findIndexOfString(data, '\r\n\r\n', dashIndex);
  Iif (tokenIndex > 512) {
    // Allow for 512 characters in the header - there is no apriori limit, but
    // this seems ok for now as we only expect it to have content type in it.
    return arrayData;
  }
  const header = uint8ArrayToString(data, 0, tokenIndex);
  // Now find the boundary  marker
  const responseHeaders = header.split('\r\n');
  const boundary = findBoundary(responseHeaders);
 
  Iif (!boundary) {
    return arrayData;
  }
  // Start of actual data is 4 characters after the token
  const offset = tokenIndex + 4;
 
  const endIndex = findIndexOfString(data, boundary, offset);
  Iif (endIndex === -1) {
    return arrayData;
  }
 
  return [data.slice(offset, endIndex - 2).buffer];
}
 
export function findBoundary(header: string[]): string {
  for (let i = 0; i < header.length; i++) {
    Iif (header[i].substr(0, 2) === '--') {
      return header[i];
    }
  }
}
 
export function findContentType(header: string[]): string {
  for (let i = 0; i < header.length; i++) {
    Iif (header[i].substr(0, 13) === 'Content-Type:') {
      return header[i].substr(13).trim();
    }
  }
}
 
export function uint8ArrayToString(data, offset, length) {
  offset = offset || 0;
  length = length || data.length - offset;
  let str = '';
 
  for (let i = offset; i < offset + length; i++) {
    str += String.fromCharCode(data[i]);
  }
 
  return str;
}