示例#1
0
文件: BoxApp.cs 项目: ektai/AppServer
        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.StreamCopyTo(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);
            }
        }
示例#2
0
文件: BoxApp.cs 项目: ektai/AppServer
        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, 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;
            }
        }
示例#3
0
        private void RequestCode(HttpContext context)
        {
            var state = context.Request.Query["state"];

            Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Logger.Error("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request.Query["code"]);

            if (token == null)
            {
                Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            var googleUserId = stateJson.Value <string>("userId");

            if (AuthContext.IsAuthenticated)
            {
                if (!CurrentUser(googleUserId))
                {
                    Logger.Debug("GoogleDriveApp: logout for " + googleUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    AuthContext.Logout();
                }
            }

            if (!AuthContext.IsAuthenticated)
            {
                var userInfo = GetUserInfo(token, out var isNew);

                if (userInfo == null)
                {
                    Logger.Error("GoogleDriveApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(MessageAction.LoginSuccessViaSocialApp);

                if (isNew)
                {
                    var userHelpTourSettings = SettingsManager.LoadForCurrentUser <UserHelpTourSettings>();
                    userHelpTourSettings.IsNewUser = true;
                    SettingsManager.SaveForCurrentUser(userHelpTourSettings);

                    PersonalSettingsHelper.IsNewUser      = true;
                    PersonalSettingsHelper.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(googleUserId) && !CurrentUser(googleUserId))
                {
                    AddLinker(googleUserId);
                }
            }

            TokenHelper.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                //var folderId = stateJson.Value<string>("folderId");

                //context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(folderId), true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                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 ext      = GetCorrectExt(jsonFile);
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleLoginProvider.GoogleDriveExt.Contains(ext))
                {
                    Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettingsHelper.ConvertNotify)
                    {
                        //context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId), true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
                return;
            }
            Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
示例#4
0
        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.StreamCopyTo(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);
            }
        }
示例#5
0
        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;
            }
        }