public static void DownloadBinary(Hashtable htDbBinaryConfig) { HttpRequest request = HttpContext.Current.Request; HttpResponse response = HttpContext.Current.Response; if ((request.HttpMethod.ToUpper() != "GET") && (request.HttpMethod.ToUpper() != "HEAD")) { response.AppendHeader("Allow", "GET, HEAD"); ResponseError(response, 405, "Method Not Allowed"); return; } string parametersString = GetParameters(request).TrimEnd('/').TrimStart('/').Replace("-", "+").Replace("_", "/"); /* Replace invalid URL chars */ parametersString = SymmCryptHelper.DecryptWithAES256FixedIV(BinaryContentUtils.DatabaseBinaryEnvironmentPassword, parametersString, Convert.FromBase64String(PRIVATE_SALT)); var parameters = parametersString.Split('/'); if (parameters.Length < 3) { ResponseError(response, 400, "Bad Request"); return; } var entity = parameters[0].ToLower(); var attribute = parameters[1].ToLower(); var id = parameters[2]; object objt = htDbBinaryConfig[entity + "/" + attribute]; if (objt == null) { ResponseError(response, 404, "Not Found"); return; } DbBinaryConfig dbBinaryConfig; dbBinaryConfig = (DbBinaryConfig)objt; byte[] buffer = GetDatabaseBinaryAttribute(id, dbBinaryConfig); if (buffer == null) { ResponseError(response, 404, "Not Found"); } else { string md5Hash = SecureHashHelper.Hash(buffer); response.Clear(); response.StatusCode = 200; //OK response.ContentType = RuntimePlatformUtils.GetMIMEType(buffer); response.AppendHeader("ETag", "\"" + md5Hash + "\""); response.AppendHeader("Accept-Ranges", "none"); if (request.HttpMethod.ToUpper() == "GET") { BinaryWrite(response, buffer); } End(response); } }
protected string GetMIMEType() { object acceptHeader = Request.Headers["Accept"]; string[] accept; if (acceptHeader == null) { accept = new string[0]; } else { accept = acceptHeader.ToString().Split(new char[] { ',' } , 250); } int nTakesJPEG = 100000; int nTakesJPG = 100000; string mime; for (int i = 0; i < accept.Length; i++) { mime = accept[i].Trim(); if (string.Equals(mime, "image/jpeg", StringComparison.CurrentCultureIgnoreCase)) { nTakesJPEG = i; } if (string.Equals(mime, "image/jpg", StringComparison.CurrentCultureIgnoreCase)) { nTakesJPG = i; } } mime = RuntimePlatformUtils.GetMIMEType(getExtension()); if (string.Equals(mime, "image/jpeg", StringComparison.CurrentCultureIgnoreCase) || string.Equals(mime, "image/jpg", StringComparison.CurrentCultureIgnoreCase)) { if (nTakesJPEG < nTakesJPG) { mime = "image/jpeg"; } else { mime = "image/jpg"; } } return(mime); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = (string)reader.Value; if (value == null) { // NullValue. return(null); } var content = Convert.FromBase64String(value); if (CanConvert(objectType)) { var mimeType = RuntimePlatformUtils.GetMIMEType(content, out _); if (mimeType.EqualsIgnoreCase("image/jpeg") || mimeType.EqualsIgnoreCase("image/jpg")) { // Fix image orientation. return(EXIFUtils.FixEXIF(content)); } } return(content); }
protected IHttpActionResult endpoint_binary(string binaryDetailsCipher) { AppInfo appInfo = null; HeContext heContext = null; try { HttpResponseMessage response = new HttpResponseMessage(); appInfo = AppInfo.GetAppInfo(); heContext = appInfo.OsContext; if (appInfo == null || !appInfo.IsApplicationEnabled) { response.StatusCode = HttpStatusCode.ServiceUnavailable; return(ResponseMessage(response)); } ValidateRequestSecurity(); ValidateRequestLogin(appInfo, heContext, true); int userId = heContext.Session.UserId; byte[] content; var statusCode = (HttpStatusCode)BinaryContentUtils.GetBinaryContent(ScreenServicesApiController.AllDbBinaryConfigs, binaryDetailsCipher, userId, out content); response.StatusCode = statusCode; if (statusCode == HttpStatusCode.OK) { string mimeType = RuntimePlatformUtils.GetMIMEType(content); response.Headers.CacheControl = new CacheControlHeaderValue() { Private = true, MaxAge = TimeSpan.FromDays(7), }; response.Headers.AcceptRanges.Clear(); response.Headers.AcceptRanges.Add("none"); response.Content = new ByteArrayContent(content); response.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType); } return(ResponseMessage(response)); } catch (Exception ex) { DatabaseAccess.FreeupResources(false); var licensingException = ex as LicensingException; if (licensingException != null) { return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable))); } ErrorLog.LogApplicationError(ex, heContext, ""); HttpStatusCode errorStatusCode = HttpStatusCode.InternalServerError; var exposeRestException = ex as ExposeRestException; if (exposeRestException != null) { errorStatusCode = exposeRestException.StatusCode; } return(ResponseMessage(new HttpResponseMessage(errorStatusCode))); } }
private void Page_Load(object sender, System.EventArgs e) { HttpContext current = HttpContext.Current; HttpRequest request = current.Request; HttpResponse response = current.Response; int cacheTime = 0; if ((!string.Equals(HttpContext.Current.Request.HttpMethod, "GET", StringComparison.CurrentCultureIgnoreCase)) && (!string.Equals(HttpContext.Current.Request.HttpMethod, "HEAD", StringComparison.CurrentCultureIgnoreCase))) { response.Clear(); response.Status = "405 Method Not Allowed"; response.StatusCode = 405; response.AppendHeader("Allow", "GET, HEAD"); response.StatusDescription = "Method Not Allowed"; response.Write("Method Not Allowed"); response.End(); return; } string parameters = request.PathInfo; if (parameters.Substring(1).IndexOf("/") == parameters.Substring(1).LastIndexOf("/")) { parameters = "/" + RuntimePlatformUtils.Images.DecryptImageDetails(parameters.Substring(1, parameters.LastIndexOf("/") - 1).Replace("-", "+").Replace("_", "/")) + parameters.Substring(parameters.LastIndexOf("/")); } else { parameters = ""; } Match m = ParametersRegex.Match(parameters); if (!m.Success) { response.Clear(); response.Status = "400 Bad Request"; response.StatusCode = 400; response.StatusDescription = "Bad Request"; response.Write("Bad Request"); response.End(); return; } _entity = m.Groups["Entity"].Value.ToLower(); _attribute = m.Groups["Attribute"].Value.ToLower(); _id = m.Groups["Id"].Value; _filename = m.Groups["Filename"].Value.ToLower(); object objt = htDbImgConfig[_entity + "/" + _attribute]; if (objt == null) { NotFound(response); return; } DbImgConfig dbimgconfig; dbimgconfig = (DbImgConfig)objt; byte[] buffer = new byte[0]; string md5Hash = ""; string reqcachecontrol = ""; string reqpragma = ""; if (Request.Headers["Cache-Control"] != null) { reqcachecontrol = Request.Headers["Cache-Control"].ToString().Trim(); } if (Request.Headers["Pragma"] != null) { reqpragma = Request.Headers["Pragma"].ToString().Trim(); } bool refreshItem = ((reqcachecontrol == "no-cache") || (reqpragma == "no-cache") || (reqcachecontrol == "max-age=0")); object tmpHash = RuntimeCache.Instance.Get(new CacheKey("DbImage/" + _entity + "/" + _attribute + "/" + _id + "/" + _filename)); if ((!refreshItem) && (tmpHash != null)) { DbImgCacheFile cacheinfo = (DbImgCacheFile)tmpHash; md5Hash = cacheinfo.md5Hash; buffer = cacheinfo.buffer; } else { OutSystems.HubEdition.Extensibility.Data.DMLService.IDMLIdentifiers identifiers = null; IDatabaseAccessProvider dbAccessProvider; if (string.IsNullOrEmpty(dbimgconfig.DBConnection)) { dbAccessProvider = DatabaseAccess.ForCurrentDatabase; identifiers = DatabaseAccess.ForCurrentDatabase.DatabaseServices.DMLService.Identifiers; } else { dbAccessProvider = DatabaseAccess.ForDBConnection(dbimgconfig.DBConnection); identifiers = DatabaseAccess.ForDBConnection(dbimgconfig.DBConnection).DatabaseServices.DMLService.Identifiers; } using (Transaction trans = dbAccessProvider.GetReadOnlyTransaction()) { try { using (Command cmd = trans.CreateCommand( "SELECT " + identifiers.EscapeIdentifier(dbimgconfig.Attribute.ToUpper()) + " FROM " + dbimgconfig.EntityGetter(null, BuiltInFunction.GetCurrentLocale()) + " WHERE " + identifiers.EscapeIdentifier(dbimgconfig.Id.ToUpper()) + " = @ID")) { cmd.CreateParameter("@ID", (DbType)dbimgconfig.IdDbType, _id); using (IDataReader reader = cmd.ExecuteReader()) { if ((reader.IsClosed) || (!reader.Read())) { NotFound(response); return; } long size = reader.GetBytes(0, 0, null, 0, 0); buffer = new byte[size]; reader.GetBytes(0, 0, buffer, 0, buffer.Length); } } } catch (Exception) { NotFound(response); return; } } md5Hash = HashHelper.Hash(buffer); if (dbimgconfig.CacheTime != 0) { DateTime absoluteexpire = DateTime.UtcNow; switch (dbimgconfig.CacheTime) { case 1: absoluteexpire = absoluteexpire.AddHours(1); break; case 2: absoluteexpire = absoluteexpire.AddDays(1); break; case 3: absoluteexpire = absoluteexpire.AddDays(7); break; } RuntimeCache.Instance.Add(new CacheKey("DbImage/" + _entity + "/" + _attribute + "/" + _id + "/" + _filename), new DbImgCacheFile(md5Hash, buffer), null, absoluteexpire, CacheUtils.NoSliding, OutSystems.RuntimeCommon.Caching.CacheItemPriority.Removable); } } bool isValidImage; cacheTime = dbimgconfig.CacheTime; response.Clear(); response.ContentType = RuntimePlatformUtils.GetMIMEType(buffer, out isValidImage); if (!isValidImage && RuntimePlatformSettings.Security.EnforceValidTypesOnBinaryEndpoints.GetValue()) { InternalError(response); return; } response.Status = "200 OK"; response.StatusCode = 200; response.StatusDescription = "OK"; response.AppendHeader("Content-MD5", md5Hash); response.AppendHeader("Last-Modified", "Sat, 01 Jan 2000 00:00:00 GMT"); response.AppendHeader("Cache-Control", _cachecontrolstr[cacheTime]); response.AppendHeader("ETag", "\"" + md5Hash + "\""); response.AppendHeader("Accept-Ranges", "none"); switch (cacheTime) { case 0: { response.Expires = -1; break; } case 1: { response.Expires = 60; // 1 hour break; } case 2: { response.Expires = 1440; // 1 day - 60*24 break; } case 3: { response.Expires = 10080; // 1 week - 60*24*7 break; } } if (string.Equals(HttpContext.Current.Request.HttpMethod, "GET", StringComparison.CurrentCultureIgnoreCase)) { response.BinaryWrite(buffer); } response.End(); }