private void StreamFile(HttpContext context) { try { var fileId = context.Request.Query[FilesLinkUtility.FileId]; var auth = context.Request.Query[FilesLinkUtility.AuthKey]; var userId = context.Request.Query[CommonLinkUtility.ParamName_UserUserID]; Logger.Debug("BoxApp: get file stream " + fileId); var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); Logger.Error(string.Format("BoxApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url()), exc); throw exc; } Token token = null; if (Guid.TryParse(userId, out var userIdGuid)) { token = TokenHelper.GetToken(AppAttr, userIdGuid); } if (token == null) { Logger.Error("BoxApp: token is null"); throw new SecurityException("Access token is null"); } var request = (HttpWebRequest)WebRequest.Create(BoxUrlFile.Replace("{fileId}", fileId) + "/content"); request.Method = "GET"; request.Headers.Add("Authorization", "Bearer " + token); using var stream = new ResponseStream(request.GetResponse()); stream.CopyTo(context.Response.Body); } catch (Exception ex) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.WriteAsync(ex.Message).Wait(); Logger.Error("BoxApp: Error request " + context.Request.Url(), ex); } try { context.Response.Body.Flush(); //TODO //context.Response.Body.SuppressContent = true; //context.ApplicationInstance.CompleteRequest(); } catch (HttpException ex) { Logger.Error("BoxApp StreamFile", ex); } }
public File <string> GetFile(string fileId, out bool editable) { Logger.Debug("BoxApp: get file " + fileId); fileId = ThirdPartySelector.GetFileId(fileId.ToString()); var token = TokenHelper.GetToken(AppAttr); var boxFile = GetBoxFile(fileId.ToString(), token); editable = true; if (boxFile == null) { return(null); } var jsonFile = JObject.Parse(boxFile); var file = ServiceProvider.GetService <File <string> >(); file.ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value <string>("id")); file.Title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name")); file.CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("created_at")); file.ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modified_at")); file.ContentLength = Convert.ToInt64(jsonFile.Value <string>("size")); file.ProviderKey = "Box"; var modifiedBy = jsonFile.Value <JObject>("modified_by"); if (modifiedBy != null) { file._modifiedByString = modifiedBy.Value <string>("name"); } var createdBy = jsonFile.Value <JObject>("created_by"); if (createdBy != null) { file._createByString = createdBy.Value <string>("name"); } var locked = jsonFile.Value <JObject>("lock"); if (locked != null) { var lockedBy = locked.Value <JObject>("created_by"); if (lockedBy != null) { var lockedUserId = lockedBy.Value <string>("id"); Logger.Debug("BoxApp: locked by " + lockedUserId); editable = CurrentUser(lockedUserId); } } return(file); }
private void ConfirmConvertFile(HttpContext context) { var fileId = context.Request.Query[FilesLinkUtility.FileId]; Logger.Debug("GoogleDriveApp: ConfirmConvertFile - " + fileId); var token = TokenHelper.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } fileId = CreateConvertedFile(driveFile, token); context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); }
private void CreateFile(HttpContext context) { var folderId = context.Request.Query[FilesLinkUtility.FolderId]; var fileName = context.Request.Query[FilesLinkUtility.FileTitle]; Logger.Debug("GoogleDriveApp: CreateFile folderId - " + folderId + " fileName - " + fileName); var token = TokenHelper.GetToken(AppAttr); var culture = UserManager.GetUsers(AuthContext.CurrentAccount.ID).GetCulture(); var storeTemplate = GlobalStore.GetStoreTemplate(); var path = FileConstant.NewDocPath + culture + "/"; if (!storeTemplate.IsDirectory(path)) { path = FileConstant.NewDocPath + "default/"; } var ext = FileUtility.InternalExtension[FileUtility.GetFileTypeByFileName(fileName)]; path += "new" + ext; fileName = FileUtility.ReplaceFileExtension(fileName, ext); string driveFile; using (var content = storeTemplate.GetReadStream("", path)) { driveFile = CreateFile(content, fileName, folderId, token); } if (driveFile == null) { Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not created"); } var jsonFile = JObject.Parse(driveFile); var fileId = jsonFile.Value <string>("id"); context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); }
public File <string> GetFile(string fileId, out bool editable) { Logger.Debug("GoogleDriveApp: get file " + fileId); fileId = ThirdPartySelector.GetFileId(fileId); var token = TokenHelper.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); editable = false; if (driveFile == null) { return(null); } var jsonFile = JObject.Parse(driveFile); var file = ServiceProvider.GetService <File <string> >(); file.ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value <string>("id")); file.Title = Global.ReplaceInvalidCharsAndTruncate(GetCorrectTitle(jsonFile)); file.CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("createdTime")); file.ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modifiedTime")); file.ContentLength = Convert.ToInt64(jsonFile.Value <string>("size")); file.ModifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value <string>(); file.ProviderKey = "Google"; var owners = jsonFile["owners"]; if (owners != null) { file.CreateByString = owners[0]["displayName"].Value <string>(); } editable = jsonFile["capabilities"]["canEdit"].Value <bool>(); return(file); }
private void StreamFile(HttpContext context) { try { var fileId = context.Request.Query[FilesLinkUtility.FileId]; var auth = context.Request.Query[FilesLinkUtility.AuthKey]; var userId = context.Request.Query[CommonLinkUtility.ParamName_UserUserID]; Logger.Debug("GoogleDriveApp: get file stream " + fileId); var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url()), exc); throw exc; } Token token = null; if (Guid.TryParse(userId, out var userIdGuid)) { token = TokenHelper.GetToken(AppAttr, userIdGuid); } if (token == null) { Logger.Error("BoxApp: token is null"); throw new SecurityException("Access token is null"); } var driveFile = GetDriveFile(fileId, token); var jsonFile = JObject.Parse(driveFile); var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media"; if (string.IsNullOrEmpty(downloadUrl)) { Logger.Error("GoogleDriveApp: downloadUrl is null"); throw new Exception("downloadUrl is null"); } Logger.Debug("GoogleDriveApp: get file stream downloadUrl - " + downloadUrl); var request = (HttpWebRequest)WebRequest.Create(downloadUrl); request.Method = "GET"; request.Headers.Add("Authorization", "Bearer " + token); using (var response = request.GetResponse()) using (var stream = new ResponseStream(response)) { stream.CopyTo(context.Response.Body); var contentLength = jsonFile.Value <string>("size"); Logger.Debug("GoogleDriveApp: get file stream contentLength - " + contentLength); context.Response.Headers.Add("Content-Length", contentLength); } } catch (Exception ex) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.WriteAsync(ex.Message).Wait(); Logger.Error("GoogleDriveApp: Error request " + context.Request.Url(), ex); } try { context.Response.Body.Flush(); //TODO //context.Response.SuppressContent = true; //context.ApplicationInstance.CompleteRequest(); } catch (HttpException ex) { Logger.Error("GoogleDriveApp StreamFile", ex); } }
public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream) { Logger.Debug("GoogleDriveApp: save file stream " + fileId + (stream == null ? " from - " + downloadUrl : " from stream")); fileId = ThirdPartySelector.GetFileId(fileId); var token = TokenHelper.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(driveFile); var currentType = GetCorrectExt(jsonFile); if (!fileType.Equals(currentType)) { try { if (stream != null) { downloadUrl = PathProvider.GetTempUrl(stream, fileType); downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl); } Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, false, out downloadUrl); stream = null; } catch (Exception e) { Logger.Error("GoogleDriveApp: Error convert", e); } } var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); request.Method = "PATCH"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = MimeMapping.GetMimeMapping(currentType); if (stream != null) { request.ContentLength = stream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = stream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } else { var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl); using var downloadStream = new ResponseStream(downloadRequest.GetResponse()); request.ContentLength = downloadStream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } try { using var response = request.GetResponse(); using var responseStream = response.GetResponseStream(); string result = null; if (responseStream != null) { using var readStream = new StreamReader(responseStream); result = readStream.ReadToEnd(); } Logger.Debug("GoogleDriveApp: save file stream response - " + result); } catch (WebException e) { Logger.Error("GoogleDriveApp: Error save file stream", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } }
public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream) { Logger.Debug("BoxApp: save file stream " + fileId + (stream == null ? " from - " + downloadUrl : " from stream")); fileId = ThirdPartySelector.GetFileId(fileId.ToString()); var token = TokenHelper.GetToken(AppAttr); var boxFile = GetBoxFile(fileId.ToString(), token); if (boxFile == null) { Logger.Error("BoxApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(boxFile); var title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name")); var currentType = FileUtility.GetFileExtension(title); if (!fileType.Equals(currentType)) { try { if (stream != null) { downloadUrl = PathProvider.GetTempUrl(stream, fileType); downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl); } Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, null, null, false, out downloadUrl); stream = null; } catch (Exception e) { Logger.Error("BoxApp: Error convert", e); } } var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId)); using (var tmpStream = new MemoryStream()) { var boundary = DateTime.UtcNow.Ticks.ToString("x"); var metadata = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title); var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata); var bytes = Encoding.UTF8.GetBytes(metadataPart); tmpStream.Write(bytes, 0, bytes.Length); if (stream != null) { stream.CopyTo(tmpStream); } else { var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl); using var downloadStream = new ResponseStream(downloadRequest.GetResponse()); downloadStream.CopyTo(tmpStream); } var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary); bytes = Encoding.UTF8.GetBytes(mediaPartEnd); tmpStream.Write(bytes, 0, bytes.Length); request.Method = "POST"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = "multipart/form-data; boundary=" + boundary; request.ContentLength = tmpStream.Length; Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length); const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; tmpStream.Seek(0, SeekOrigin.Begin); while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } try { using var response = request.GetResponse(); using var responseStream = response.GetResponseStream(); string result = null; if (responseStream != null) { using var readStream = new StreamReader(responseStream); result = readStream.ReadToEnd(); } Logger.Debug("BoxApp: save file response - " + result); } catch (WebException e) { Logger.Error("BoxApp: Error save file", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } }