Compare commits

..

No commits in common. "e6a0e9f89462552b062259aad58ebe95108d550d" and "7042afc76ae1b01773f07393daad4bfc73ff1d8a" have entirely different histories.

8 changed files with 84 additions and 137 deletions

View File

@ -5,5 +5,7 @@ public class CajetanConfig
public string[] NonInteractiveSpecificLists { get; set; } = [];
public string[] NonInteractiveSpecificUsers { get; set; } = [];
public EMode Mode { get; set; } = EMode.DownloadCreatorContent;
public EMode Mode { get; set; } = EMode.None;
public string ErrorMessage { get; set; } = string.Empty;
}

View File

@ -1,8 +0,0 @@
namespace OF_DL.Models.Dtos.Lists;
public class ListUsersDto
{
[JsonProperty("list")] public List<UsersListDto> List { get; set; } = [];
[JsonProperty("hasMore")] public bool? HasMore { get; set; }
[JsonProperty("nextOffset")] public int NextOffset { get; set; }
}

View File

@ -2,6 +2,7 @@ namespace OF_DL.Models;
public enum EMode
{
None,
DownloadCreatorContent,
OutputBlockedUsers,
UpdateAllUserInfo

View File

@ -49,7 +49,14 @@ static async Task<ServiceCollection> ConfigureServices(string[] args)
AnsiConsole.Markup("[green]config.conf located successfully!\n[/]");
CajetanConfig cajetanConfig = ParseCommandlineArgs(args, configService.CurrentConfig);
if (!ParseCommandlineArgs(args, configService.CurrentConfig, out CajetanConfig cajetanConfig))
{
AnsiConsole.MarkupLine($"\n[red]{cajetanConfig.ErrorMessage}[/]\n");
AnsiConsole.MarkupLine("[red]Press any key to exit.[/]");
Console.ReadKey();
exitHelper.ExitWithCode(3);
}
// Set up full dependency injection with loaded config
services = [];
@ -83,26 +90,26 @@ static async Task<ServiceCollection> ConfigureServices(string[] args)
return services;
}
static CajetanConfig ParseCommandlineArgs(string[] args, Config currentConfig)
static bool ParseCommandlineArgs(string[] args, Config currentConfig, out CajetanConfig parsedConfig)
{
const string SPECIFIC_LISTS_ARG = "--specific-lists";
const string SPECIFIC_USERS_ARG = "--specific-users";
const string OUTPUT_BLOCKED_USERS_ARG = "--output-blocked";
const string UPDATE_ALL_USER_INFO_ARG = "--update-userinfo";
CajetanConfig parsedConfig = new();
parsedConfig = new();
if (ParseListAndUserArguments(ref parsedConfig))
return parsedConfig;
return true;
if (ParseFlagArgument(OUTPUT_BLOCKED_USERS_ARG, EMode.OutputBlockedUsers, ref parsedConfig))
return parsedConfig;
return true;
if (ParseFlagArgument(UPDATE_ALL_USER_INFO_ARG, EMode.UpdateAllUserInfo, ref parsedConfig))
return parsedConfig;
return true;
// Will process all active subscriptions
return parsedConfig;
parsedConfig.ErrorMessage = "No mode argument provided!";
return false;
bool ParseListAndUserArguments(ref CajetanConfig parsedConfig)
{

View File

@ -11,7 +11,6 @@ global using OF_DL.Services;
global using Serilog;
global using Serilog.Context;
global using Spectre.Console;
global using ListsDtos = OF_DL.Models.Dtos.Lists;
global using MessageDtos = OF_DL.Models.Dtos.Messages;
global using MessageEntities = OF_DL.Models.Entities.Messages;
global using SubscriptionsDtos = OF_DL.Models.Dtos.Subscriptions;

View File

@ -27,95 +27,6 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe
return GetAllSubscriptions(endpoint, includeRestricted, "expired");
}
public new async Task<MessageEntities.MessageCollection> GetMessages(string endpoint, string folder, IStatusReporter statusReporter)
{
(bool couldExtract, long userId) = ExtractUserId(endpoint);
_eventHandler.OnMessage("Getting Unread Chats", "grey");
HashSet<long> usersWithUnread = couldExtract ? await GetUsersWithUnreadMessagesAsync() : [];
MessageEntities.MessageCollection messages = await base.GetMessages(endpoint, folder, statusReporter);
if (usersWithUnread.Contains(userId))
{
_eventHandler.OnMessage("Restoring unread state", "grey");
await MarkAsUnreadAsync($"/chats/{userId}/mark-as-read");
}
return messages;
static (bool couldExtract, long userId) ExtractUserId(string endpoint)
{
string withoutChatsAndMessages = endpoint
.Replace("chats", "", StringComparison.OrdinalIgnoreCase)
.Replace("messages", "", StringComparison.OrdinalIgnoreCase);
string trimmed = withoutChatsAndMessages.Trim(' ', '/', '\\');
if (long.TryParse(trimmed, out long userId))
return (true, userId);
return (false, default);
}
}
public new async Task<Dictionary<string, long>?> GetListUsers(string endpoint)
{
if (!HasSignedRequestAuth())
return null;
try
{
Dictionary<string, long> users = new(StringComparer.OrdinalIgnoreCase);
Log.Debug($"Calling GetListUsers - {endpoint}");
const int limit = 50;
int offset = 0;
Dictionary<string, string> getParams = new()
{
["format"] = "infinite",
["limit"] = limit.ToString()
};
while (true)
{
getParams["offset"] = offset.ToString();
string? body = await BuildHeaderAndExecuteRequests(getParams, endpoint, new HttpClient());
if (string.IsNullOrWhiteSpace(body))
break;
ListsDtos.ListUsersDto? listUsers = DeserializeJson<ListsDtos.ListUsersDto>(body, s_mJsonSerializerSettings);
if (listUsers?.List is null)
break;
foreach (ListsDtos.UsersListDto item in listUsers.List)
{
if (item.Id is null)
continue;
users.TryAdd(item.Username, item.Id.Value);
}
if (listUsers.HasMore is false)
break;
offset = listUsers.NextOffset;
}
return users;
}
catch (Exception ex)
{
ExceptionLoggerHelper.LogException(ex);
}
return null;
}
public async Task<UserEntities.UserInfo?> GetDetailedUserInfoAsync(string endpoint)
{
Log.Debug($"Calling GetDetailedUserInfo: {endpoint}");
@ -153,6 +64,29 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe
return null;
}
public async Task SortBlockedAsync(string endpoint, string order = "recent", string direction = "desc")
{
Log.Debug($"Calling SortBlocked - {endpoint}");
try
{
var reqBody = new { order, direction };
var result = new { success = false, canAddFriends = false };
string? body = await BuildHeaderAndExecuteRequests([], endpoint, GetHttpClient(), HttpMethod.Post, reqBody);
if (!string.IsNullOrWhiteSpace(body))
result = JsonConvert.DeserializeAnonymousType(body, result);
if (result?.success != true)
_eventHandler.OnMessage($"Failed to sort blocked (order: {order}, direction; {direction})! Endpoint: {endpoint}", "yellow");
}
catch (Exception ex)
{
ExceptionLoggerHelper.LogException(ex);
}
}
public async Task<Dictionary<string, long>> GetUsersWithProgressAsync(string typeDisplay, string endpoint, string? typeParam, bool offsetByCount)
{
Dictionary<string, long> usersOfType = await _eventHandler.WithStatusAsync(
@ -238,6 +172,37 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe
}
}
public new async Task<MessageEntities.MessageCollection> GetMessages(string endpoint, string folder, IStatusReporter statusReporter)
{
(bool couldExtract, long userId) = ExtractUserId(endpoint);
_eventHandler.OnMessage("Getting Unread Chats", "grey");
HashSet<long> usersWithUnread = couldExtract ? await GetUsersWithUnreadMessagesAsync() : [];
MessageEntities.MessageCollection messages = await base.GetMessages(endpoint, folder, statusReporter);
if (usersWithUnread.Contains(userId))
{
_eventHandler.OnMessage("Restoring unread state", "grey");
await MarkAsUnreadAsync($"/chats/{userId}/mark-as-read");
}
return messages;
static (bool couldExtract, long userId) ExtractUserId(string endpoint)
{
string withoutChatsAndMessages = endpoint
.Replace("chats", "", StringComparison.OrdinalIgnoreCase)
.Replace("messages", "", StringComparison.OrdinalIgnoreCase);
string trimmed = withoutChatsAndMessages.Trim(' ', '/', '\\');
if (long.TryParse(trimmed, out long userId))
return (true, userId);
return (false, default);
}
}
public async Task<HashSet<long>> GetUsersWithUnreadMessagesAsync()
{
MessageDtos.ChatsDto unreadChats = await GetChatsAsync("/chats", onlyUnread: true);
@ -279,29 +244,6 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe
}
}
public async Task SortBlockedAsync(string endpoint, string order = "recent", string direction = "desc")
{
Log.Debug($"Calling SortBlocked - {endpoint}");
try
{
var reqBody = new { order, direction };
var result = new { success = false, canAddFriends = false };
string? body = await BuildHeaderAndExecuteRequests([], endpoint, GetHttpClient(), HttpMethod.Post, reqBody);
if (!string.IsNullOrWhiteSpace(body))
result = JsonConvert.DeserializeAnonymousType(body, result);
if (result?.success != true)
_eventHandler.OnMessage($"Failed to sort blocked (order: {order}, direction; {direction})! Endpoint: {endpoint}", "yellow");
}
catch (Exception ex)
{
ExceptionLoggerHelper.LogException(ex);
}
}
private async Task<Dictionary<string, long>?> GetAllSubscriptions(string endpoint, bool includeRestricted, string type)
{
if (!HasSignedRequestAuth())

View File

@ -2,8 +2,6 @@ namespace OF_DL.Services;
public interface ICajetanApiService : IApiService
{
new Task<Dictionary<string, long>?> GetListUsers(string endpoint);
Task<UserEntities.UserInfo?> GetDetailedUserInfoAsync(string endpoint);
Task<Dictionary<string, long>> GetUsersWithProgressAsync(string typeDisplay, string endpoint, string? typeParam, bool offsetByCount);
Task<HashSet<long>> GetUsersWithUnreadMessagesAsync();

View File

@ -134,7 +134,7 @@ internal class Worker(IServiceProvider serviceProvider)
DateTime startTime = DateTime.Now;
UserListResult allUsersAndLists = await GetAvailableUsersAsync();
Dictionary<string, long> usersToDownload = allUsersAndLists.Users;
Dictionary<string, long> usersToDownload = [];
if (_cajetanConfig.NonInteractiveSpecificLists is not null && _cajetanConfig.NonInteractiveSpecificLists.Length > 0)
usersToDownload = await GetUsersFromSpecificListsAsync(allUsersAndLists, _cajetanConfig.NonInteractiveSpecificLists);
@ -142,6 +142,9 @@ internal class Worker(IServiceProvider serviceProvider)
else if (_cajetanConfig.NonInteractiveSpecificUsers is not null && _cajetanConfig.NonInteractiveSpecificUsers.Length > 0)
usersToDownload = GetUsersFromSpecificUsernames(allUsersAndLists, [.. _cajetanConfig.NonInteractiveSpecificUsers]);
if (usersToDownload.Count == 0)
return;
int userNum = 0;
int userCount = usersToDownload.Count;
CajetanDownloadEventHandler eventHandler = new();
@ -325,14 +328,17 @@ internal class Worker(IServiceProvider serviceProvider)
Log.Information("Getting Users from list '{ListName:l}' (Include Restricted: {IncludeRestrictedSubscriptions})", name, currentConfig.IncludeRestrictedSubscriptions);
AnsiConsole.MarkupLine($"[green]Getting Users from list '{name}' (Include Restricted: {currentConfig.IncludeRestrictedSubscriptions})[/]");
Dictionary<string, long> listUsernames = await _apiService.GetListUsers($"/lists/{listId}/users") ?? [];
List<string> listUsernames = await _apiService.GetListUsers($"/lists/{listId}/users") ?? [];
foreach ((string username, long userId) in listUsernames)
foreach (string u in listUsernames)
{
if (usersFromLists.ContainsKey(username))
if (usersFromLists.ContainsKey(u))
continue;
usersFromLists[username] = userId;
if (!allUsersAndLists.Users.TryGetValue(u, out long userId))
continue;
usersFromLists[u] = userId;
}
}