public async Task <bool> SaveFolderIds(FolderIds folderIds, string accountName)
        {
            var jsonSerializedToken = JsonConvert.SerializeObject(folderIds);
            var request             = new HttpRequestMessage
            {
                Method     = HttpMethod.Put,
                RequestUri = new Uri($"http://infra.io.vtex.com/vbase/v2/{this._httpContextAccessor.HttpContext.Request.Headers[SheetsCatalogImportConstants.VTEX_ACCOUNT_HEADER_NAME]}/{this._environmentVariableProvider.Workspace}/buckets/{this._applicationName}/{SheetsCatalogImportConstants.BUCKET}/files/{accountName}"),
                Content    = new StringContent(jsonSerializedToken, Encoding.UTF8, SheetsCatalogImportConstants.APPLICATION_JSON)
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[SheetsCatalogImportConstants.HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(SheetsCatalogImportConstants.AUTHORIZATION_HEADER_NAME, authToken);
                request.Headers.Add(SheetsCatalogImportConstants.VTEX_ID_HEADER_NAME, authToken);
            }

            var client   = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);

            _context.Vtex.Logger.Info("SaveFolderIds", null, $"Account '{accountName}' [{response.StatusCode}] {jsonSerializedToken}");

            return(response.IsSuccessStatusCode);
        }
        public async Task <FolderIds> LoadFolderIds(string accountName)
        {
            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"http://infra.io.vtex.com/vbase/v2/{this._httpContextAccessor.HttpContext.Request.Headers[SheetsCatalogImportConstants.VTEX_ACCOUNT_HEADER_NAME]}/{this._environmentVariableProvider.Workspace}/buckets/{this._applicationName}/{SheetsCatalogImportConstants.BUCKET}/files/{accountName}")
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[SheetsCatalogImportConstants.HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(SheetsCatalogImportConstants.AUTHORIZATION_HEADER_NAME, authToken);
                request.Headers.Add(SheetsCatalogImportConstants.VTEX_ID_HEADER_NAME, authToken);
            }

            request.Headers.Add("Cache-Control", "no-cache");

            var client   = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);

            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            FolderIds folderIds = JsonConvert.DeserializeObject <FolderIds>(responseContent);

            return(folderIds);
        }
示例#3
0
        public async Task <string> ClearSheet()
        {
            Response.Headers.Add("Cache-Control", "no-cache");
            string    response       = string.Empty;
            string    imagesFolderId = null;
            string    accountName    = this._httpContextAccessor.HttpContext.Request.Headers[DriveImportConstants.VTEX_ACCOUNT_HEADER_NAME];
            FolderIds folderIds      = await _driveImportRepository.LoadFolderIds(accountName);

            if (folderIds != null)
            {
                imagesFolderId = folderIds.ImagesFolderId;
                ListFilesResponse spreadsheets = await _googleDriveService.ListSheetsInFolder(imagesFolderId);

                if (spreadsheets != null)
                {
                    SheetRange sheetRange = new SheetRange();
                    sheetRange.Ranges = new List <string>();
                    sheetRange.Ranges.Add($"A2:Z{DriveImportConstants.DEFAULT_SHEET_SIZE}");

                    foreach (GoogleFile sheet in spreadsheets.Files)
                    {
                        response = response + " - " + _googleDriveService.ClearSpreadsheet(sheet.Id, sheetRange).Result;
                    }
                }
                else
                {
                    response = "null sheet";
                }
            }
            else
            {
                response = "null folderIds";
            }

            return(response);
        }
示例#4
0
        /// <summary>
        /// Hard delete messages and subfolders under the specified folder.
        /// </summary>
        /// <param name="folderIndex">The id of folder in which subfolders and messages should be deleted</param>
        protected void HardDeleteMessagesAndSubfolders(FolderIds folderIndex)
        {
            #region Client connects with Server
            this.pcbOut      = ConstValues.ValidpcbOut;
            this.pcbAuxOut   = ConstValues.ValidpcbAuxOut;
            this.returnValue = this.oxcrpcAdapter.EcDoConnectEx(
                ref this.pcxh,
                TestSuiteBase.UlIcxrLinkForNoSessionLink,
                ref this.pulTimeStamp,
                null,
                this.userDN,
                ref this.pcbAuxOut,
                this.rgwClientVersion,
                out this.rgwBestVersion,
                out this.picxr);
            Site.Assert.AreEqual <uint>(0, this.returnValue, "EcDoConnectEx should succeed. This call is the precondition for EcDoRpcExt2. '0' is expected to be returned. The returned value is {0}.", this.returnValue);
            #endregion

            #region Logon to mailbox
            this.rgbIn     = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege);
            this.pcbOut    = ConstValues.ValidpcbOut;
            this.pcbAuxOut = ConstValues.ValidpcbAuxOut;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoCompression | PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable);

            Site.Assert.AreEqual <uint>(0, this.returnValue, "RopLogon should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue);
            RopLogonResponse logonResponse = (RopLogonResponse)this.response;
            uint             logonHandle   = this.responseSOHTable[TestSuiteBase.FIRST][logonResponse.OutputHandleIndex];
            #endregion

            #region OpenFolder
            this.rgbIn            = AdapterHelper.ComposeRgbIn(ROPCommandType.RopOpenFolder, logonHandle, logonResponse.FolderIds[(int)folderIndex]);
            this.pcbOut           = ConstValues.ValidpcbOut;
            this.pcbAuxOut        = ConstValues.ValidpcbAuxOut;
            this.responseSOHTable = new List <List <uint> >();
            uint payloadCount = 0;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.rgbOut,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable,
                out payloadCount,
                ref this.rgbAuxOut);

            Site.Assert.AreEqual <uint>(0, this.returnValue, "RopOpenFolder should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue);
            RopOpenFolderResponse openFolderResponse = (RopOpenFolderResponse)this.response;
            this.objHandle = this.responseSOHTable[TestSuiteBase.FIRST][openFolderResponse.OutputHandleIndex];
            #endregion

            #region HardDeleteFoldersAndMessages
            this.rgbIn            = AdapterHelper.ComposeRgbIn(ROPCommandType.RopHardDeleteMessagesAndSubfolders, this.objHandle, 0);
            this.pcbOut           = ConstValues.ValidpcbOut;
            this.pcbAuxOut        = ConstValues.ValidpcbAuxOut;
            this.responseSOHTable = new List <List <uint> >();
            payloadCount          = 0;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.rgbOut,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable,
                out payloadCount,
                ref this.rgbAuxOut);

            // The returned value 1125 means ecNoDelSubmitMsg, that is, deleting a message that has been submitted for sending is not permitted.
            bool retValue = (this.returnValue == 0) || (this.returnValue == 1125);
            Site.Assert.AreEqual <bool>(true, retValue, "The returned status is {0}. TRUE means that RopHardDeleteMessagesAndSubfolders succeed, and FALSE means that RopHardDeleteMessagesAndSubfolders failed.", retValue);
            #endregion

            #region Client disconnects with Server
            this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh);
            Site.Assert.AreEqual <uint>(0, this.returnValue, "EcDoDisconnect should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue);
            #endregion
        }
        /// <summary>
        /// Hard delete messages and subfolders under the specified folder.
        /// </summary>
        /// <param name="folderIndex">The id of folder in which subfolders and messages should be deleted</param>
        protected void HardDeleteMessagesAndSubfolders(FolderIds folderIndex)
        {
            #region Client connects with Server
            this.pcbOut = ConstValues.ValidpcbOut;
            this.pcbAuxOut = ConstValues.ValidpcbAuxOut;
            this.returnValue = this.oxcrpcAdapter.EcDoConnectEx(
                ref this.pcxh,
                TestSuiteBase.UlIcxrLinkForNoSessionLink,
                ref this.pulTimeStamp,
                null,
                this.userDN,
                ref this.pcbAuxOut,
                this.rgwClientVersion,
                out this.rgwBestVersion,
                out this.picxr);
            Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed. This call is the precondition for EcDoRpcExt2. '0' is expected to be returned. The returned value is {0}.", this.returnValue);
            #endregion

            #region Logon to mailbox
            this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege);
            this.pcbOut = ConstValues.ValidpcbOut;
            this.pcbAuxOut = ConstValues.ValidpcbAuxOut;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoCompression | PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable);

            Site.Assert.AreEqual<uint>(0, this.returnValue, "RopLogon should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); 
            RopLogonResponse logonResponse = (RopLogonResponse)this.response;
            uint logonHandle = this.responseSOHTable[TestSuiteBase.FIRST][logonResponse.OutputHandleIndex];
            #endregion

            #region OpenFolder
            this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopOpenFolder, logonHandle, logonResponse.FolderIds[(int)folderIndex]);
            this.pcbOut = ConstValues.ValidpcbOut;
            this.pcbAuxOut = ConstValues.ValidpcbAuxOut;
            this.responseSOHTable = new List<List<uint>>();
            uint payloadCount = 0;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.rgbOut,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable,
                out payloadCount,
                ref this.rgbAuxOut);

            Site.Assert.AreEqual<uint>(0, this.returnValue, "RopOpenFolder should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); 
            RopOpenFolderResponse openFolderResponse = (RopOpenFolderResponse)this.response;
            this.objHandle = this.responseSOHTable[TestSuiteBase.FIRST][openFolderResponse.OutputHandleIndex];
            #endregion

            #region HardDeleteFoldersAndMessages
            this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopHardDeleteMessagesAndSubfolders, this.objHandle, 0);
            this.pcbOut = ConstValues.ValidpcbOut;
            this.pcbAuxOut = ConstValues.ValidpcbAuxOut;
            this.responseSOHTable = new List<List<uint>>();
            payloadCount = 0;

            this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2(
                ref this.pcxh,
                PulFlags.NoXorMagic,
                this.rgbIn,
                ref this.rgbOut,
                ref this.pcbOut,
                null,
                ref this.pcbAuxOut,
                out this.response,
                ref this.responseSOHTable,
                out payloadCount,
                ref this.rgbAuxOut);

            // The returned value 1125 means ecNoDelSubmitMsg, that is, deleting a message that has been submitted for sending is not permitted.
            bool retValue = (this.returnValue == 0) || (this.returnValue == 1125);
            Site.Assert.AreEqual<bool>(true, retValue, "The returned status is {0}. TRUE means that RopHardDeleteMessagesAndSubfolders succeed, and FALSE means that RopHardDeleteMessagesAndSubfolders failed.", retValue);
            #endregion

            #region Client disconnects with Server
            this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh);
            Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoDisconnect should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); 
            #endregion
        }
示例#6
0
        public Query(IGoogleDriveService googleDriveService, IDriveImportRepository driveImportRepository)
        {
            Name = "Query";

            FieldAsync <BooleanGraphType>(
                "haveToken",
                resolve: async context =>
            {
                Token token = await googleDriveService.GetGoogleToken();
                return(token != null && !string.IsNullOrEmpty(token.RefreshToken));
            }
                );

            /// query Reviews($searchTerm: String, $from: Int, $to: Int, $orderBy: String, $status: Boolean)
            FieldAsync <StringGraphType>(
                "getOwnerEmail",
                arguments: new QueryArguments(
                    new QueryArgument <StringGraphType> {
                Name = "accountName", Description = "Account Name"
            }
                    ),
                resolve: async context =>
            {
                string email       = string.Empty;
                string accountName = context.GetArgument <string>("accountName");
                Token token        = await googleDriveService.GetGoogleToken();
                if (token != null)
                {
                    string newFolderId  = string.Empty;
                    FolderIds folderIds = await driveImportRepository.LoadFolderIds(accountName);
                    if (folderIds != null)
                    {
                        newFolderId = folderIds.NewFolderId;
                    }
                    else
                    {
                        newFolderId = await googleDriveService.FindNewFolderId(accountName);
                    }

                    ListFilesResponse listFilesResponse = await googleDriveService.ListFiles();
                    if (listFilesResponse != null)
                    {
                        var owners = listFilesResponse.Files.Where(f => f.Id.Equals(newFolderId)).Select(o => o.Owners.Distinct()).FirstOrDefault();
                        if (owners != null)
                        {
                            email = owners.Select(o => o.EmailAddress).FirstOrDefault();
                        }
                        else
                        {
                            newFolderId = await googleDriveService.FindNewFolderId(accountName);
                            owners      = listFilesResponse.Files.Where(f => f.Id.Equals(newFolderId)).Select(o => o.Owners.Distinct()).FirstOrDefault();
                            if (owners != null)
                            {
                                email = owners.Select(o => o.EmailAddress).FirstOrDefault();
                            }
                        }
                    }
                }

                return(email);
            }
                );

            FieldAsync <StringGraphType>(
                "sheetLink",
                resolve: async context =>
            {
                return(await googleDriveService.GetSheetLink());
            }
                );
        }
示例#7
0
        public async Task <IActionResult> ListImages()
        {
            Response.Headers.Add("Cache-Control", "no-cache");
            string newFolderId;
            string doneFolderId;
            string errorFolderId;
            string importFolderId;
            string accountFolderId;
            string imagesFolderId;
            string accountName = this._httpContextAccessor.HttpContext.Request.Headers[DriveImportConstants.VTEX_ACCOUNT_HEADER_NAME];

            FolderIds folderIds = await _driveImportRepository.LoadFolderIds(accountName);

            if (folderIds != null)
            {
                accountFolderId = folderIds.AccountFolderId;
                imagesFolderId  = folderIds.ImagesFolderId;
                newFolderId     = folderIds.NewFolderId;
                doneFolderId    = folderIds.DoneFolderId;
                errorFolderId   = folderIds.ErrorFolderId;
            }
            else
            {
                Dictionary <string, string> folders = await _googleDriveService.ListFolders();   // Id, Name

                if (!folders.ContainsValue(DriveImportConstants.FolderNames.IMPORT))
                {
                    importFolderId = await _googleDriveService.CreateFolder(DriveImportConstants.FolderNames.IMPORT);
                }
                else
                {
                    importFolderId = folders.FirstOrDefault(x => x.Value == DriveImportConstants.FolderNames.IMPORT).Key;
                }

                if (string.IsNullOrEmpty(importFolderId))
                {
                    _context.Vtex.Logger.Info("DriveImport", null, $"Could not find '{DriveImportConstants.FolderNames.IMPORT}' folder");
                    return(Json($"Could not find {DriveImportConstants.FolderNames.IMPORT} folder"));
                }

                folders = await _googleDriveService.ListFolders(importFolderId);

                if (!folders.ContainsValue(accountName))
                {
                    accountFolderId = await _googleDriveService.CreateFolder(accountName, importFolderId);
                }
                else
                {
                    accountFolderId = folders.FirstOrDefault(x => x.Value == accountName).Key;
                }

                if (string.IsNullOrEmpty(accountFolderId))
                {
                    _context.Vtex.Logger.Info("DriveImport", null, $"Could not find {accountFolderId} folder");
                    return(Json($"Could not find {accountFolderId} folder"));
                }

                folders = await _googleDriveService.ListFolders(accountFolderId);

                if (!folders.ContainsValue(DriveImportConstants.FolderNames.IMAGES))
                {
                    imagesFolderId = await _googleDriveService.CreateFolder(DriveImportConstants.FolderNames.IMAGES, accountFolderId);
                }
                else
                {
                    imagesFolderId = folders.FirstOrDefault(x => x.Value == DriveImportConstants.FolderNames.IMAGES).Key;
                }

                if (string.IsNullOrEmpty(imagesFolderId))
                {
                    _context.Vtex.Logger.Info("DriveImport", null, $"Could not find {imagesFolderId} folder");
                    return(Json($"Could not find {imagesFolderId} folder"));
                }

                folders = await _googleDriveService.ListFolders(imagesFolderId);

                if (!folders.ContainsValue(DriveImportConstants.FolderNames.NEW))
                {
                    newFolderId = await _googleDriveService.CreateFolder(DriveImportConstants.FolderNames.NEW, imagesFolderId);

                    bool setPermission = await _googleDriveService.SetPermission(newFolderId);

                    if (!setPermission)
                    {
                        _context.Vtex.Logger.Error("DriveImport", "SetPermission", $"Could not set permissions on '{DriveImportConstants.FolderNames.NEW}' folder {newFolderId}");
                    }
                }
                else
                {
                    newFolderId = folders.FirstOrDefault(x => x.Value == DriveImportConstants.FolderNames.NEW).Key;
                }

                if (!folders.ContainsValue(DriveImportConstants.FolderNames.DONE))
                {
                    doneFolderId = await _googleDriveService.CreateFolder(DriveImportConstants.FolderNames.DONE, imagesFolderId);
                }
                else
                {
                    doneFolderId = folders.FirstOrDefault(x => x.Value == DriveImportConstants.FolderNames.DONE).Key;
                }

                if (!folders.ContainsValue(DriveImportConstants.FolderNames.ERROR))
                {
                    errorFolderId = await _googleDriveService.CreateFolder(DriveImportConstants.FolderNames.ERROR, imagesFolderId);
                }
                else
                {
                    errorFolderId = folders.FirstOrDefault(x => x.Value == DriveImportConstants.FolderNames.ERROR).Key;
                }
            }

            if (folderIds == null)
            {
                folderIds = new FolderIds
                {
                    AccountFolderId = accountFolderId,
                    DoneFolderId    = doneFolderId,
                    ErrorFolderId   = errorFolderId,
                    ImagesFolderId  = imagesFolderId,
                    ImportFolderId  = imagesFolderId,
                    NewFolderId     = newFolderId
                };

                _driveImportRepository.SaveFolderIds(folderIds, accountName);
            }

            Dictionary <string, string> images     = new Dictionary <string, string>();
            ListFilesResponse           imageFiles = new ListFilesResponse();

            imageFiles.Files = new List <GoogleFile>();
            string nextPageToken = string.Empty;

            do
            {
                ListFilesResponse listFilesResponse = await _googleDriveService.ListImagesInFolder(newFolderId, nextPageToken);

                imageFiles.Files.AddRange(listFilesResponse.Files);
                nextPageToken = listFilesResponse.NextPageToken;
            } while (!string.IsNullOrEmpty(nextPageToken));

            return(Json(imageFiles));
        }
示例#8
0
        public async Task <string> AddThumbnails()
        {
            Response.Headers.Add("Cache-Control", "no-cache");
            string result         = string.Empty;
            string newFolderId    = null;
            string imagesFolderId = null;
            string accountName    = this._httpContextAccessor.HttpContext.Request.Headers[DriveImportConstants.VTEX_ACCOUNT_HEADER_NAME];

            FolderIds folderIds = await _driveImportRepository.LoadFolderIds(accountName);

            if (folderIds != null)
            {
                newFolderId    = folderIds.NewFolderId;
                imagesFolderId = folderIds.ImagesFolderId;
                ListFilesResponse imageFiles = new ListFilesResponse();
                imageFiles.Files = new List <GoogleFile>();
                string nextPageToken = string.Empty;
                do
                {
                    ListFilesResponse listFilesResponse = await _googleDriveService.ListImagesInFolder(newFolderId, nextPageToken);

                    imageFiles.Files.AddRange(listFilesResponse.Files);
                    nextPageToken = listFilesResponse.NextPageToken;
                } while (!string.IsNullOrEmpty(nextPageToken));

                ListFilesResponse spreadsheets = await _googleDriveService.ListSheetsInFolder(imagesFolderId);

                if (imageFiles != null && spreadsheets != null)
                {
                    var sheetIds = spreadsheets.Files.Select(s => s.Id);
                    if (sheetIds != null)
                    {
                        foreach (var sheetId in sheetIds)
                        {
                            Dictionary <string, int> headerIndexDictionary = new Dictionary <string, int>();
                            string sheetContent = await _googleDriveService.GetSheet(sheetId, string.Empty);

                            GoogleSheet googleSheet    = JsonConvert.DeserializeObject <GoogleSheet>(sheetContent);
                            string      valueRange     = googleSheet.ValueRanges[0].Range;
                            string      sheetName      = valueRange.Split("!")[0];
                            string[]    sheetHeader    = googleSheet.ValueRanges[0].Values[0];
                            int         headerIndex    = 0;
                            int         rowCount       = googleSheet.ValueRanges[0].Values.Count();
                            int         writeBlockSize = rowCount;
                            foreach (string header in sheetHeader)
                            {
                                headerIndexDictionary.Add(header.ToLower(), headerIndex);
                                headerIndex++;
                            }

                            string[][] arrValuesToWrite = new string[writeBlockSize][];

                            for (int index = 1; index < rowCount; index++)
                            {
                                string imageFileName = string.Empty;

                                string[] dataValues = googleSheet.ValueRanges[0].Values[index];
                                if (headerIndexDictionary.ContainsKey("image") && headerIndexDictionary["image"] < dataValues.Count())
                                {
                                    imageFileName = dataValues[headerIndexDictionary["image"]];
                                }

                                GoogleFile file = imageFiles.Files.FirstOrDefault(f => f.Name.Equals(imageFileName));
                                if (file != null)
                                {
                                    string[] row = new string[headerIndexDictionary.Count];
                                    row[headerIndexDictionary["thumbnail"]] = $"=IMAGE(\"{ file.ThumbnailLink}\")";
                                    arrValuesToWrite[index - 1]             = row;
                                }
                            }

                            string lastColumn = ((char)(headerIndexDictionary.Count + 65)).ToString();

                            ValueRange valueRangeToWrite = new ValueRange
                            {
                                Range  = $"{sheetName}!A2:{lastColumn}{rowCount + 1}",
                                Values = arrValuesToWrite
                            };

                            await _googleDriveService.WriteSpreadsheetValues(sheetId, valueRangeToWrite);
                        }
                    }
                }
            }

            return(result);
        }
示例#9
0
        public async Task <IActionResult> GetOwnerEmail()
        {
            string email       = null;
            string accountName = this._httpContextAccessor.HttpContext.Request.Headers[DriveImportConstants.VTEX_ACCOUNT_HEADER_NAME];

            try
            {
                Token token = await _googleDriveService.GetGoogleToken();

                if (token != null)
                {
                    string    newFolderId    = string.Empty;
                    string    imagesFolderId = string.Empty;
                    FolderIds folderIds      = await _driveImportRepository.LoadFolderIds(accountName);

                    if (folderIds != null)
                    {
                        newFolderId    = folderIds.NewFolderId;
                        imagesFolderId = folderIds.ImagesFolderId;
                        _context.Vtex.Logger.Info("GetOwnerEmail", null, $"New Folder Id: {newFolderId}");
                    }
                    else
                    {
                        _context.Vtex.Logger.Info("GetOwnerEmail", null, "Could not load folder structure from storage.");
                        newFolderId = await _googleDriveService.FindNewFolderId(accountName);
                    }

                    ListFilesResponse listFilesResponse = await _googleDriveService.ListFiles();

                    if (listFilesResponse != null)
                    {
                        var owners = listFilesResponse.Files.Where(f => f.Id.Equals(newFolderId)).Select(o => o.Owners.Distinct()).FirstOrDefault();
                        if (owners != null)
                        {
                            email = owners.Select(o => o.EmailAddress).FirstOrDefault();
                        }
                        else
                        {
                            _context.Vtex.Logger.Info("GetOwnerEmail", null, "Could not find owners. (1)");
                            newFolderId = await _googleDriveService.FindNewFolderId(accountName);

                            owners = listFilesResponse.Files.Where(f => f.Id.Equals(newFolderId)).Select(o => o.Owners.Distinct()).FirstOrDefault();
                            if (owners != null)
                            {
                                email = owners.Select(o => o.EmailAddress).FirstOrDefault();
                            }
                            else
                            {
                                _context.Vtex.Logger.Info("GetOwnerEmail", null, "Could not find owners. (2)");
                                owners = listFilesResponse.Files.Where(f => f.Id.Equals(imagesFolderId)).Select(o => o.Owners.Distinct()).FirstOrDefault();
                            }
                            if (owners != null)
                            {
                                email = owners.Select(o => o.EmailAddress).FirstOrDefault();
                            }
                            else
                            {
                                _context.Vtex.Logger.Info("GetOwnerEmail", null, "Could not find owners. (3)");
                            }
                        }
                    }
                }
                else
                {
                    _context.Vtex.Logger.Info("GetOwnerEmail", null, "Could not load Token.");
                }
            }
            catch (Exception ex)
            {
                _context.Vtex.Logger.Error("GetOwnerEmail", null, $"Error getting Drive owner", ex);
            }

            _context.Vtex.Logger.Info("GetOwnerEmail", null, $"Email = {email}");

            Response.Headers.Add("Cache-Control", "no-cache");
            return(Json(email));
        }