using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using AngleSharp.Dom;
using ArchiSteamFarm;
using ArchiSteamFarm.Plugins;
namespace m4d0ne.SpringClean2020
{
[Export(typeof(IPlugin))]
internal sealed class SpringClean : IBotCommand
{
public string Name => nameof(SpringClean);
public Version Version => typeof(SpringClean).Assembly.GetName().Version;
private async Task<bool> JoinEvent(Bot bot)
{
return await bot.ArchiWebHandler.UrlPostWithSession("https://store.steampowered.com", "/springcleaning/ajaxoptintoevent");
}
private async Task<List<uint>> GetGamesToPlay(Bot bot)
{
List<uint> tasks = new List<uint>();
IDocument eventPage = await bot.ArchiWebHandler.UrlGetToHtmlDocumentWithSession("https://store.steampowered.com", "/springcleaning");
if (eventPage != null)
{
var taskNodes = eventPage.GetElementsByClassName("task_app_completed");
foreach(var node in taskNodes)
{
string appID = node.GetAttributeValue("data-sg-appid");
if(!string.IsNullOrEmpty(appID))
{
tasks.Add(uint.Parse(appID));
}
}
}
return tasks;
}
private async Task RequestMissingLicense(Bot bot, List<uint> apps) {
List<uint> notOwned = new List<uint>();
var ownedGames = await bot.ArchiWebHandler.GetMyOwnedGames();
if (ownedGames != null) {
notOwned = ownedGames.Where(x => !apps.Contains(x.Key)).ToDictionary(x => x.Key).Keys.ToList();
} else {
notOwned = apps;
}
if (notOwned.Count() > 0) {
await bot.Commands.Response(ASF.GlobalConfig.SteamOwnerID, string.Format("ADDLICENSE {0} {1}", bot.BotName, string.Join(",", notOwned.Select(x => string.Format("app/{0}",x)))));
}
}
private async Task<string> DoSpringClean(Bot bot)
{
bool joined = await JoinEvent(bot);
if(joined)
{
List<uint> appsToPlay = await GetGamesToPlay(bot);
if(appsToPlay.Count > 0)
{
await RequestMissingLicense(bot, appsToPlay);
await bot.Actions.Play(appsToPlay);
return bot.BotName + ": Ok";
}
else
{
return bot.BotName + ": No games to play!";
}
}
return bot.BotName + ": Could not join event!";
}
public async Task<string> OnBotCommand(Bot bot, ulong steamID, string message, string[] args)
{
switch(args[0].ToUpperInvariant())
{
case "SPRINGCLEAN" when bot.HasPermission(steamID, BotConfig.EPermission.Operator):
if(args.Count() > 1)
{
List<Bot> activeBots = Bot.GetBots(args[1]).Where(x => x.IsConnectedAndLoggedOn).ToList();
int delayCnt = activeBots.Count();
IList<string> result = await Utilities.InParallel(activeBots.Select( async x => { await Task.Delay(TimeSpan.FromSeconds(delayCnt * 30)); --delayCnt; return await DoSpringClean(x); }));
return result.Count() > 0 ? string.Join(Environment.NewLine, result) : null;
}
else
{
return await DoSpringClean(bot);
}
default:
return null;
}
}
public void OnLoaded()
{
ASF.ArchiLogger.LogGenericInfo("SpringCleanPlugin loaded. Expect weird behaviour and unexpected consequences.");
}
}
}