/// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="file"></param> /// <returns></returns> public bool UpdateUserProfile(string name, LibNeeo.IO.File file) { bool isCompleted = false; if (!UpdateUsersDisplayName(name)) { NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidUser); } else if (file == null) { isCompleted = true; } else { file.Info = new NeeoFileInfo() { Name = _userID, Creator = _userID, MediaType = MediaType.Image, MimeType = MimeType.ImageJpeg }; if (FileManager.Save(file, FileCategory.Profile)) { isCompleted = true; } } return(isCompleted); }
/// <summary> /// Deletes the expired files from file servers. /// </summary> public static void DeleteExpiredFiles() { const string delimeter = ","; const string expiryPeriod = "expiryPeriod"; DbManager dbManager = new DbManager(); DataTable dtExpiredFiles = dbManager.GetExpiredFile(DateTime.UtcNow, Convert.ToInt16(ConfigurationManager.AppSettings[expiryPeriod])); string recordIDs = ""; foreach (DataRow dr in dtExpiredFiles.Rows) { try { if (File.Delete(dr["fullPath"].ToString())) { recordIDs += dr["id"].ToString() + ","; } } catch (Exception exception) { LogManager.CurrentInstance.ErrorLogger.LogError( MethodBase.GetCurrentMethod().DeclaringType, exception.Message, exception); } } if (recordIDs != string.Empty) { dbManager.DeleteSharedFile(recordIDs, delimeter); } }
protected void SetResponseWithFileData(LibNeeo.IO.File file) { string contentType = file.Info.MimeType.GetDescription(); if (file.Info.MimeType == MimeType.DocWordx) { contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } if (file.Info.MimeType == MimeType.DocPptx) { contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } if (file.Info.MimeType == MimeType.DocXlsx) { contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } _httpContext.Response.ClearContent(); _httpContext.Response.ClearHeaders(); _httpContext.Response.Buffer = true; _httpContext.Response.ContentType = contentType; _httpContext.Response.AddHeader("Content-Length", file.Info.Length.ToString()); _httpContext.Response.TransmitFile(file.Info.FullPath); //_httpContext.Response.AddHeader("Ext", MimeTypeMapping.GetMimeTypeDetail(file.Info.MimeType.GetDescription()).Extension); //_httpContext.Response.BinaryWrite(System.IO.File.ReadAllBytes(file.Info.FullPath)); _httpContext.Response.Flush(); _httpContext.Response.End(); }
/// <summary> /// Gets the user's avatar base on the file path of avatar. /// </summary> /// <returns>It returns Avatar if exists.</returns> public Stream GetAvatarStream() { LibNeeo.IO.File file = FileManager.GetFile(_userID, FileCategory.Profile, MediaType.Image); if (file != null) { return(LibNeeo.IO.File.GetStream(file.Info.FullPath)); } return(null); }
public async Task <HttpResponseMessage> UploadMultipartAsync() { string fileId = null; if (!Request.Headers.Contains("uid")) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } if (Request.Headers.Contains("id")) { fileId = Request.Headers.GetValues("id").First(); } string uId = Request.Headers.GetValues("uid").First(); if (Request.Content.IsMimeMultipartContent()) { MultipartMemoryStreamProvider provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()); foreach (HttpContent content in provider.Contents) { if (content.Headers.ContentType == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } if (content.Headers.ContentDisposition.FileName == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } string contentType = content.Headers.ContentType.ToString(); string sourceExtension = content.Headers.ContentDisposition.FileName.Split(new char[] { '.' }).Last().Split(new char[] { '"' }).First(); if (!MimeTypeMapping.ValidateMimeType(contentType)) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } using (var stream = content.ReadAsStreamAsync().Result) { File uploadedFile = FileFactory.Create(contentType); uploadedFile.Info.Name = fileId; //file.Info.Extension = "." + sourceExtension; uploadedFile.Info.Creator = uId; uploadedFile.Info.Length = Convert.ToInt64(content.Headers.ContentLength); uploadedFile.FileStream = new FileDataStream() { Stream = stream }; SharedMedia.Save(new NeeoUser(uId), uploadedFile, FileCategory.Shared, 0); var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.OK; response.Headers.Location = new Uri(uploadedFile.Info.Url); return(response); } } } return(Request.CreateResponse(HttpStatusCode.BadRequest)); }
/// <summary> /// Processes the http request to send the required response. /// </summary> /// <remarks>It is used to send image data to the requester if the request </remarks> /// <param name="context">An object holding http context object for setting up response header on sending response.</param> public void ProcessRequest(HttpContext context) { _httpContext = context; LibNeeo.IO.File file = null; ulong timeStamp = 0; short fileClass = 0; if (!NeeoUtility.IsNullOrEmpty(context.Request.QueryString["id"]) && !NeeoUtility.IsNullOrEmpty(context.Request.QueryString["sig"]) && !NeeoUtility.IsNullOrEmpty(context.Request.QueryString["fc"]) && !NeeoUtility.IsNullOrEmpty(context.Request.QueryString["mt"])) { string fileID = HttpUtility.UrlEncode(context.Request.QueryString["id"].ToString()); FileCategory fileCategory = (FileCategory)Convert.ToInt16(context.Request.QueryString["fc"]); MediaType mediaType = (MediaType)Convert.ToInt16(context.Request.QueryString["mt"]); if (NeeoUtility.GenerateSignature(fileID + fileCategory.ToString("D") + mediaType.ToString("D")) == context.Request.QueryString["sig"].ToString()) { file = GetRequestedFile(fileID, fileCategory, mediaType); if (file != null) { SetResponseWithFileData(file); } else { Logger.LogManager.CurrentInstance.ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "File ID: " + fileID + ", File Category: Shared, Status: File does not exists."); } } } else if (!NeeoUtility.IsNullOrEmpty(context.Request.QueryString["id"]) && !NeeoUtility.IsNullOrEmpty(context.Request.QueryString["sig"])) { // This part is to give backward compatibility for shared file service given with release 3 string fileID = HttpUtility.UrlEncode(context.Request.QueryString["id"].ToString()); if (NeeoUtility.GenerateSignature(fileID) == context.Request.QueryString["sig"].ToString()) { file = GetRequestedFile(fileID, FileCategory.Shared, MediaType.Image); if (file != null) { SetResponseWithFileData(file); } else { Logger.LogManager.CurrentInstance.ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "File ID: " + fileID + ", File Category: Group, Status: File does not exists."); } } } SetResponseHeaders((int)HttpStatusCode.BadRequest); }
public HttpResponseMessage Post([FromBody] UploadGroupIconRequest request) { if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } LogRequest(request); ulong temp = 0; request.Uid = request.Uid.Trim(); request.gID = request.gID.ToLower(); try { var file = new LibNeeo.IO.File() { Info = new NeeoFileInfo() { Creator = request.Uid, MimeType = MimeType.ImageJpeg, MediaType = MediaType.Image }, Data = request.data, }; if (NeeoGroup.SaveGroupIcon(request.Uid, request.gID.ToLower(), file)) { return(Request.CreateResponse(HttpStatusCode.OK)); } else { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } } catch (ApplicationException appExp) { return(SetCustomResponseMessage("", (HttpStatusCode)(CustomHttpStatusCode)(Convert.ToInt32(appExp.Message)))); } catch (Exception exception) { LogManager.CurrentInstance.ErrorLogger.LogError( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception); return(SetCustomResponseMessage("", (HttpStatusCode)CustomHttpStatusCode.ServerInternalError)); } }
/// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="file"></param> /// <param name="fileCategory"></param> /// <param name="recipientCount"></param> /// <param name="isOverloaded"></param> /// <returns></returns> public static bool Save(NeeoUser user, File file, FileCategory fileCategory, ushort recipientCount = 0, bool isOverloaded = true) { bool isOperationCompleted = false; file.Info.Name = NeeoUtility.IsNullOrEmpty(file.Info.Name) ? Guid.NewGuid().ToString("N") : file.Info.Name; var server = FileServerManager.GetInstance().SelectServer(); DbManager dbManager = new DbManager(); file.Info.FullPath = server.GetServerNetworkPath(); try { //file.Info.CreationTimeUtc = DateTime.UtcNow; FileManager.Save(file, FileCategory.Shared); if (dbManager.StartTransaction()) { if (dbManager.InsertSharedFileInformation(file.Info.Name, file.Info.Creator, Convert.ToUInt16(file.Info.MediaType), Convert.ToUInt16(file.Info.MimeType), Path.Combine(file.Info.FullPath, file.Info.FullName), file.Info.CreationTimeUtc, recipientCount, file.Info.Length, file.Info.Hash)) { file.Info.Url = NeeoUrlBuilder.BuildFileUrl(server.LiveDomain, file.Info.Name, FileCategory.Shared, file.Info.MediaType); dbManager.CommitTransaction(); isOperationCompleted = true; } else { dbManager.RollbackTransaction(); } } } catch (ApplicationException appException) { dbManager.RollbackTransaction(); throw; } catch (Exception exception) { dbManager.RollbackTransaction(); LogManager.CurrentInstance.ErrorLogger.LogError(MethodBase.GetCurrentMethod().DeclaringType, exception.Message, exception); throw new ApplicationException(CustomHttpStatusCode.ServerInternalError.ToString("D")); } return(isOperationCompleted); }
public async Task <HttpResponseMessage> Put([FromUri] string type, [FromUri] string sessionID) { long startingPosition = 0; try { if (type != "resumable" || NeeoUtility.IsNullOrEmpty(sessionID)) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } var session = await UploadSessionManager.ValidateSessionAsync(sessionID); if (session == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } session.FileInfo.Extension = MimeTypeMapping.GetMimeTypeDetail(session.FileInfo.MimeType.GetDescription()).Extension; long? contentLength = Request.Content.Headers.ContentLength; string contentType = Request.Content.Headers.ContentType == null ? null : Request.Content.Headers.ContentType.ToString(); if (Request.Content.Headers.Contains("Content-Range")) { var contentRange = Request.Content.Headers.GetValues("Content-Range").First(); if (contentRange == "bytes */*") { var file = SharedMedia.GetMedia(session.FileInfo.Name, session.FileInfo.MediaType); if (file != null) { var response = Request.CreateResponse((HttpStatusCode)308); response.Headers.Add("Range", "bytes=0-" + file.Info.Length); response.ReasonPhrase = "Resumable Incomplete"; return(response); } else { var response = Request.CreateResponse((HttpStatusCode)308); response.Headers.Add("Range", "bytes=0-0"); response.ReasonPhrase = "Resumable Incomplete"; return(response); } } else { var delimeter = new char[] { '-', '/', ' ' }; var rangeValues = contentRange.Split(delimeter); if (rangeValues.Length != 4) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } if (Convert.ToInt64(rangeValues[2]) != session.FileInfo.Length) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } startingPosition = Convert.ToInt64(rangeValues[1]); } } if (contentLength == null || contentLength > (long)session.FileInfo.Length) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } using (var stream = await Request.Content.ReadAsStreamAsync()) { var newFile = new File() { Info = session.FileInfo, FileStream = new FileDataStream() { Stream = stream, Postion = startingPosition } }; if (SharedMedia.Save(new NeeoUser(session.FileInfo.Creator), newFile, FileCategory.Shared, 0)) { // check the length of the file with the database then delete it. await UploadSessionManager.DeleteSessionAsync(sessionID); var response = new HttpResponseMessage(HttpStatusCode.Created); response.Headers.Location = new Uri(newFile.Info.Url); return(response); } } return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } catch (Exception exception) { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> UploadDataAsync(ApiController controller) { if (controller.Request.Content.Headers.ContentType == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } if (Request.Content.Headers.ContentType.ToString().Split(new char[] { ';' })[0] != "application/json") { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } var requestBody = await Request.Content.ReadAsStringAsync(); var fileRequest = JsonConvert.DeserializeObject <UploadFileRequest>(requestBody); controller.Validate(fileRequest); if (!ModelState.IsValid) { return(controller.Request.CreateResponse(HttpStatusCode.BadRequest)); } if (!NeeoUtility.IsNullOrEmpty(fileRequest.FId)) { Guid resultingGuid; if (!Guid.TryParse(fileRequest.FId, out resultingGuid)) { LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" + "fID : " + fileRequest.FId + " is not parseable."); return(Request.CreateResponse(HttpStatusCode.BadRequest)); } fileRequest.FId = resultingGuid.ToString("N").ToLower(); } NeeoUser sender = new NeeoUser(fileRequest.Uid); File uploadedFile = FileFactory.Create(fileRequest.MimeType.GetDescription()); uploadedFile.Info.Name = fileRequest.FId; uploadedFile.Info.Creator = fileRequest.Uid; uploadedFile.Data = fileRequest.Data; //LibNeeo.IO.File uploadingFile = new LibNeeo.IO.File() //{ // Info = new NeeoFileInfo() // { // MediaType = MediaType.Image, // MimeType = fileRequest.MimeType, // Extension = "jpg" // }, // Data = fileRequest.Data //}; SharedMedia.Save(sender, uploadedFile, FileCategory.Shared, 0); #region log user request and response /*********************************************** * To log user response ***********************************************/ if (_logRequestResponse) { LogManager.CurrentInstance.InfoLogger.LogInfo( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Response ===> " + uploadedFile.Info.Url); } #endregion log user request and response return(Request.CreateResponse(HttpStatusCode.OK, new Dictionary <string, string>() { { "UploadFileResult", uploadedFile.Info.Url } })); }
/// <summary> /// /// </summary> /// <param name="uID"></param> /// <param name="data"></param> /// <param name="gID"></param> public void UploadGroupIcon(string uID, string data, string gID) { ulong temp = 0; uID = (uID != null) ? uID.Trim() : uID; #region log user request and response /*********************************************** * To log user request ***********************************************/ if (_logRequestResponse) { LogManager.CurrentInstance.InfoLogger.LogInfo( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" + "Request ===> senderID : " + uID + ", groupID : " + gID); } #endregion // #region Verify User //var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; //string keyFromClient = request.Headers["key"]; //if (NeeoUtility.AuthenticateUserRequest(uID, keyFromClient)) //{ // #endregion if (NeeoUtility.IsNullOrEmpty(uID) || !ulong.TryParse(uID, out temp) || NeeoUtility.IsNullOrEmpty(data) || NeeoUtility.IsNullOrEmpty(gID)) { NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments); } else { gID = gID.ToLower(); try { var file = new LibNeeo.IO.File() { Info = new NeeoFileInfo() { Creator = uID, MimeType = MimeType.ImageJpeg, MediaType = MediaType.Image }, Data = data, }; if (!NeeoGroup.SaveGroupIcon(uID, gID.ToLower(), file)) { NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError); } } catch (ApplicationException appExp) { NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)(Convert.ToInt32(appExp.Message))); } catch (Exception exception) { LogManager.CurrentInstance.ErrorLogger.LogError( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception); NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError); } } //} //else //{ // NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode) HttpStatusCode.Unauthorized); //} }
/// <summary> /// /// </summary> /// <param name="uID"></param> /// <param name="data"></param> /// <param name="mimeType"></param> /// <param name="recipientCount"></param> /// <returns></returns> public string UploadFile(string uID, string fID, string data, ushort mimeType, ushort recipientCount) { ulong temp = 0; string resultUrl = null; uID = (uID != null) ? uID.Trim() : uID; fID = (fID != null) ? fID.Trim() : fID; fID = (fID != null) ? fID.Trim() : fID; #region log user request and response /*********************************************** * To log user request ***********************************************/ if (_logRequestResponse) { LogManager.CurrentInstance.InfoLogger.LogInfo( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" + "Request ===> senderID : " + uID + ", mimeType : " + mimeType.ToString() + ", fID : " + fID + ", recipientCount : " + recipientCount.ToString()); } #endregion // #region Verify User //var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; //string keyFromClient = request.Headers["key"]; //if (NeeoUtility.AuthenticateUserRequest(uID, keyFromClient)) //{ // #endregion if (NeeoUtility.IsNullOrEmpty(uID) && !ulong.TryParse(uID, out temp) && !Enum.IsDefined(typeof(MimeType), mimeType) && (recipientCount == 0 || recipientCount >= 255) && NeeoUtility.IsNullOrEmpty(data)) { NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments); } else { if (!NeeoUtility.IsNullOrEmpty(fID)) { Guid resultingGuid; if (!Guid.TryParse(fID, out resultingGuid)) { LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" + "fID : " + fID + " is not parseable."); NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments); return(resultUrl); } fID = resultingGuid.ToString("N").ToLower(); } NeeoUser sender = new NeeoUser(uID); try { LibNeeo.IO.File file = new LibNeeo.IO.File() { Info = new NeeoFileInfo() { Creator = uID, MediaType = MediaType.Image, MimeType = (MimeType)mimeType, Name = fID }, Data = data }; if (SharedMedia.Save(sender, file, FileCategory.Shared, recipientCount)) { resultUrl = file.Info.Url; } #region log user request and response /*********************************************** * To log user response ***********************************************/ if (_logRequestResponse) { LogManager.CurrentInstance.InfoLogger.LogInfo( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Response ===> " + resultUrl); } #endregion } catch (ApplicationException appExp) { NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)(Convert.ToInt32(appExp.Message))); } catch (Exception exp) { LogManager.CurrentInstance.ErrorLogger.LogError( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, exp.Message, exp); NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.UnknownError); } } return(resultUrl); //} //else //{ // NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)HttpStatusCode.Unauthorized); // return resultUrl; //} }
/// <summary> /// /// </summary> /// <param name="userID"></param> /// <param name="groupID"></param> /// <param name="file"></param> /// <returns></returns> public static bool SaveGroupIcon(string userID, string groupID, File file) { file.Info.Name = groupID; return(FileManager.Save(file, FileCategory.Group)); }