private static async Task MessagesDeny(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { var innerMessage = VkNet.Model.Message.FromJson(new VkNet.Utils.VkResponse(message.Object)); var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, innerMessage.UserId); if (subscriber == null) { return; } if (!subscriber.IsChatAllowed.HasValue || subscriber.IsChatAllowed.Value) { subscriber.IsChatAllowed = false; } await context.History_GroupActions.AddAsync(new History_GroupActions() { ActionType = (int)Models.Database.Common.GroupActionTypes.BlockMessaging, IdGroup = message.IdGroup, IdSubscriber = subscriber.Id, Dt = DateTime.UtcNow }); await context.SaveChangesAsync(); }
private static async Task UserUnblock(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { var innerMessage = message.Object.ToObject <UserUnblock>(); var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, innerMessage.IdUser); if (subscriber == null) { return; } subscriber.IsBlocked = false; await context.History_GroupActions.AddAsync(new History_GroupActions() { ActionType = (int)Models.Database.Common.GroupActionTypes.Unblocked, IdGroup = message.IdGroup, IdSubscriber = subscriber.Id, Dt = DateTime.UtcNow }); await context.SaveChangesAsync(); }
private static async Task GroupJoin(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { var innerMessage = message.Object.ToObject <GroupJoin>(); if (!innerMessage.IdUser.HasValue || innerMessage.IdUser.Value <= 0) { return; } var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, innerMessage.IdUser); if (subscriber == null) { return; } subscriber.IsUnsubscribed = false; subscriber.DtUnsubscribe = null; subscriber.IsSubscribedToGroup = true; await context.History_GroupActions.AddAsync(new History_GroupActions() { ActionType = (int)Models.Database.Common.GroupActionTypes.JoinGroup, IdGroup = message.IdGroup, IdSubscriber = subscriber.Id, Dt = DateTime.UtcNow }); await context.SaveChangesAsync(); }
private void createUniformBuffers(VkContext context) { var bufferSize = Marshal.SizeOf <UniformBufferObject>(); var usageFlags = Vk.BufferUsageFlags.UniformBuffer; var memProps = Vk.MemoryPropertyFlags.HostVisible | Vk.MemoryPropertyFlags.HostCoherent; var buffers = new BufferWithMemory[this.wrapper.ImageCapacity]; for (int i = 0; i < this.wrapper.ImageCapacity; i++) { try { buffers[i] = VkHelper.CreateBuffer(context, bufferSize, usageFlags, memProps, this.wrapper.SharingMode); } catch (Vk.ResultException result) { throw new VkException($"An error occurred while creating uniform buffer {i}.", result); } } this.wrapper.UniformBuffers = new Vk.Buffer[this.wrapper.ImageCapacity]; this.wrapper.UniformBuffersMemory = new Vk.DeviceMemory[this.wrapper.ImageCapacity]; for (int i = 0; i < this.wrapper.ImageCapacity; i++) { this.wrapper.UniformBuffers[i] = buffers[i].Buffer; this.wrapper.UniformBuffersMemory[i] = buffers[i].Memory; } }
public async Task <IActionResult> CallBack([FromBody] Updates updates) { switch (updates.Type) { case "confirmation": return(Ok(Cfg["ConfirmCode"])); case "message_new": var message = MessageNew.FromJson(new VkResponse(updates.Object)).Message; if (message.Text == "/start") { await VkHelper.SendMsg(message.PeerId, "Сова инициализирована.", VkHelper.DefaultKeyboard); } if (string.IsNullOrEmpty(message.Payload)) { return(Ok("ok")); } var payload = (string)JObject.Parse(message.Payload)["button"] ?? string.Empty; string week; switch (payload) { case "lessons_today": week = await Parser.ParseWeek(0); await VkHelper.SendMsg(message.PeerId, week.ExtractDay((byte)DateTime.Now.Day)); break; case "lessons_current": week = await Parser.ParseWeek(0); await VkHelper.SendMsg(message.PeerId, week); break; case "lessons_next": week = await Parser.ParseWeek(1); await VkHelper.SendMsg(message.PeerId, week); break; case "lessons_all": week = await Parser.ParseAll(); await VkHelper.SendMsg(message.PeerId, week); break; } break; } return(Ok("ok")); }
public LoginVk() { try { VkHelper.CheckEthernet(); InitializeComponent(); wb.ScriptErrorsSuppressed = true; wb.Navigate( "https://oauth.vk.com/authorize?client_id=3987742&scope=2080255&redirect_uri=https://oauth.vk.com/blank.html&display=page&response_type=token"); } catch (NetworkInformationException) { System.Windows.Forms.MessageBox.Show(@"Ошибка интернет соединения."); } }
private void WebBrowser_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e) { try { VkHelper.CheckEthernet(); if (!e.Url.ToString().StartsWith("https://oauth.vk.com/blank.html")) { return; } AccessToken = e.Url.Fragment.Split('&')[0].Replace("#access_token=", ""); Close(); } catch (NetworkInformationException) { System.Windows.Forms.MessageBox.Show(@"Ошибка интернет соединения."); } }
private static async Task WallPostNew(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { if (await IsPassedCallbackMessage(context, message)) { return; } var newPost = VkNet.Model.Post.FromJson(new VkNet.Utils.VkResponse(message.Object)); if (!newPost.Id.HasValue || await context.WallPosts.AnyAsync(x => x.IdGroup == message.IdGroup && x.IdVk == newPost.Id)) { return; } var newWallPost = new WallPosts() { DtAdd = newPost.Date ?? DateTime.UtcNow, IdGroup = message.IdGroup, IdVk = newPost.Id.Value, Text = newPost.Text }; await context.WallPosts.AddAsync(newWallPost); await context.SaveChangesAsync(); var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, newPost.FromId); if (subscriber == null) { return; } await context.History_WallPosts.AddAsync(new History_WallPosts() { Dt = DateTime.UtcNow, IdPost = newWallPost.Id, IdSubscriber = subscriber.Id, IsRepost = false }); await context.SaveChangesAsync(); }
private void createDepthResources(VkContext context) { var depthFormat = VkHelper.FindDepthFormat(context); var depthImage = VkHelper.CreateImage(context, this.wrapper.Extent.Width, this.wrapper.Extent.Height, depthFormat, Vk.ImageTiling.Optimal, Vk.ImageUsageFlags.DepthStencilAttachment, Vk.MemoryPropertyFlags.DeviceLocal); var depthImageView = VkHelper.CreateImageView(context, depthImage.Image, depthFormat, Vk.ImageAspectFlags.Depth); context.TransitionImageLayout(depthImage.Image, depthFormat, Vk.ImageLayout.Undefined, Vk.ImageLayout.DepthStencilAttachmentOptimal); this.wrapper.DepthImage = depthImage.Image; this.wrapper.DepthImageMemory = depthImage.Memory; this.wrapper.DepthImageView = depthImageView; }
public void Play(ListBox sender) { try { SetTagNull(OldNumber); if (!((Audio)sender.Items[CurrentPlayIndex]).IsPlayed) //todo проверять на индекс, возможно что то не так { if (FlagPrev) { for (var i = CurrentPlayIndex + 1; i < sender.Items.Count; i++) { if (!((Audio)sender.Items[i]).IsPlayed) { continue; } CurrentPlayIndex = i; break; } } else { for (var i = CurrentPlayIndex - 1; i >= 0; i--) { if (!((Audio)sender.Items[i]).IsPlayed) { continue; } CurrentPlayIndex = i; break; } } } VkHelper.CheckEthernet(); Bass.BASS_StreamFree(Stream); Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero); Stream = Bass.BASS_StreamCreateURL(((Audio)sender.Items[CurrentPlayIndex]).Path, 0, BASSFlag.BASS_DEFAULT, null, IntPtr.Zero); if (!Bass.BASS_ChannelPlay(Stream, false)) { return; } SetTagPlay(CurrentPlayIndex); OldNumber = CurrentPlayIndex; FlagPlay = true; Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, ((float)SliderVolum.Value) / 100); SliderTrack.Maximum = Bass.BASS_ChannelBytes2Seconds(Stream, Bass.BASS_ChannelGetLength(Stream)); BeginText.Text = ((Audio)sender.Items[CurrentPlayIndex]).Title; var font = new Font("Segoe UI Ligh", 12); var ta = new ThicknessAnimation { From = new Thickness(240, 0, 0, 0), To = new Thickness(Convert.ToDouble(-(TextRenderer.MeasureText(BeginText.Text, font)).Width), 0, 0, 0), Duration = TimeSpan.FromMilliseconds(10000), RepeatBehavior = RepeatBehavior.Forever }; BeginText.BeginAnimation(MarginProperty, ta); } catch (NetworkInformationException) { System.Windows.Forms.MessageBox.Show(@"Ошибка интернет соединения."); } }
private static async Task MessageNew(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { if (await IsPassedCallbackMessage(context, message)) { return; } var innerMessage = VkNet.Model.Message.FromJson(new VkNet.Utils.VkResponse(message.Object)); var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, innerMessage.UserId); if (subscriber == null) { return; } await context.History_Messages.AddAsync(new History_Messages() { Dt = DateTime.UtcNow, IsOutgoingMessage = false, IdSubscriber = subscriber.Id, Text = innerMessage.Body }); bool isCancelMessaging = innerMessage.Body?.ToLower() == "стоп"; if (!isCancelMessaging && (!subscriber.IsChatAllowed.HasValue || !subscriber.IsChatAllowed.Value)) { await context.History_GroupActions.AddAsync(new History_GroupActions() { ActionType = (int)Models.Database.Common.GroupActionTypes.AcceptMessaging, IdGroup = message.IdGroup, IdSubscriber = subscriber.Id, Dt = DateTime.UtcNow }); subscriber.IsChatAllowed = true; } await context.SaveChangesAsync(); var vkApi = await vkPoolService.GetGroupVkApi(message.IdGroup); if (isCancelMessaging) { await context.History_GroupActions.AddAsync(new History_GroupActions() { ActionType = (int)Models.Database.Common.GroupActionTypes.CancelMessaging, IdGroup = message.IdGroup, IdSubscriber = subscriber.Id, Dt = DateTime.UtcNow }); if (!subscriber.IsChatAllowed.HasValue || subscriber.IsChatAllowed.Value) { subscriber.IsChatAllowed = false; if (vkApi != null) { await context.History_Messages.AddAsync(new History_Messages() { Dt = DateTime.UtcNow, IsOutgoingMessage = true, IdSubscriber = subscriber.Id, Text = "Вы успешно отписаны от сообщений группы" }); await vkApi.Messages.SendAsync(new VkNet.Model.RequestParams.MessagesSendParams() { Message = "Вы успешно отписаны от сообщений группы", UserId = innerMessage.UserId }); } } await context.SaveChangesAsync(); return; } if (vkApi == null) { return; } var replyToMessageResult = await CallbackHelper.ReplyToMessage(context, message.IdGroup, subscriber.Id, innerMessage); if (replyToMessageResult == null) { return; } if (replyToMessageResult.Item1.HasValue) { var _configuration = serviceProvider.GetService <IConfiguration>(); var messageHelper = new MessageHelper(_configuration, context); await messageHelper.SendMessages(vkApi, message.IdGroup, replyToMessageResult.Item1.Value, innerMessage.UserId.Value); await context.History_Messages.AddAsync(new History_Messages() { Dt = DateTime.UtcNow, IsOutgoingMessage = true, IdSubscriber = subscriber.Id, IdMessage = replyToMessageResult.Item1 }); await context.SaveChangesAsync(); } else if (replyToMessageResult.Item2) { await vkApi.Messages.MarkAsReadAsync(innerMessage.UserId.ToString(), groupId : message.IdGroup); } }
private static async Task WallRepost(IServiceProvider serviceProvider, DatabaseContext context, CallbackMessage message) { if (await IsPassedCallbackMessage(context, message)) { return; } var repost = VkNet.Model.Wall.FromJson(new VkNet.Utils.VkResponse(message.Object)); if (!repost.FromId.HasValue || repost.FromId.Value <= 0) { return; } var repostedPost = repost.CopyHistory.FirstOrDefault(); var post = await context.WallPosts.FirstOrDefaultAsync(x => x.IdGroup == message.IdGroup && x.IdVk == repostedPost.Id); if (post == null) { post = new WallPosts() { DtAdd = repostedPost.Date ?? DateTime.UtcNow, IdGroup = message.IdGroup, IdVk = repostedPost.Id.Value, }; await context.WallPosts.AddAsync(post); await context.SaveChangesAsync(); } var vkPoolService = serviceProvider.GetService <VkPoolService>(); var subscriber = await VkHelper.CreateSubscriber(context, vkPoolService, message.IdGroup, repost.FromId); if (subscriber == null) { return; } bool hasSubscriberRepost = await context.SubscriberReposts .AnyAsync(x => x.WallPost.IdVk == repostedPost.Id && x.Subscriber.IdVkUser == subscriber.IdVkUser && x.DtRepost == repost.Date); if (!hasSubscriberRepost) { await context.SubscriberReposts.AddAsync(new SubscriberReposts() { DtRepost = repost.Date ?? DateTime.UtcNow, IdPost = post.Id, IdSubscriber = subscriber.Id, Text = repost.Text, }); } await context.History_WallPosts.AddAsync(new History_WallPosts() { Dt = DateTime.UtcNow, IdPost = post.Id, IdSubscriber = subscriber.Id, IsRepost = true }); await context.SaveChangesAsync(); }
private void createRenderPass(VkContext context) { var colourAttachment = new Vk.AttachmentDescription(); colourAttachment.Format = this.wrapper.Format; colourAttachment.Samples = Vk.SampleCountFlags.Count1; colourAttachment.LoadOp = Vk.AttachmentLoadOp.Clear; colourAttachment.StoreOp = Vk.AttachmentStoreOp.Store; colourAttachment.StencilLoadOp = Vk.AttachmentLoadOp.DontCare; colourAttachment.StencilStoreOp = Vk.AttachmentStoreOp.DontCare; colourAttachment.InitialLayout = Vk.ImageLayout.Undefined; colourAttachment.FinalLayout = Vk.ImageLayout.PresentSrcKhr; var colourAttachmentRef = new Vk.AttachmentReference(); colourAttachmentRef.Attachment = 0; colourAttachmentRef.Layout = Vk.ImageLayout.ColorAttachmentOptimal; var depthAttachment = new Vk.AttachmentDescription(); depthAttachment.Format = VkHelper.FindDepthFormat(context); depthAttachment.Samples = Vk.SampleCountFlags.Count1; depthAttachment.LoadOp = Vk.AttachmentLoadOp.Clear; depthAttachment.StoreOp = Vk.AttachmentStoreOp.DontCare; depthAttachment.StencilLoadOp = Vk.AttachmentLoadOp.DontCare; depthAttachment.StencilStoreOp = Vk.AttachmentStoreOp.DontCare; depthAttachment.InitialLayout = Vk.ImageLayout.Undefined; depthAttachment.FinalLayout = Vk.ImageLayout.DepthStencilAttachmentOptimal; var depthAttachmentRef = new Vk.AttachmentReference(); depthAttachmentRef.Attachment = 1; depthAttachmentRef.Layout = Vk.ImageLayout.DepthStencilAttachmentOptimal; var subpass = new Vk.SubpassDescription(); subpass.PipelineBindPoint = Vk.PipelineBindPoint.Graphics; subpass.ColorAttachmentCount = 1; subpass.ColorAttachments = new Vk.AttachmentReference[] { colourAttachmentRef }; subpass.DepthStencilAttachment = depthAttachmentRef; var subpassDep = new Vk.SubpassDependency(); subpassDep.SrcSubpass = VkConstants.VK_SUBPASS_EXTERNAL; subpassDep.DstSubpass = 0; subpassDep.SrcStageMask = Vk.PipelineStageFlags.ColorAttachmentOutput; subpassDep.DstStageMask = Vk.PipelineStageFlags.ColorAttachmentOutput; subpassDep.SrcAccessMask = 0; subpassDep.DstAccessMask = Vk.AccessFlags.ColorAttachmentRead | Vk.AccessFlags.ColorAttachmentWrite; var renderPassInfo = new Vk.RenderPassCreateInfo(); renderPassInfo.AttachmentCount = 2; renderPassInfo.Attachments = new Vk.AttachmentDescription[] { colourAttachment, depthAttachment }; renderPassInfo.SubpassCount = 1; renderPassInfo.Subpasses = new Vk.SubpassDescription[] { subpass }; renderPassInfo.DependencyCount = 1; renderPassInfo.Dependencies = new Vk.SubpassDependency[] { subpassDep }; try { this.wrapper.RenderPass = context.Device.CreateRenderPass(renderPassInfo); } catch (Vk.ResultException result) { throw new VkException("An error occurred while creating a render pass.", result); } }
public async Task <string> Post() { var parsedRequest = new JObject(); var result = "ok"; try { using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) { var request = await reader.ReadToEndAsync(); try { parsedRequest = JObject.Parse(request); } catch { throw new JsonReaderException("Не удалось преобразовать JSON"); } } // await Response.Body.WriteAsync(Encoding.UTF8.GetBytes("ok")); if (parsedRequest["type"] == null) { throw new Exception("Запрос не имеет свойство type"); } //Проверка Secret Key var config = Configuration.GetInstance(); if (!string.IsNullOrEmpty(config.GetConfig("vkSecretKey"))) { if (parsedRequest["secret"].ToString() != config.GetConfig("vkSecretKey")) { //Ключи неверные _logger.Log(LogLevel.Warning, "Request from undefined server. Secret keys does not match. Server IP: " + this.Request.Host.Host + Environment.NewLine + "Request: " + parsedRequest.ToString()); Response.StatusCode = 403; return("Forbidden"); } } switch (parsedRequest["type"].ToString()) { case "confirmation": result = VkHelper.GetConfirmationToken(); break; case "message_new": handleNewMessage(parsedRequest["object"]); break; default: throw new Exception("Неопознанный тип запроса: " + parsedRequest["type"]); } } catch (Exception e) { //Что-то сломалось result = e.Message; _logger.Log(LogLevel.Error, e.Message); } return(result); }
//Обработчик новых сообщений private void handleNewMessage(JToken obj) { var message = ""; var userId = Convert.ToInt32(obj["message"]?["peer_id"]); var date = Convert.ToInt32(obj["message"]?["date"]); try { var ownerIdGroupRAP = -28905875; if (userId == 0) { message = "Не удалось получить информацию об отправителе"; throw new Exception("Не удалось получить информацию об отправителе"); } if (date == 0) { date = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } // Тело сообщения var body = obj["message"]?["text"]?.ToString().Trim().ToLower(); if (body == null) { message = "Не удалось получить текст сообщения"; throw new Exception("Не удалось получить тело запроса"); } // Новые треки if (body.Contains("новые треки")) { var query = "#премьераТрека@rhymes"; var isSended = false; var musicCountStr = Regex.Match(body, @"[0-9]+").ToString(); if (!int.TryParse(musicCountStr, out var musicCount)) { musicCount = 4; } if (musicCount > 15) { VkHelper.SendMessage(userId, "Количество треков не должно превышать 15", date); return; } var posts = VkHelper.SearchWall(ownerIdGroupRAP, query, musicCount); foreach (var post in posts.WallPosts) { if (post.Attachments == null) { continue; } message = post.Text; var attachments = new List <Audio>(); foreach (var attachment in post.Attachments) { if (attachment.Instance is Audio) { attachments.Add(attachment.Instance as Audio); } } // Отправка каждой новой песни пользователю VkHelper.SendMessage(userId, message, date, attachments); isSended = true; } // Конец foreach для posts if (!isSended) { VkHelper.SendMessage(userId, "Не удалось найти новые треки", date); } } // Случайные треки else if (body.Contains("случайные треки")) { int countAudios; int randOffset; var audios = new List <Audio>(); var audiosByAuthor = new List <Audio>(); var match = Regex.Match(body, @"(случайные треки)\s*([0-9]*)\s*(\w*)", RegexOptions.IgnoreCase); var musicCountStr = match.Groups[2].Value; var author = match.Groups[3].Value; if (!int.TryParse(musicCountStr, out var musicCount)) { musicCount = 1; } if (musicCount > 10) { musicCount = 10; } if (author == "") { countAudios = VkHelper.GetCountAudio(ownerIdGroupRAP); if (countAudios > 0) { if (countAudios < musicCount) { musicCount = countAudios > 10 ? 10 : countAudios; } randOffset = new Random().Next(0, countAudios - musicCount); audios = VkHelper.GetAudios(ownerIdGroupRAP, musicCount, randOffset).ToList(); } else { message = "Не удалось найти песни по указанному запросу"; } } else { audios = VkHelper.SearchAudios(author, true).ToList(); countAudios = audios.Count; if (countAudios > 0) { if (countAudios < musicCount) { musicCount = countAudios; } randOffset = new Random().Next(0, countAudios - musicCount); audiosByAuthor = audios.ToList().GetRange(randOffset, musicCount); } else { message = "Не удалось найти песни по указанному запросу"; } } VkHelper.SendMessage(userId, message, date, author == "" ? audios : audiosByAuthor); } //Помощь else if (body.Contains("функции")) { message = "--------" + Environment.NewLine + "Новые треки N" + Environment.NewLine + "• Данная функция позволяет получить последние новые песни из группы \"Рифмы и Панчи\"" + Environment.NewLine + "• N - количество песен для получения. Если не указывать, то по умолчанию вернется 4 песни" + Environment.NewLine + "• Примеры: Новые треки 10 или Новые треки" + Environment.NewLine + "--------" + Environment.NewLine + "Случайные треки N Автор" + Environment.NewLine + "• Данная функция позволяет получать случайные песни" + Environment.NewLine + "• N - количество песен для получения. Если не указывать, то по умолчанию вернется 1 песня" + Environment.NewLine + "• Автор - автор песен, у которого необходимо получить случайные треки. Если не указывать, будет происходить поиск случайных песен из группы \"Рифмы и Панчи\"" + Environment.NewLine + "• Примеры: Случайные треки 10 Нервы, или Случайные треки 5, или Случайные треки Нервы, или Случайные треки" + Environment.NewLine + "--------" + Environment.NewLine + "Функции" + Environment.NewLine + "• Сообщает о доступных функциях"; VkHelper.SendMessage(userId, message, date); } else { message = "Неизвестная функция. " + Environment.NewLine + "Попробуйте воспользоваться запросом \"Функции\""; VkHelper.SendMessage(userId, message, date); } } catch (Exception e) { if (message == "") { message = "Что-то пошло не так, не удалось обработать запрос"; } if (userId != 0 && date != 0) { VkHelper.SendMessage(userId, message, date); } _logger.Log(LogLevel.Error, e.Message); } }
public CallBackController(IConfiguration configuration) { Cfg = configuration; VkHelper.AuthWithToken(Cfg["AccessToken"]); }