using SvetoforVKBot.Models; using SvetoforVKBot.Models.Updates; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Threading; using System.Web.Mvc; using VkNet; using VkNet.Enums.SafetyEnums; using VkNet.Model.Keyboard; using VkNet.Model.RequestParams; using VkNet.Model; using System.Security.Cryptography; using Newtonsoft.Json; using VkNet.Model.Attachments; using System.Linq; using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.Sheets.v4; using Google.Apis.Sheets.v4.Data; using SvetoforVKBot.App_Start; using System.Configuration; using SvetoforVKBot.Data; namespace SvetoforVKBot.Controllers { class GoogleApi : IDisposable { readonly string[] Scopes = { SheetsService.Scope.Spreadsheets }; readonly string ApplicationName = "chatbot-vk-instagram"; //readonly string sheet = "Лист1"; readonly string credential_file = "client_secret.json"; SheetsService service; public GoogleApi() { try { GoogleCredential credential; string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"\" + credential_file; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) //new FileStream(credential_file, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream) .CreateScoped(Scopes); } // Create Google Sheets API service. service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); } catch (Exception ee) { Console.WriteLine("Ошибка при работе с google sheets: {0}", ee.Message); } } public void AppendEntry(string range, List> rangesValues, string sheet) { var valueRange = new ValueRange(); valueRange.Values = rangesValues; var appendRequest = service.Spreadsheets.Values.Append(valueRange, sheet, range); appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED; var appendReponse = appendRequest.Execute(); } public void Dispose() { ; } } public class ExportDataController : Controller { readonly string SheetAllUsersId = "1jr68NfIrlz2bVsN-HZg0Kv2sSJ82J5G-EbtXl-YMK44"; readonly string SheetConsultationsId = "1nWHvWufxDy6g2ZJtqd4K8MDM6Gh8OHWasRGXIyqbT2k"; private SvetoforVKBot.Data.SvetoforVKBotEntities db = new SvetoforVKBot.Data.SvetoforVKBotEntities(); protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } private const int SELFCHATID = 59111081; //GET: AllUsers public HttpStatusCodeResult AllUsers() { List ids = new List(); MessagesSendParams @params = new MessagesSendParams(); MessagesSendParams @params2 = new MessagesSendParams(); MessageEditParams editParams = new MessageEditParams(); HttpStatusCodeResult httpResult = new HttpStatusCodeResult(200); var client = new VkApi(); List phones; string agree; string reg; var phone = ""; try { client.AuthorizeAsync(new ApiAuthParams { AccessToken = ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Token }); #region Добавление в гугл таблицу using (GoogleApi myApi = new GoogleApi()) { List> rangeObj = new List>(); var users = db.Users.Where(usr => usr.export == 0).ToList(); foreach (var u in users) { phones = JsonConvert.DeserializeObject>(u.phone); if (phones.Count > 0) phone = phones[0]; else phone = "-"; if (u.reg == 1) reg = "Зарегистрирован"; else reg = "Не зарегистрирован"; if (u.agree == 1) agree = "Есть"; else agree = "Нет"; rangeObj.Add(new List() { u.chatId.ToString(), //u.firstName.ToString(), //u.lastName.ToString(), //u.fio.ToString(), reg, phone, u.birthday.ToShortDateString(), agree, }); var con = db.Users.Where(el => el.chatId == u.chatId).Single(); con.export = 1; db.SaveChanges(); Thread.Sleep(30); } //Добавление в таблицу данных объектов myApi.AppendEntry($"Лист1!A:H", rangeObj, SheetAllUsersId); } #endregion Добавление в гугл таблицу } catch (Exception ee) { @params.Message = "‼Ошибка в ExportDataController: " + ee.Message; @params.Attachments = null; @params.Keyboard = null; @params.UserId = 59111081; @params.RandomId = GetRandomId(); client.Messages.SendAsync(@params); } return httpResult; } public HttpStatusCodeResult PersonalConsultations() { List ids = new List(); MessagesSendParams @params = new MessagesSendParams(); MessagesSendParams @params2 = new MessagesSendParams(); MessageEditParams editParams = new MessageEditParams(); HttpStatusCodeResult httpResult = new HttpStatusCodeResult(200); var client = new VkApi(); List phones; string phone = ""; string birthdate = ""; string date = ""; try { client.AuthorizeAsync(new ApiAuthParams { AccessToken = ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Token }); #region Добавление в гугл таблицу using (GoogleApi myApi = new GoogleApi()) { List> rangeObj = new List>(); var consultations = db.PersonalConsultations.Join(db.Users, pc => pc.chatId, u => u.chatId, (pc, u) => new PersonalCons{ chatId = pc.chatId, //fio = u.fio, phone = u.phone, birthdate = u.birthday, question = u.question, date = pc.datetime, state = pc.state }) .Where(c => c.state == 1) .ToList(); foreach (var c in consultations) { phones = JsonConvert.DeserializeObject>(c.phone); if (phones.Count > 0) phone = phones[0]; else phone = "-"; birthdate = c.birthdate.ToShortDateString(); date = c.date.ToString("dd.MM.yyyy HH:mm"); rangeObj.Add(new List() { c.chatId, c.fio, phone, birthdate, c.question, date, }); var con = db.PersonalConsultations.Where(el => el.chatId == c.chatId).Single(); con.state = 2; db.SaveChanges(); Thread.Sleep(30); } //Добавление в таблицу данных объектов myApi.AppendEntry($"Лист1!A:H", rangeObj, SheetConsultationsId); } #endregion Добавление в гугл таблицу } catch (Exception ee) { @params.Message = "‼Ошибка в ExportDataController: " + ee.Message; @params.Attachments = null; @params.Keyboard = null; @params.UserId = 59111081; @params.RandomId = GetRandomId(); client.Messages.SendAsync(@params); } return httpResult; } private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); private int GetRandomId() { var intBytes = new byte[4]; Rng.GetBytes(intBytes); return BitConverter.ToInt32(intBytes, 0); } } }