Disforget/Search.cs

76 lines
2 KiB
C#
Raw Normal View History

2023-02-22 22:03:01 +01:00
using System.Net;
using System.Net.Http.Json;
namespace Disforget;
public class Search
{
2023-02-23 10:27:59 +01:00
public Search(ulong channel)
2023-02-22 22:03:01 +01:00
{
_channel = channel;
_cli = Utils.CreateClient();
}
2023-02-23 10:27:59 +01:00
private readonly HttpClient _cli;
private readonly List<Message> _messages = new();
private readonly ulong _channel;
private int _pages = -1, _total;
2023-02-22 22:03:01 +01:00
public async Task<List<Message>> Perform()
{
int page = 0;
2023-02-23 10:27:59 +01:00
do
2023-02-22 22:03:01 +01:00
{
await DoSearch(page);
await Task.Delay(1500);
page++;
2023-02-23 10:27:59 +01:00
} while (page < _pages);
2023-02-22 22:03:01 +01:00
Console.WriteLine($"\nFound and processed {_messages.Count} messages.");
return _messages;
}
private async Task DoSearch(int page)
{
2023-02-23 10:27:59 +01:00
var reqstr = $"https://discord.com/api/v9/{(Utils.Data.Type.ToLower() == "dm" ? "channels" : "guilds")}/{_channel}/messages/search?author_id={Utils.Data.UserId}&include_nsfw=true{(page > 0 ? $"&offset={page * 25}" : "")}";
2023-02-22 22:03:01 +01:00
REQ:
var resp = await _cli.GetAsync(reqstr);
if (resp.StatusCode == HttpStatusCode.TooManyRequests)
{
await Task.Delay(30000);
Console.Write($"\x1b[2K\rRequest {++page}/{_pages} FAILED [REPEATING] ({_messages.Count}/{_total})");
goto REQ;
}
Response? result = await resp.Content.ReadFromJsonAsync<Response>();
if (result == null)
{
Console.WriteLine("Failed (null)...");
Environment.Exit(3);
}
_total = result.TotalResults;
2023-02-23 10:27:59 +01:00
_pages = (int)Math.Ceiling(_total / 25.0);
2023-02-22 22:03:01 +01:00
_messages.AddRange(result.Messages);
Console.Write($"\x1b[2K\rRequest {++page}/{_pages} Status: {resp.StatusCode} ({_messages.Count}/{_total})");
}
2023-02-23 10:27:59 +01:00
public override bool Equals(object? obj)
{
return obj is Search search &&
_channel == search._channel;
}
public override int GetHashCode()
{
return HashCode.Combine(_cli, _messages, _channel, _pages, _total);
}
2023-02-22 22:03:01 +01:00
}