Created
September 8, 2019 19:26
-
-
Save ivanmem/59c34f654b5bb490b521473c775100f8 to your computer and use it in GitHub Desktop.
LongPoolUser.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using VkNet.Abstractions; | |
using VkNet.Exception; | |
using VkNet.Model;using VkNet.Model.RequestParams; | |
namespace ProjectName | |
{ | |
public class LongPool | |
{ | |
public LongPool(OptionsObj options) | |
{ | |
this._api = Authorization.GetInstance(options.Login, options.Password); | |
if (_api is null) | |
{ | |
Logger.Error(_api, null, "Ошибка авторизации."); | |
return; | |
} | |
this.uploads = new Uploads(_api); | |
BotId = (ulong)options.BotId; | |
} | |
private IVkApi _api; | |
private Uploads uploads; | |
private ulong BotId; | |
public string CommandsPath; | |
private void MonteceVkBot_Logout(IVkApi owner) | |
{ | |
Console.WriteLine("Отключение от VK...", ConsoleColor.Red); | |
} | |
private bool IsActive; | |
private Timer WatchTimer = null; | |
private ulong? _ts; | |
private ulong? _pts; | |
private string _key; | |
private string _server; | |
private delegate void MessagesRecievedDelegate(IVkApi owner, IEnumerable<Message> groupUpdate); | |
private event MessagesRecievedDelegate NewMessages; | |
/// <summary> | |
/// Запустить слежение за обновлениями в группе | |
/// </summary> | |
public void Start() | |
{ | |
try | |
{ | |
LongPollServerResponse Pool = _api.Messages.GetLongPollServer(true); | |
ulong ts; | |
if (Pool.Ts == "" || Pool.Ts == null) | |
{ | |
throw new Exception(); | |
} | |
else | |
{ | |
ts = Convert.ToUInt64(Pool.Ts); | |
} | |
StartAsync(ts, Pool.Pts); | |
NewMessages += uploads.GetUpdate; | |
_api.OnTokenExpires += MonteceVkBot_Logout; | |
Console.WriteLine("Слежение за сообщениями активировано.", ConsoleColor.Yellow); | |
} | |
catch (System.Net.Http.HttpRequestException ex) | |
{ | |
Console.WriteLine("Нет соединения с интернетом!", ConsoleColor.Red); | |
} | |
} | |
private LongPollServerResponse GetLongPoolServer(ulong? lastPts = null) | |
{ | |
LongPollServerResponse longPollServer = _api.Messages.GetLongPollServer(); | |
if (lastPts != null) | |
{ | |
_pts = lastPts; | |
} | |
_ts = Convert.ToUInt64(longPollServer.Ts); | |
_key = longPollServer.Key; | |
_server = longPollServer.Server; | |
return longPollServer; | |
} | |
private Task<LongPollServerResponse> GetLongPoolServerAsync(ulong? lastPts = null) | |
{ | |
return Task.Run(() => | |
{ | |
return GetLongPoolServer(lastPts); | |
}); | |
} | |
private IEnumerable<Message> GetLongPoolHistory() | |
{ | |
try | |
{ | |
LongPollHistoryResponse response = _api.Messages.GetLongPollHistory( | |
new MessagesGetLongPollHistoryParams | |
{ | |
Pts = _pts, | |
Ts = _ts.Value | |
}); | |
_pts = response.NewPts; | |
if (response.Messages.Count == 0) | |
{ | |
return null; | |
} | |
return response.Messages; | |
} | |
catch (LongPollException exception) | |
{ | |
if (exception is LongPollOutdateException outdateException) | |
{ | |
_ts = Convert.ToUInt64(outdateException.Ts); | |
} | |
else | |
{ | |
try | |
{ | |
LongPollServerResponse server = GetLongPoolServer(); | |
_ts = Convert.ToUInt64(server.Ts); | |
_key = server.Key; | |
_server = server.Server; | |
} | |
catch (System.Net.WebException ex) | |
{ | |
return null; | |
} | |
catch (IOException ex) | |
{ | |
return null; | |
} | |
catch (System.Threading.Tasks.TaskCanceledException ex) | |
{ | |
return null; | |
} | |
catch (System.Net.Sockets.SocketException ex) | |
{ | |
return null; | |
} | |
catch (Flurl.Http.FlurlHttpException) | |
{ | |
return null; | |
} | |
#if !DEBUG | |
catch (Exception ex) | |
{ | |
Logger.Error(_api, ex, "Ошибка в GetLongPollServer!"); | |
return null; | |
} | |
#endif | |
} | |
} | |
catch (System.Net.Http.HttpRequestException ex) | |
{ | |
Console.WriteLine("Нет соединения с интернетом! " + DateTime.Now, ConsoleColor.Red); | |
} | |
catch (System.Net.WebException ex) | |
{ | |
return null; | |
} | |
catch (IOException ex) | |
{ | |
return null; | |
} | |
catch (System.Threading.Tasks.TaskCanceledException ex) | |
{ | |
return null; | |
} | |
catch (System.Net.Sockets.SocketException ex) | |
{ | |
return null; | |
} | |
catch (Flurl.Http.FlurlHttpException) | |
{ | |
return null; | |
} | |
catch (VkNet.Exception.PublicServerErrorException ex) | |
{ | |
Console.WriteLine($"{DateTime.Now} Вконтакте недоступен!\n{ex.Message}", ConsoleColor.Red); | |
return null; | |
} | |
#if !DEBUG | |
catch (Exception ex) | |
{ | |
Logger.Error(_api, ex, "Ошибка в GetLongPoolHistory!"); | |
} | |
#endif | |
return null; | |
} | |
private Task<IEnumerable<Message>> GetLongPoolHistoryAsync() | |
{ | |
return Task.Run(() => { return GetLongPoolHistory(); }); | |
} | |
private async void WatchAsync(object state) | |
{ | |
IEnumerable<Message> history = await GetLongPoolHistoryAsync(); | |
if (!(history is null)) | |
{ | |
//CurrentSleepSteps = 0; | |
NewMessages?.Invoke(_api, history); | |
} | |
//else if (CurrentSleepSteps < MaxSleepSteps) | |
//{ | |
// CurrentSleepSteps++; | |
//} | |
WatchTimer.Change(333, Timeout.Infinite); | |
} | |
private async void StartAsync(ulong? lastTs = null, ulong? lastPts = null) | |
{ | |
if (IsActive) | |
{ | |
Console.WriteLine("Messages for {0} already watching", ConsoleColor.Red); | |
} | |
IsActive = true; | |
await GetLongPoolServerAsync(lastPts); | |
WatchTimer = new Timer(new TimerCallback(WatchAsync), null, 333, Timeout.Infinite); | |
} | |
private void Stop() | |
{ | |
if (WatchTimer != null) | |
{ | |
WatchTimer.Dispose(); | |
} | |
IsActive = false; | |
WatchTimer = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment