Beispiel #1
0
        internal static void ConfirmConvertFile(HttpContext context)
        {
            var fileId = context.Request[FilesLinkUtility.FileId];

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

            var token = Token.GetToken();

            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(fileId) + "&" + FilesLinkUtility.Action + "=app", true);
        }
Beispiel #2
0
        internal 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();

            var culture   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).GetCulture();
            var storeTemp = Global.GetStoreTemplate();

            var path = FileConstant.NewDocPath + culture.TwoLetterISOLanguageName + "/";

            if (!storeTemp.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 = storeTemp.IronReadStream("", path, 10))
            {
                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(fileId) + "&" + FilesLinkUtility.Action + "=app" + "&new=true", true);
        }
Beispiel #3
0
        internal static File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("GoogleDriveApp: get file " + fileId);
            var token     = Token.GetToken();
            var driveFile = GetDriveFile(fileId, token);

            editable = false;

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

            var jsonFile = JObject.Parse(driveFile);

            var file = new File
            {
                ID               = jsonFile.Value <string>("id"),
                Title            = Global.ReplaceInvalidCharsAndTruncate(GetCorrectTitle(jsonFile)),
                CreateOn         = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("createdDate")),
                ModifiedOn       = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modifiedDate")),
                ContentLength    = Convert.ToInt64(jsonFile.Value <string>("fileSize")),
                ModifiedByString = jsonFile.Value <string>("lastModifyingUserName"),
                ProviderKey      = "Google"
            };

            var owners = jsonFile.Value <JArray>("ownerNames");

            if (owners != null)
            {
                file.CreateByString = owners.ToObject <List <string> >().FirstOrDefault();
            }

            editable = jsonFile.Value <bool>("editable");
            return(file);
        }
Beispiel #4
0
        internal static void SaveFile(string fileId, string downloadUrl)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl);

            var token = Token.GetToken();

            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 #5
0
        internal static void StreamFile(HttpContext context)
        {
            try
            {
                var fileId = context.Request[FilesLinkUtility.FileId];
                var auth   = context.Request[FilesLinkUtility.AuthKey];
                var userId = context.Request[CommonLinkUtility.ParamName_UserUserID];

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

                int validateTimespan;
                int.TryParse(WebConfigurationManager.AppSettings["files.stream-url-minute"], out validateTimespan);
                if (validateTimespan <= 0)
                {
                    validateTimespan = 5;
                }

                var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, TimeSpan.FromMinutes(validateTimespan));
                if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);

                    Global.Logger.Error(string.Format("GoogleDriveApp: {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc);

                    throw exc;
                }

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

                var jsonFile = JObject.Parse(driveFile);

                var downloadUrl   = jsonFile.Value <string>("downloadUrl");
                var contentLength = jsonFile.Value <string>("fileSize");

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                    throw new Exception("downloadUrl is null");
                }

                Global.Logger.Debug("GoogleDriveApp: get file stream  downloadUrl - " + downloadUrl);

                var request = WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token.AccessToken);

                using (var response = request.GetResponse())
                    using (var stream = new ResponseStream(response))
                    {
                        stream.StreamCopyTo(context.Response.OutputStream);

                        Global.Logger.Debug("GoogleDriveApp: get file stream  contentLength - " + contentLength);
                        context.Response.AddHeader("Content-Length", contentLength);
                    }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.Write(ex.Message);
                Global.Logger.Error("GoogleDriveApp: Error for: " + context.Request.Url, ex);
            }
            try
            {
                context.Response.Flush();
                context.Response.End();
            }
            catch (HttpException)
            {
            }
        }