218. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 4/2/2019 1:07:33 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

218.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\ARS_Frontend\ars-app\ars-app-server\server\routes\275 275Attachment.js Wed Mar 27 19:18:19 2019 UTC
2 C:\AraxisMergeCompare\Pri_re\ARS_Frontend\ars-app\ars-app-server\server\routes\275 275Attachment.js Fri Mar 29 17:53:29 2019 UTC

218.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 784
Changed 1 2
Inserted 0 0
Removed 0 0

218.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

218.4 Active regular expressions

No regular expressions were active.

218.5 Comparison detail

  1   const expr ess = requ ire('expre ss');
  2   const rout er = expre ss.Router( );
  3   const rest  = require ('../../re st/rest');
  4   const auth Middleware  = require ('../../au th/authGua rdMiddlewa re');
  5   const path  = require ('path');
  6   const fs =  require(' fs');
  7  
  8   const LOGD BG = false ; // log d etailed de bug messag es
  9   function l ogdbg(...a rgs) {
  10     LOGDBG & & console. log('Debug  ', ...arg s);
  11   }
  12  
  13   const LOGI NF = false ; // log i nteresting  informati on message s
  14   function l oginf(...a rgs) {
  15     LOGINF & & console. log('Info  ', ...args );
  16   }
  17  
  18   const LOGE RR = true;  // log cr itical err or message s
  19   function l ogerr(...a rgs) {
  20     LOGERR & & console. log('Error  ', ...arg s);
  21   }
  22  
  23   // DRY - D on't Repea t Yourself
  24   // The ser ver https: //localhos t:4200/ re cognizes / assets, bu t fs.write File() doe s not.
  25   const xmlN ame = 'XML .XML'; //  constant,  for now
  26   // const x mlName = ' XMLtest.xm l';        // constan t, for now  --
  27   // const x mlPath = ' /assets/xm l/';  // f ailed!
  28   // const x mlPath = p ath.join(_ _dirname,  '../../../ ../attachm entViewerT emp');
  29   const appP ath = path .join(__di rname, '.. /../../..' ); // wher e the ars- app is, re lative to  this file
  30   // Don't u se 'src/as sets/xml',  since it  will trigg er webpack  to re-com pile!
  31   // const x mlPath = p ath.join(a ppPath, 's rc/assets/ xml');   / / seems to  be writab le. That m ight not b e good. Bu t try it
  32   const xmlP ath = path .join(appP ath, 'atta chmentView erTemp');
  33   const xmlF ile = path .join(xmlP ath, xmlNa me);
  34   logdbg('xm lFile=', x mlFile);
  35   const href CDAView =  '/attachme nt/cda'; / / href="cd a" in /att achment/xm l buffer,  is /attach ment/cda r oute
  36   const href CDAExport  = '../CDA. xsl'; // f or export
  37   function x mlCDA(body , cdaUrl)  {
  38     // Repla ce <?xml-s tylesheet  ?> with lo cal versio n
  39     // This  overrides  similar co de in the  275parser! !
  40     //
  41     // const  cdaUrl =  'cda'; //  route, /at tachment/c da, not a  file
  42     let xml  = new Stri ng(body);
  43     logdbg(` href='${cd aUrl}'`);
  44     // use p attern for  only one  replace
  45     // Proba ly should  de-quote c daUrl
  46     // xml =  xml.repla ce(/(<\?xm l-styleshe et .*)href =['"]([-a- zA-Z0-9.\/ \\:]*[\/\\ ]|)CDA.xsl ['"]/, '$1 href="' +  cdaUrl + ' "');
  47     xml = xm l.replace( /href=['"] ([-a-zA-Z0 -9.\/\\:]+ )CDA\.xsl[ '"]/, 'hre f="' + cda Url + '"') ;
  48     logdbg(x ml);
  49     return x ml;
  50   }
  51  
  52   // I tried  many meth ods of get ting the f ile name f rom the he ader and f ailed many  times.
  53   // So, I h ave abstra cted that  operation  out, to ma ke sure th at it is d one consis tently in  one place.
  54   function h drGetName( headers) {
  55     // Error   in /view Attachment   TypeErro r: headers .get is no t a functi on
  56     // const  getXAttac hmentName  = headers. get('X-Att achment-Na me');
  57     // logdb g('getXAtt achmentNam e=', getXA ttachmentN ame);  //  Doesn't wo rk! node m akes it lo wercase!!!
  58     // const  XAttachme ntName = h eaders['X- Attachment -Name'];
  59     // logdb g('XAttach mentName=' , XAttachm entName);   // Doesn' t work! no de makes i t lowercas e!!!
  60     const xA ttachmentN ame = head ers['x-att achment-na me'];
  61     loginf(' xAttachmen tName=', x Attachment Name);
  62     return x Attachment Name;
  63   }
  64   // likewis e, pass th e file nam e as a hea der in our  result,
  65   // It coul d be a map ping, but  here, it i s the iden tity.
  66   function r esSetName( res, name)  {
  67     loginf(' resSetName : X-Attach ment-Name= ', name);
  68     res.set( 'X-Attachm ent-Name',  name); //  pass it a long, Uppe r case get s changed  to lowerca se at some  point!!
  69   }
  70  
  71         // h ttps://dev eloper.moz illa.org/e n-US/docs/ Web/HTTP/H eaders/Con tent-Dispo sition
  72         // c ontent-dis position s hould be ' inline; fi lename=foo ' or 'atta chment; fi lename=bar '
  73         // N ormally in line is sh own by the  browser,  and attach ments are  saved to a  file.
  74         // i nline migh t not have  a filenam e.
  75         // f ilename is  only a de fault for  the SaveAs ... dialog .
  76         //SE RVER.DOMAI N.EXT
  77         // H owever, /a rs/api/v1/ file norma lly just r eturns
  78         // t he filenam e as the ' Content-Di sposition'
  79         // * ******* Ch anged, now
  80         // l ogdbg(`res .set({'Con tent-Dispo sition': $ {_contentD isposition  || 'falsy  _contentD isposition '}});`);
  81         // r es.set({'C ontent-Dis position':  _contentD isposition  || 'falsy  _contentD isposition '});
  82         // r es.set('co ntent-disp osition',  fileName | | 'somethi ngFishy.gi f');
  83  
  84  
  85   // /attach ment/searc hAttachmen ts  includ ed to matc h plausibl e searches .
  86   router.pos t('/search Attachment s', authMi ddleware,  (req, res)  => {
  87     rest
  88       .postR esource(
  89         proc ess.env.EN D_POINT_BA SE_URI + p rocess.env .SEARCH_AT TACHMENTS,
  90         req. body
  91       )
  92       .then( data => {
  93         res. status(dat a.response .statusCod e).json(da ta.respons eBody);
  94       })
  95       .catch (error =>  logerr('/s earchAttac hments', e rror));
  96   });
  97  
  98   // /attach ment/unmat ched837Cla im
  99   router.pos t('/unmatc hed837Clai m', authMi ddleware,  (req, res)  => {
  100     rest.pos tResource(
  101         `${p rocess.env .END_POINT _BASE_URI} ${process. env.MANUAL _MATCHING_ UNMATCHED_ 837}`, req .body)
  102       .then( data => {
  103         res. status(dat a.response .statusCod e).json(da ta.respons eBody);
  104       })
  105       .catch (error =>  logerr('27 5_attachme nt.js unma tched837Cl aim', erro r));
  106   })
  107  
  108   // /attach ment/archi veAttachme nt
  109   router.pos t('/archiv eAttachmen t', authMi ddleware,  (req, res)  => {
  110     logdbg(' /archiveAt tachment') ;
  111     rest.pos tResource(
  112         `${p rocess.env .END_POINT _BASE_URI} ${process. env.ARCHIV E_ATTACHME NT}`, req. body)
  113       .then( data => {
  114         res. status(dat a.response .statusCod e).json(da ta.respons eBody);
  115       })
  116       .catch (error =>  {
  117         loge rr('275_at tachment.j s /archive Attachment  ', error) ;
  118         res. status(400 ).json(err or);
  119       })
  120   })
  121  
  122   // /attach ment/viewA ttachment
  123   router.pos t('/viewAt tachment',  (req, res ) => {
  124     logdbg(' /viewAttac hment');
  125     const at tachmentRe quest = re q.body;
  126     logdbg(' attachment Request ',  attachmen tRequest);
  127     rest.pos tResource( `${process .env.END_P OINT_BASE_ URI}/ars/a pi/v1/file `, attachm entRequest )
  128       .then( data => {
  129         cons t name = h drGetName( data.respo nse.header s);
  130         if ( data.respo nse.status Code == 40 4) {
  131           //  not found , occurs o n local wh en attachm ents are m issing.
  132           //  presumabl y could oc cur on pro duction se rvers.
  133           //  I'm not s ure this i s the norm al way of  handling t his.  PEER  REVIEW
  134           lo ginf('data .response. statusCode =', data.r esponse.st atusCode);
  135           re sSetName(r es, name);  // just f or informa tional pur poses
  136           re turn res.s tatus(data .response. statusCode ); // Not  found happ ens with l ocal, inco mplete att achement d b
  137         }
  138  
  139         // c onst _Cont entType =  data.respo nse.header s['Content -Type'];   // undefin ed
  140         // l ogdbg('_Co ntentType= ', _Conten tType);
  141         let  _contentTy pe = data. response.h eaders['co ntent-type '];
  142         logd bg('_conte ntType=',  _contentTy pe);
  143         _con tentType =  _contentT ype || '/' ; // if fi le not fou nd.
  144         if ( /^ *applic ation\/jso n.*/.test( _contentTy pe)) {
  145           //  an error?
  146           lo gdbg('data .response. headers=',  JSON.stri ngify(data .response. headers));
  147           //  logdbg('d ata.respon seBody=',  data.respo nseBody);
  148           //  logdbg('d ata=', dat a);  // ve rbose
  149         }
  150  
  151         // B ecause thi s is .js,  not .ts, w e don't ha ve typing  on the dat a value
  152         // w e rely on  convention s set down
  153         // b etween Fro ntend 275A ttachment. js and Bac kend FileO perations. java
  154         // N amely, we  expect dat a to be {r esponse: a ny, respon seBody: an y}
  155  
  156         // / / Despite  the fact t hat FileOp erations.j ava has:
  157         // / / .header( 'Content-D isposition ', Filenam eUtils.get Name(fullP ath))
  158         // / / The foll owing does n't work:
  159         // c onst _Cont entDisposi tion = dat a.response .headers[' Content-Di sposition' ];
  160         // l ogdbg('_Co ntentDispo sition=',  _ContentDi sposition) ;
  161         // / / and this  does, bec ause it is  lowercase :
  162         // c onst _cont entDisposi tion = dat a.response .headers[' content-di sposition' ];
  163         // l ogdbg('_co ntentDispo sition=',  _contentDi sposition) ;
  164  
  165         resS etName(res , name); / / pass it  along
  166         cons t fileName  = name;
  167  
  168         if ( !fileName)  {
  169           lo gdbg('Erro r: missing  filename' );
  170           re turn res.s tatus(404) ;
  171         }
  172  
  173         let  fileBuf =  null;
  174         cons t EXT = fi leName.spl it('.').po p().toUppe rCase();
  175         if ( EXT === 'X ML') {
  176           //  XML is co pied to a  temp file!
  177           //  It could  have been  a Blob (or  LocalStor age?)
  178           //  This only  works bec ause attac hment-view er.html is  looking f or _THIS_  file.
  179           //  How will  this work  with multi ple client s? Is it a  local fil e?
  180           fi leBuf = ne w Buffer(' file sent  to ' + xml File, 'utf 8');
  181           //  Replace a ny CDA.xsl  in XML
  182           //  So that w e can use  our own cd aUrl
  183  
  184           re s.contentT ype('appli cation/oct et-stream' ); // XML  response i sn't a fil e at all,  it's a mes sage
  185           fs .writeFile (xmlFile,  xmlCDA(dat a.response Body, href CDAView),  err => {
  186              // async c all-back
  187              // Error:  Can't set  headers af ter they a re sent.
  188              fileBuf =  new Buffer ('xmlFile= ' + xmlFil e +
  189                (err ? e rr.errno +  ' ' + err .message :  'err is f alsy!'),
  190                'utf8'
  191              );
  192              if (err) {
  193                logerr(` Error: wri teFile(${x mlFile})`,  err);
  194                logerr(' Error: ' +  err.errno  + ' ' + e rr.message , err);
  195                // throw  err;
  196              } else {
  197                logdbg(' Success! w rote ', xm lFile);
  198              }
  199           }) ;
  200         } el se {
  201           //  // Normal  file alre ady has co ntents in  data.respo nseBody
  202           //  if (data. responseBo dy['type']  !== 'Buff er') {
  203           //    console .log("data .responseB ody['type' ]=", data. responseBo dy['type'] );
  204           //    logerr( 'typeof da ta.respons eBody=',ty peof data. responseBo dy);
  205           //    console .log(`data .responseB ody=${JSON .stringify (data.resp onseBody)} `);
  206           //    fileBuf  = new Buf fer('FAKE! ', 'utf8') ;
  207           //  } else {
  208           fi leBuf = ne w Buffer(d ata.respon seBody, 'u tf8');
  209           //  }
  210           re s.contentT ype(_conte ntType); / / normal f ile has sa me type as  was sent
  211         }
  212        // re s.setHeade r('x-attac hment-name ', data.re sponse.hea ders['x-at tachment-n ame']);
  213         retu rn res.sta tus(data.r esponse.st atusCode). send(fileB uf);
  214       })
  215       .catch (error =>  logerr('in  /viewAtta chment ',  error));
  216  
  217     //const  filePath =  path.join (__dirname , '../../. ./../src/a ssets/imag es/asset1. png')
  218     //const  filePath =  path.join (__dirname , '../../. ./../src/a ssets/imag es/attachm entViewerT est.txt')
  219  
  220     // const  fileStrea m = fs.cre ateReadStr eam(filePa th);
  221     // fileS tream.pipe (res);
  222  
  223   });
  224  
  225   // /attach ment/expor tAttachmen t
  226   router.pos t('/export Attachment ', (req, r es) => {
  227     const at tachmentRe quest = re q.body;
  228     rest.pos tResource( `${process .env.END_P OINT_BASE_ URI}/ars/a pi/v1/file `, attachm entRequest )
  229       .then( data => {
  230         // r es.setEnco ding('bina ry')
  231         // r es.content Type('appl ication/oc tet-stream ')
  232         // l ogdbg(data .response)
  233         cons t _content Type = dat a.response .headers[' content-ty pe'];
  234         logd bg('_conte ntType=',  _contentTy pe);
  235         res. contentTyp e(_content Type); //  same as re s.type(_co ntentType) ;
  236         res. setHeader( 'x-attachm ent-name',  data.resp onse.heade rs['x-atta chment-nam e']);
  237         cons t name = h drGetName( data.respo nse.header s);
  238         resS etName(res , name); / / pass it  along
  239         // r es.set({
  240         //    'Content- Dispositio n': `${dat a.response .headers[' content-di sposition' ]}`});
  241         let  file = nul l;
  242         // i f (/.*\/xm l/.test(_c ontentType )) {
  243         // _ contentTyp e of XML.X ML is actu ally 'appl ication/oc tet', so t hat doesn' t work.
  244         // S ince we co ntrol back -end, we c ould chang e it to 't ext/xml' ? ?
  245         if ( name === ' XML.XML')  {
  246           //  Our best  guess is t hat CDA.xs l will be  in the par ent direct ory (i.e.,  shared)
  247           fi le = new B uffer(xmlC DA(data.re sponseBody , hrefCDAE xport), 'u tf8');
  248         } el se {
  249           fi le = new B uffer(data .responseB ody, 'utf8 ');
  250         }
  251         logd bg('/expor tAttachmen t file.byt eLength=',  file.byte Length);
  252         res. status(dat a.response .statusCod e).send(fi le);
  253       })
  254       .catch (error =>  console.er ror(error) );
  255  
  256   });
  257  
  258   // /attach ment/expor tAsPDF
  259   router.pos t('/export AsPDF', (r eq, res) = > {
  260     logdbg(' /exportAsP DF post re q.body=',  req.body);
  261     logdbg(` /exportAsP DF rest.po stResource ("${proces s.env.END_ POINT_BASE _URI}/api/ v1/exportA sPDF", req .body)`);
  262     //  cons t attachId LX = req.b ody.attach IdLX;
  263     rest.pos tResource( `${process .env.END_P OINT_BASE_ URI}/ars/a pi/v1/expo rtAsPDF`,  req.body)
  264       .then( value => {
  265         //     logdbg(' value.resp onse=', va lue.respon se);
  266         logd bg('/expor tAsPDF val ue => valu e.response Body=', va lue.respon seBody);
  267         if ( !value.res ponseBody)  {
  268           //  Error occ ured
  269           lo gerr('/exp ortAsPDF e rror: resp onseBody u ndefined') ;
  270           re turn res.s tatus(500) ;
  271         }
  272         if ( value.resp onseBody[' errorCode' ]) {
  273           //  Error occ ured
  274           lo gerr('/exp ortAsPDF e rrorCode:  ', value.r esponseBod y['errorCo de']);
  275           re turn res.s tatus(500) ;
  276         }
  277         cons t contentT ype = valu e.response .headers[' content-ty pe'];
  278         logd bg('conten t-type ',  contentTyp e);
  279         res. contentTyp e(contentT ype);
  280  
  281         cons t name = h drGetName( value.resp onse.heade rs);
  282         resS etName(res , name); / / pass it  along
  283  
  284         cons t file = n ew Buffer( value.resp onseBody,  'utf8');
  285         res. status(val ue.respons e.statusCo de).send(f ile);
  286       }).cat ch(reason  => logerr( '/exportAs PDF ', rea son));
  287  
  288   });
  289  
  290   router.get ('/xml', ( req, res)  => {
  291     // /atta chment/xml
  292     // deliv er an (the ) XML>XML  file direc tly to the  browser
  293     logdbg(' /xml ', xm lFile);
  294     fs.readF ile(xmlFil e, (err, d ata) => {
  295       if (er r) {
  296         logd bg('/xml ' , JSON.str ingify(err ));
  297         res. status(500 ).json(err );
  298       } else  {
  299         logd bg('/xml O K');
  300         res. writeHead( 200, {
  301           'C ontent-Typ e': 'text/ xml'
  302         });
  303         res. write(data ); // alre ady have d ata
  304         res. end();
  305       }
  306     });
  307   });
  308  
  309   router.get ('/cda', ( req, res)  => {
  310     // /atta chment/cda
  311     // deliv er a CDA.x sl file di rectly to  the browse r, to fulf ill href=' cda' in th e xml buff er
  312     const cd aName = 's rc/assets/ xml/CDA.xs l';
  313     const cd aFile = pa th.join(ap pPath, cda Name); //  an actual  file on th e server
  314  
  315     logdbg(' /cda ', cd aFile);
  316     fs.readF ile(cdaFil e, (err, d ata) => {
  317       if (er r) {
  318         logd bg('/cda ' , JSON.str ingify(err ));
  319         res. status(500 ).json(err );
  320       } else  {
  321         logd bg('/cda O K');
  322         res. writeHead( 200, {
  323           'C ontent-Typ e': 'text/ xsl'
  324         });  // XSL, no t XML
  325         res. write(data ); // alre ady have d ata
  326         res. end();
  327       }
  328     });
  329   });
  330  
  331   router.pos t('/cleanX ml', (req,  res) => {
  332     // ??? T his only r emoves the  single fi le xmlFile
  333     // So wh y read the  directory ? just unl ink it.
  334  
  335     //  fs.r eaddir(xml Path, (err , files) = > {
  336     //    if  (err) {
  337     //       console.lo g('Error / cleanXml e rr=', err)
  338     //    }
  339     //    if  (files.so me(file =>  file ===  'XML.XML') ) {
  340     //       fs.unlink( path.join( xmlPath,'X ML.XML'),  (err) => {
  341     //         if (err)  {
  342     //           consol e.error(er r)
  343     //           return  res.statu s(500).jso n({message : 'Unable  to clean x ml temp fi le'});
  344     //         }
  345     //       })
  346     //       return res .status(20 0).json({m essage: 'x ml temp fi les have b een cleane d.'});
  347     //    }
  348     //
  349     //  })
  350     fs.exist s(xmlFile,  exists =>  {
  351       if (!e xists) {
  352         res. status(200 ).json({
  353           me ssage: 'No  XML.XML t emp files  exist.'
  354         });
  355       } else  {
  356         fs.u nlink(xmlF ile, err = > {
  357           if  (err) {
  358              //
  359              // Don't c omplain if  file did  not exist
  360              logerr(err );
  361              res.status (500).json ({
  362                message:  'Unable t o clean xm l temp fil e'
  363              });
  364           }  else {
  365              res.status (200).json ({
  366                message:  'xml temp  files hav e been cle aned.'
  367              });
  368           }
  369         });
  370       }
  371     });
  372     return r es;
  373  
  374     //  cons t filePath  = path.jo in(__dirna me, '../.. /../../att achmentVie werTemp/') ;
  375     //  fs.r eaddir(fil ePath, (er r, files)  => {
  376     //    if  (err) {
  377     //       logerr('/c leanXml er r=', err)
  378     //    }
  379     //    if  (files.so me(file =>  file ===  'XML.XML') ) {
  380     //       fs.unlink( filePath+' XML.XML',  (err) => {
  381     //         if (err)  {
  382     //           logerr (err);
  383     //           return  res.statu s(500).jso n({message : 'Unable  to clean x ml temp fi le'});
  384     //         }
  385     //       })
  386     //       return res .status(20 0).json({m essage: 'x ml temp fi les have b een cleane d.'});
  387     //    }
  388     //
  389     //  })
  390  
  391   });
  392  
  393   module.exp orts = rou ter;