Beispiel #1
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);
        }
        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);
        }
Beispiel #3
0
        public string GetFileStreamUrl(File file)
        {
            if (file == null)
            {
                return(string.Empty);
            }

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

            return(GetFileStreamUrl(fileId));
        }
Beispiel #4
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);
        }
Beispiel #5
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;
            }
        }
Beispiel #6
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;
            }
        }
Beispiel #7
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;
                    }
                }
        }
Beispiel #8
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;
            }
        }