Exemplo n.º 1
0
        public String GetRefreshedToken()
        {
            if (IsExpired)
            {
                var app = ThirdPartySelector.GetApp(App);
                try
                {
                    Global.Logger.Debug("Refresh token for app: " + App);

                    var refreshUrl = app.GetRefreshUrl();

                    var refreshed = OAuth20TokenHelper.RefreshToken(refreshUrl, this);

                    if (refreshed != null)
                    {
                        AccessToken  = refreshed.AccessToken;
                        RefreshToken = refreshed.RefreshToken;
                        ExpiresIn    = refreshed.ExpiresIn;
                        Timestamp    = DateTime.UtcNow;

                        SaveToken(this);
                    }
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("Refresh token for app: " + app, ex);
                }
            }
            return(AccessToken);
        }
Exemplo n.º 2
0
        public string GetFileStreamUrl(File file)
        {
            if (file == null)
            {
                return(string.Empty);
            }

            var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());

            Global.Logger.Debug("GoogleDriveApp: get file stream url " + fileId);

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));

            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;

            query += FilesLinkUtility.Action + "=stream&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
            query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
            query += ThirdPartySelector.AppAttr + "=" + AppAttr;

            return(uriBuilder.Uri + "?" + query);
        }
Exemplo n.º 3
0
        public File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("BoxApp: get file " + fileId);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId, token);

            editable = true;

            if (boxFile == null)
            {
                return(null);
            }

            var jsonFile = JObject.Parse(boxFile);

            var file = new File
            {
                ID            = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value <string>("id")),
                Title         = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name")),
                CreateOn      = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("created_at")),
                ModifiedOn    = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modified_at")),
                ContentLength = Convert.ToInt64(jsonFile.Value <string>("size")),
                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");
                    Global.Logger.Debug("BoxApp: locked by " + lockedUserId);

                    editable = CurrentUser(lockedUserId);
                }
            }

            return(file);
        }
Exemplo n.º 4
0
        private void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request.Query["code"]);

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

            var boxUserId = context.Request.Query["userId"];

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

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

                if (userInfo == null)
                {
                    Logger.Error("BoxApp: 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(boxUserId) && !CurrentUser(boxUserId))
                {
                    AddLinker(boxUserId);
                }
            }

            TokenHelper.SaveToken(token);

            var fileId = context.Request.Query["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
Exemplo n.º 5
0
        public string GetFileStreamUrl(File file)
        {
            if (file == null)
            {
                return(string.Empty);
            }

            var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());

            return(GetFileStreamUrl(fileId));
        }
Exemplo n.º 6
0
        private void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request["code"]);

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

            var boxUserId = context.Request["userId"];

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(boxUserId))
                {
                    Global.Logger.Debug("BoxApp: logout for " + boxUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

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

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

                CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, MessageAction.LoginSuccessViaSocialApp);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

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

            Token.SaveToken(token);

            var fileId = context.Request["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
Exemplo n.º 7
0
        private static void ConfirmConvertFile(HttpContext context)
        {
            var fileId = context.Request[FilesLinkUtility.FileId];

            Global.Logger.Debug("GoogleDriveApp: ConfirmConvertFile - " + fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.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);
        }
Exemplo n.º 8
0
        private static void CreateFile(HttpContext context)
        {
            var folderId = context.Request[FilesLinkUtility.FolderId];
            var fileName = context.Request[FilesLinkUtility.FileTitle];

            Global.Logger.Debug("GoogleDriveApp: CreateFile folderId - " + folderId + " fileName - " + fileName);

            var token = Token.GetToken(AppAttr);

            var culture       = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).GetCulture();
            var storeTemplate = Global.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)
            {
                Global.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);
        }
Exemplo n.º 9
0
        public File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("GoogleDriveApp: get file " + fileId);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token     = Token.GetToken(AppAttr);
            var driveFile = GetDriveFile(fileId, token);

            editable = false;

            if (driveFile == null)
            {
                return(null);
            }

            var jsonFile = JObject.Parse(driveFile);

            var file = new File
            {
                ID               = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value <string>("id")),
                Title            = Global.ReplaceInvalidCharsAndTruncate(GetCorrectTitle(jsonFile)),
                CreateOn         = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("createdTime")),
                ModifiedOn       = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modifiedTime")),
                ContentLength    = Convert.ToInt64(jsonFile.Value <string>("size")),
                ModifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value <string>(),
                ProviderKey      = "Google"
            };

            var owners = jsonFile["owners"];

            if (owners != null)
            {
                file.CreateByString = owners[0]["displayName"].Value <string>();
            }

            editable = jsonFile["capabilities"]["canEdit"].Value <bool>();
            return(file);
        }
Exemplo n.º 10
0
        public String GetRefreshedToken()
        {
            if (IsExpired)
            {
                var app = ThirdPartySelector.GetApp(App);
                try
                {
                    var refreshed = app.RefreshToken(RefreshToken);

                    if (refreshed != null)
                    {
                        AccessToken  = refreshed.AccessToken;
                        RefreshToken = refreshed.RefreshToken;
                        ExpiresIn    = refreshed.ExpiresIn;
                        Timestamp    = DateTime.UtcNow;
                    }
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("Refresh token for app: " + app, ex);
                }
            }
            return(AccessToken);
        }
Exemplo n.º 11
0
        private static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

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

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

            if (token == null)
            {
                Global.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 (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(googleUserId))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout for " + googleUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

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

                if (userInfo == null)
                {
                    Global.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(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

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

            Token.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)
                {
                    Global.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)
                {
                    Global.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))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.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;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
Exemplo n.º 12
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId +
                                (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.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
                {
                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl ?? Guid.NewGuid().ToString());
                    if (stream != null)
                    {
                        using (var tmpStream = new MemoryStream())
                        {
                            stream.CopyTo(tmpStream);

                            Global.Logger.Debug("GoogleDriveApp: GetExternalUri format: " + fileType);
                            downloadUrl = DocumentServiceConnector.GetExternalUri(tmpStream, fileType, key);
                        }
                    }

                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Global.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();
                            }
                        }

                        Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
Exemplo n.º 13
0
        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;
            }
        }
Exemplo n.º 14
0
        public void SaveFile(string fileId, string downloadUrl)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile = JObject.Parse(driveFile);
            var curExt   = GetCorrectExt(jsonFile);
            var newExt   = FileUtility.GetFileExtension(downloadUrl);

            if (curExt != newExt)
            {
                try
                {
                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + newExt + " to " + curExt + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, newExt, curExt, key, false, out downloadUrl);
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var downloadRequest = WebRequest.Create(downloadUrl);

            using (var downloadResponse = downloadRequest.GetResponse())
                using (var downloadStream = new ResponseStream(downloadResponse))
                {
                    var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));
                    request.Method = "PUT";
                    request.Headers.Add("Authorization", "Bearer " + token.AccessToken);
                    request.ContentType   = downloadResponse.ContentType;
                    request.ContentLength = downloadResponse.ContentLength;

                    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 stream = response.GetResponseStream())
                            {
                                var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;

                                Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                            }
                    }
                    catch (WebException e)
                    {
                        Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                        request.Abort();
                        var httpResponse = (HttpWebResponse)e.Response;
                        if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                        }
                        throw;
                    }
                }
        }
Exemplo n.º 15
0
        public void SaveFile(string fileId, string downloadUrl)
        {
            Global.Logger.Debug("BoxApp: save file stream " + fileId + " from - " + downloadUrl);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

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

            var boxFile = GetBoxFile(fileId, token);

            if (boxFile == null)
            {
                Global.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 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);

                var downloadRequest = WebRequest.Create(downloadUrl);
                using (var downloadResponse = downloadRequest.GetResponse())
                    using (var downloadStream = new ResponseStream(downloadResponse))
                    {
                        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.AccessToken);
                request.ContentType   = "multipart/form-data; boundary=" + boundary;
                request.ContentLength = tmpStream.Length;
                Global.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 stream = response.GetResponseStream())
                    {
                        var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;

                        Global.Logger.Debug("BoxApp: save file response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("BoxApp: Error save file", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }