CernerFhirController.cs 20.4 KB
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Xml;
using ADAM.CernerFHIR.Client;
using ADAM.CernerFHIR.Helper;
using ADAM.CernerFHIR.Model;
using AIAHTML5.API.Models;
using eLearningPlayer.model;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;

namespace AIAHTML5.API.Controllers
{
    public class CernerFhirController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public void Get(string id)
        {
            //Update cerner user session values.
            var cernerSessionId = id;// jsonData["sessionId"].Value<string>(); 
            var db = new DBModel();
            var CernerUserSession = db.CheckCernerUserSession(cernerSessionId).SingleOrDefault();
            var NewLoginResult = AsyncToSyncTaskHelper.AsyncHelpers.RunSync(() => ADAM.CernerFHIR.Client.ResourceProcessor.GetCernerResourceRefreshToken(CernerUserSession.LoginResult));
            NewLoginResult.EndPointURL = NewLoginResult?.EndPointURL ?? CernerUserSession.LoginResult.EndPointURL;
            if (NewLoginResult != null)
            {
                var UpdatedCernerUserSession = new CernerUserSessionInfo()
                {
                    CernerCode = CernerUserSession.CernerCode,
                    FhirUserSessionId = cernerSessionId,
                    CernerInfoJWT = CernerUserSession.CernerInfoJWT,
                    LoginResult = NewLoginResult
                };
                db.UpdateCernerFhirSessionInfo(UpdatedCernerUserSession);
            }
            

            //HttpResponseMessage response = null;
            //return response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = null };
        }

        // POST api/<controller>
        public HttpResponseMessage Post([FromBody]JObject cernerimageAIA)
        {
            HttpResponseMessage response = null;

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(cernerimageAIA);

            var Base64ImageData = cernerimageAIA["data"].Value<string>();
            var Base64ImageName = cernerimageAIA["name"].Value<string>();
            var Base64ImageBlob = cernerimageAIA["blob"].Value<object>();
            var Base64ImageInfo = cernerimageAIA["imageInfo"].Value<object>();
            var Base64ImageInfoJson = cernerimageAIA["imageInfoJson"].Value<object>();
            var CernerUserSessionId = cernerimageAIA["CernerUserSessionId"].Value<string>();

            dynamic CernerAIAImageInfo = new {
                Data = Base64ImageData,
                Name = Base64ImageName,
                Blob = Base64ImageBlob,
                Info = Base64ImageInfo,
                infoJson = Base64ImageInfoJson,
                SessionId = CernerUserSessionId
            };
            
            // Upload data to cerner Fhir resource server
            UploadDocumentToCerner(CernerAIAImageInfo);

            response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = null };
            return response;
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }

        [HttpGet]
        [Route("UpdateToken")]
        public HttpResponseMessage UpdateCernerToken(string sessionId)
        {
            //Update cerner user session values.
            var cernerSessionId = sessionId;// jsonData["sessionId"].Value<string>(); 
            var db = new DBModel();
            var CernerUserSession = db.CheckCernerUserSession(cernerSessionId).SingleOrDefault();
            var NewLoginResult = AsyncToSyncTaskHelper.AsyncHelpers.RunSync(() => ADAM.CernerFHIR.Client.ResourceProcessor.GetCernerResourceRefreshToken(CernerUserSession.LoginResult));
            NewLoginResult.EndPointURL = NewLoginResult.EndPointURL ?? CernerUserSession.LoginResult.EndPointURL;
            var UpdatedCernerUserSession = new CernerUserSessionInfo()
            {
                CernerCode = CernerUserSession.CernerCode,
                FhirUserSessionId = cernerSessionId,
                CernerInfoJWT = CernerUserSession.CernerInfoJWT,
                LoginResult = NewLoginResult
            };
            db.UpdateCernerFhirSessionInfo(UpdatedCernerUserSession);

            HttpResponseMessage response = null;
            return response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = null };
        }

        #region Cerner fhir resource call

        [NonAction]
        public void UploadDocumentToCerner(dynamic CernerAIAImageInfo)
        {
            var ImageHtmlTag = ConvertToImageHtmlTag(CernerAIAImageInfo.Data);
            var ImageName = CernerAIAImageInfo.Name.Split('.')[0];
            var finalHtml = CreateXHtml(ImageHtmlTag, ImageName);

            finalHtml = AddSelfClosingTags(finalHtml);

            //... Convert to rtf document.(Only applying inline styles to html, not really converting to rtf)
            //finalHtml = ConvertHtmlToText(finalHtml);// ConvertToRtfDocument(finalHtml);

            var base64EncodeHtmlData = Base64Encode(finalHtml);
            string[] PidGids = {"","", ImageName };
            //var VocabCode = new List<MedicalVocabulary>();
            var db = new DBModel();
            var CernerFhirSessionInfo = db.GetCernerFhirSessionInfo(CernerAIAImageInfo.SessionId);
            var loginResult = (LoginResult)CernerFhirSessionInfo.LoginResult;
            var cernerInfoJWT = (CernerInfoJWT)CernerFhirSessionInfo.CernerInfoJWT;

            var documentPath = Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "Content", "DocumentReference.txt");
            string documentFormat = File.ReadAllText(documentPath);
            
            var AsyncTask = AsyncToSyncTaskHelper.AsyncHelpers.RunSync<string>(() => ADAM.CernerFHIR.Client.DocumentReferenceResource.PostDocumentReferenceAsync(base64EncodeHtmlData, PidGids, null, loginResult, cernerInfoJWT, documentFormat));
            var DocumentId = AsyncTask.Split(',')[1];
            
            var AIAImageInfo = new CernerUserImageAIA
            {
                DocumentId = DocumentId,
                JsonData = CernerAIAImageInfo.infoJson.ToString(),
                PatientId = cernerInfoJWT.PatientId,
                Encounter = cernerInfoJWT.Encounter,
                Code = CernerFhirSessionInfo.CernerCode
            };
            // save this DocumentId with the Json data to AIA database.
            //Create a object.
            db.SaveAIAImageIdWithJsondataForCerner(AIAImageInfo);
            
        }

        private string ConvertToImageHtmlTag(string AIAImageDataURL)
        {
            return $"<div><img src=\"{AIAImageDataURL}\"/></div>";
        }

        private string CreateXHtml(string rawhtml, string title)
        {
            var meta = "<meta http-equiv=\"x-ua-compatible\" content=\"IE=edge\"/>";

            StringWriter s = new StringWriter();
            s.WriteLine("{0}", "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
            s.WriteLine("{0}", "<html lang=\"en\" xmlns:adam=\"urn:DataProcessor\" xmlns:ax=\"http://www.adam.com\" xmlns:exsl=\"http://exslt.org/common\">");
            s.WriteLine("{0}", meta);
            s.WriteLine("{0}", "<head>");
            s.WriteLine("<title>{0}</title>", title);
            s.WriteLine("{0}", "</head>");
            s.WriteLine("{0}", "<body>");
            s.WriteLine("{0}", rawhtml);
            s.WriteLine("{0}", "</body>");
            s.WriteLine("{0}", "</html>");

            return s.ToString();
        }

        private string AddSelfClosingTags(string html)
        {
            string res = string.Empty;

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            doc.DocumentNode.Descendants("script").ToList().ForEach(x => { x.Remove(); });

            //Change all img instance src to Base64.
            doc.DocumentNode.Descendants("img")
                                        .Where(e =>
                                        {
                                            string src = e.GetAttributeValue("src", null) ?? "";
                                            return !string.IsNullOrEmpty(src);
                                        })
                                        .ToList()
                                        .ForEach(x =>
                                        {
                                            //if (!(x.OuterHtml.Contains("ftradamlogo")))
                                            x.SetAttributeValue("style", "max-width:800px;");

                                            //string currentSrcValue = x.GetAttributeValue("src", null);
                                            //currentSrcValue = currentSrcValue.Replace("../..", baseUrl);
                                            //var imageBase64Data = ConvertImageURLToBase64(currentSrcValue);

                                            //x.SetAttributeValue("src", "data:image/jpeg;base64," + imageBase64Data);
                                        });

            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            doc.Save(xw);

            return res = sw.ToString();
        }

        private static string ConvertHtmlToText(string source)
        {

            string result;

            // Remove HTML Development formatting
            // Replace line breaks with space
            // because browsers inserts space
            result = source.Replace("\r", " ");
            // Replace line breaks with space
            // because browsers inserts space
            result = result.Replace("\n", " ");
            // Remove step-formatting
            result = result.Replace("\t", string.Empty);
            // Remove repeating speces becuase browsers ignore them
            result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                  @"( )+", " ");

            // Remove the header (prepare first by clearing attributes)
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*head([^>])*>", "<head>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"(<( )*(/)( )*head( )*>)", "</head>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(<head>).*(</head>)", string.Empty,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // remove all scripts (prepare first by clearing attributes)
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*script([^>])*>", "<script>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"(<( )*(/)( )*script( )*>)", "</script>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //result = System.Text.RegularExpressions.Regex.Replace(result, 
            //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
            //         string.Empty, 
            //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"(<script>).*(</script>)", string.Empty,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // remove all styles (prepare first by clearing attributes)
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*style([^>])*>", "<style>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"(<( )*(/)( )*style( )*>)", "</style>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(<style>).*(</style>)", string.Empty,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // insert tabs in spaces of <td> tags
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*td([^>])*>", "\t",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // insert line breaks in places of <BR> and <LI> tags
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*br( )*>", "\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*li( )*>", "\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // insert line paragraphs (double line breaks) in place
            // if <P>, <DIV> and <TR> tags
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*div([^>])*>", "\r\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*tr([^>])*>", "\r\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<( )*p([^>])*>", "\r\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // Remove remaining tags like <a>, links, images,
            // comments etc - anything thats enclosed inside < >
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<[^>]*>", string.Empty,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // replace special characters:
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&nbsp;", " ",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&bull;", " * ",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&lsaquo;", "<",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&rsaquo;", ">",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&trade;", "(tm)",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&frasl;", "/",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"<", "<",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @">", ">",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&copy;", "(c)",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&reg;", "(r)",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            // Remove all others. More can be added, see
            // http://hotwired.lycos.com/webmonkey/reference/special_characters/
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     @"&(.{2,6});", string.Empty,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);


            // make line breaking consistent
            result = result.Replace("\n", "\r");

            // Remove extra line breaks and tabs:
            // replace over 2 breaks with 2 and over 4 tabs with 4. 
            // Prepare first to remove any whitespaces inbetween
            // the escaped characters and remove redundant tabs inbetween linebreaks
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\r)( )+(\r)", "\r\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\t)( )+(\t)", "\t\t",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\t)( )+(\r)", "\t\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\r)( )+(\t)", "\r\t",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            // Remove redundant tabs
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\r)(\t)+(\r)", "\r\r",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            // Remove multible tabs followind a linebreak with just one tab
            result = System.Text.RegularExpressions.Regex.Replace(result,
                     "(\r)(\t)+", "\r\t",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            // Initial replacement target string for linebreaks
            string breaks = "\r\r\r";
            // Initial replacement target string for tabs
            string tabs = "\t\t\t\t\t";
            for (int index = 0; index < result.Length; index++)
            {
                result = result.Replace(breaks, "\r\r");
                result = result.Replace(tabs, "\t\t\t\t");
                breaks = breaks + "\r";
                tabs = tabs + "\t";
            }

            // Thats it.
            return result;

        }

        private string Base64Encode(string plainText)
        {
            byte[] bytTemp = System.Text.Encoding.UTF8.GetBytes(plainText.ToString());
            return Convert.ToBase64String(bytTemp);
        }

        //private string ConvertImageURLToBase64(string url)
        //{
        //    StringBuilder _sb = new StringBuilder();

        //    Byte[] _byte = GetImage(url);

        //    if (_byte != null)
        //        _sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));

        //    return _sb.ToString();
        //}

        //private byte[] GetImage(string imageUrl)
        //{
        //    Stream stream = null;
        //    byte[] buf;

        //    try
        //    {
        //        System.Net.WebRequest req = System.Net.WebRequest.Create(imageUrl);
        //        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
        //                                                | (SecurityProtocolType)768
        //                                                | (SecurityProtocolType)3072
        //                                                | SecurityProtocolType.Ssl3;
        //        WebResponse webResponse = req.GetResponse();
        //        stream = webResponse.GetResponseStream();
        //        Encoding encode = Encoding.GetEncoding("utf-8");

        //        using (BinaryReader br = new BinaryReader(stream))
        //        {
        //            int len = (int)(webResponse.ContentLength);
        //            buf = br.ReadBytes(len);
        //            br.Close();
        //        }

        //        stream.Close();
        //        webResponse.Close();
        //    }
        //    catch (Exception exp)
        //    {
        //        buf = null;
        //    }

        //    return (buf);
        //}

        #endregion
    }
}