Skip to content

Commit

Permalink
Fixing up the tool to stop if config is wrong
Browse files Browse the repository at this point in the history
Fix for issue where would never finish a blocktrain

Made writing in a lock so it doesn't bump over itself (might not work)

Added fxCop and styleCop

LOADS OF CLEANING
  • Loading branch information
rmaclean committed May 24, 2020
1 parent bd3b775 commit 342b3a6
Show file tree
Hide file tree
Showing 19 changed files with 432 additions and 300 deletions.
26 changes: 26 additions & 0 deletions CommandHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace twot
{
using System;
using static System.ConsoleColor;
using static ConsoleHelper;

internal static class CommandHelpers
{
internal static bool CommandHeader(string title, bool dryRun = false)
{
Writeln(Cyan, title);
if (dryRun)
{
Writeln(Yellow, " ⚠ Dry run mode");
}

if (!Config.Load().Success)
{
return false;
}

Console.WriteLine();
return true;
}
}
}
54 changes: 30 additions & 24 deletions Commands/BaseScoreCommand.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,46 @@
namespace twot
{
using System.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tweetinvi.Models;

using Tweetinvi;
using System.Collections.Generic;
using static ConsoleHelper;
using Tweetinvi.Models;

using static System.ConsoleColor;
using static ConsoleHelper;

class ScoreSettings
internal class ScoreSettings
{
public string mode { get; set; } = "";
public string mode { get; set; } = string.Empty;

public Action<int>? onComplete { get; set; }

public Func<IUser?, Task>? onUserAsync { get; set; }

public Action<IUser?, ThreadedLogger, double>? onUser { get; set; }

public Action<ThreadedLogger>? beforeRun { get; set; }
}

class BaseScoreCommand
internal class BaseScoreCommand
{
internal async Task<List<(IUser, double)>> GetBotsOrDead(double minScore)
internal static async Task<List<(IUser, double)>> GetBotsOrDead(double minScore)
{
Writeln(DarkBlue, "Loading people, this may take some time...");
using (var spinner = new Spinner())
{
var me = User.GetAuthenticatedUser();

var friends = await me.GetFriendIdsAsync(Int32.MaxValue);
var followers = await me.GetFollowersAsync(Int32.MaxValue);
var friends = await me.GetFriendIdsAsync(int.MaxValue);
var followers = await me.GetFollowersAsync(int.MaxValue);

var scoringConfig = new ScoreConfig();

var result = followers
.Where(_ => !friends.Contains(_.Id))
.Select(Follower => (Follower, Score: Score(Follower, scoringConfig)))
.Select(follower => (Follower: follower, Score: Score(follower, scoringConfig)))
.Where(_ => _.Score > minScore)
.OrderBy(_ => _.Follower.Name);

Expand All @@ -43,18 +49,7 @@ internal async Task<List<(IUser, double)>> GetBotsOrDead(double minScore)
}
}

private async Task InvokeAction(IUser follower, double score, ThreadedLogger logger, ProgressBar pbar, ScoreSettings settings)
{
if (settings.onUserAsync != null)
{
await settings.onUserAsync!.Invoke(follower);
}

settings.onUser?.Invoke(follower, logger, score);
pbar.Tick($"Processed @{follower.UserIdentifier.ScreenName}");
}

internal async Task Run(double minScore, bool log, ScoreSettings settings)
internal static async Task Run(double minScore, bool log, ScoreSettings settings)
{
var botsOrDead = await GetBotsOrDead(minScore);
using (var logger = new ThreadedLogger($"{settings.mode}.log", log))
Expand All @@ -76,7 +71,18 @@ internal async Task Run(double minScore, bool log, ScoreSettings settings)
settings.onComplete!.Invoke(botsOrDead.Count);
}

double Score(IUser follower, ScoreConfig scoring)
private static async Task InvokeAction(IUser follower, double score, ThreadedLogger logger, ProgressBar pbar, ScoreSettings settings)
{
if (settings.onUserAsync != null)
{
await settings.onUserAsync!.Invoke(follower);
}

settings.onUser?.Invoke(follower, logger, score);
pbar.Tick($"Processed @{follower.UserIdentifier.ScreenName}");
}

private static double Score(IUser follower, ScoreConfig scoring)
{
var result = 0.0;
if (scoring.DefaultProfileImage.Enabled && follower.DefaultProfileImage == scoring.DefaultProfileImage.Value)
Expand Down
39 changes: 21 additions & 18 deletions Commands/BlockTrainCommand.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
namespace twot
{
using System.Linq;
using System;
using System.Threading.Tasks;
using Tweetinvi;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Linq;
using System.Threading.Tasks;

using Tweetinvi;
using Tweetinvi.Models;
using System.Collections.Generic;
using static ConsoleHelper;

using static System.ConsoleColor;
using static CommandHelpers;
using static ConsoleHelper;

class BlockTrain : ICommand
#pragma warning disable CA1812
internal class BlockTrain : ICommand
#pragma warning restore CA1812
{
public void AddCommand(Command rootCommand)
{
Expand All @@ -38,22 +43,22 @@ public void AddCommand(Command rootCommand)
muteOption.AddAlias("-m");
cmd.Add(muteOption);

cmd.Handler = CommandHandler.Create<bool, string, bool, bool>(Execute);
cmd.Handler = CommandHandler.Create<bool, string, bool, bool>(this.Execute);
rootCommand.Add(cmd);
}

private async Task<List<IUser>> GetTargets(string targetUsername)
private static async Task<List<IUser>> GetTargets(string targetUsername)
{
using (var spinner = new Spinner())
{
var result = new List<IUser>();
var me = User.GetAuthenticatedUser();
var friends = await me.GetFriendsAsync(Int32.MaxValue);
var friends = await me.GetFriendsAsync(int.MaxValue);

var target = User.GetUserFromScreenName(targetUsername);
result.Add(target);

var enermies = await target.GetFollowersAsync(Int32.MaxValue);
var enermies = await target.GetFollowersAsync(int.MaxValue);

var targetsForBlock = enermies.Where(enermy => !friends.Contains(enermy));
result.AddRange(targetsForBlock);
Expand All @@ -62,7 +67,7 @@ private async Task<List<IUser>> GetTargets(string targetUsername)
}
}

private async Task BlockUser(IUser targetUser, bool dryRun, ProgressBar pbar, ThreadedLogger logger, bool mute)
private static async Task BlockUser(IUser targetUser, bool dryRun, ProgressBar pbar, ThreadedLogger logger, bool mute)
{
if (!dryRun)
{
Expand All @@ -80,16 +85,13 @@ private async Task BlockUser(IUser targetUser, bool dryRun, ProgressBar pbar, Th
logger.LogMessage(targetUser!.ScreenName);
}

private async Task Execute(bool dryRun, string targetUsername, bool log, bool mute)
private async Task<int> Execute(bool dryRun, string targetUsername, bool log, bool mute)
{
Writeln(Cyan, "Block Train 🚂");
if (dryRun)
if (!CommandHeader("Block Train 🚂", dryRun))
{
Writeln(Yellow, " ⚠ Dry run mode");
return -1;
}

Console.WriteLine();

Writeln(DarkBlue, $"Loading people to {(mute ? "mute" : "block")}, this may take some time...");
var targets = await GetTargets(targetUsername).ConfigureAwait(false);

Expand All @@ -106,7 +108,8 @@ private async Task Execute(bool dryRun, string targetUsername, bool log, bool mu
Task.WaitAll(actions);
}

Writeln(Green, $"{(mute ? "Muted" : "Blocked")} a total of { targets.Count } people");
Writeln(Green, $"{(mute ? "Muted" : "Blocked")} a total of {targets.Count} people");
return 0;
}
}
}
28 changes: 16 additions & 12 deletions Commands/CleanCommand.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
namespace twot
{
using System;
using System.Threading.Tasks;
using System.CommandLine;
using System.CommandLine.Invocation;
using static ConsoleHelper;
using System.Threading.Tasks;

using static System.ConsoleColor;
using static CommandHelpers;
using static ConsoleHelper;

class CleanCommand : BaseScoreCommand, ICommand
#pragma warning disable CA1812
internal class CleanCommand : BaseScoreCommand, ICommand
#pragma warning restore CA1812
{
public void AddCommand(Command rootCommand)
{
Expand All @@ -21,8 +25,8 @@ public void AddCommand(Command rootCommand)
var minScoreOption = new Option<double>(
"--score",
() => 0.85,
"Sets the score for min kicking. Defaults to 0.85"
);
"Sets the score for min kicking. Defaults to 0.85");

minScoreOption.Name = "minscore";
minScoreOption.AddAlias("-s");
cmd.Add(minScoreOption);
Expand All @@ -33,16 +37,15 @@ public void AddCommand(Command rootCommand)
logOption.AddAlias("-l");
cmd.Add(logOption);

cmd.Handler = CommandHandler.Create<bool, double, bool>(Execute);
cmd.Handler = CommandHandler.Create<bool, double, bool>(this.Execute);
rootCommand.Add(cmd);
}

private async Task Execute(bool dryRun, double minScore, bool log)
private async Task<int> Execute(bool dryRun, double minScore, bool log)
{
Writeln(Cyan, "Running clean 🧹");
if (dryRun)
if (!CommandHeader("Running clean 🧹", dryRun))
{
Writeln(Yellow, " ⚠ Dry run mode");
return -1;
}

await Run(minScore, log, new ScoreSettings
Expand All @@ -56,7 +59,6 @@ private async Task Execute(bool dryRun, double minScore, bool log)
await user!.BlockAsync();
await user!.UnBlockAsync();
}
},
onUser = (user, logger, score) => logger.LogMessage(user!.UserIdentifier.ScreenName),
beforeRun = logger =>
Expand All @@ -67,8 +69,10 @@ private async Task Execute(bool dryRun, double minScore, bool log)
{
logger.LogMessage("# DryRun Mode");
}
}
},
});

return 0;
}
}
}
31 changes: 17 additions & 14 deletions Commands/InitCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ namespace twot
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;

using Newtonsoft.Json;
using static ConsoleHelper;

using static System.ConsoleColor;
using static ConsoleHelper;

class InitCommand : twot.ICommand
#pragma warning disable CA1812
internal class InitCommand : twot.ICommand
#pragma warning restore CA1812
{
public void AddCommand(Command rootCommand)
{
Expand All @@ -17,21 +21,20 @@ public void AddCommand(Command rootCommand)

var scoreInit = new Command("Score", "Initialises a score file for use with the Clean command.");
scoreInit.AddAlias("score");
scoreInit.AddOption(new Option<string>("--file", () => "score.json", "This allows you to specify where you output " +
"the scoring config to. Defaults to score.json"));
scoreInit.Handler = CommandHandler.Create<string>(InitScoreConfig);
scoreInit.AddOption(new Option<string>("--file", () => "score.json", "This allows you to specify where " +
"you output the scoring config to. Defaults to score.json"));
scoreInit.Handler = CommandHandler.Create<string>(this.InitScoreConfig);

cmd.AddCommand(scoreInit);

var secretsInit = new Command("Secrets", "Initialises a secrets.json file for your Twitter keys.");
secretsInit.AddAlias("secrets");
secretsInit.AddOption(new Option<string>("--file", () => "secrets.json", "This allows you to specify where you output " +
"the secrets config to. Defaults to secrets.json"));
secretsInit.Handler = CommandHandler.Create<string>(InitSecretsConfig);
secretsInit.AddOption(new Option<string>("--file", () => "secrets.json", "This allows you to specify " +
"where you output the secrets config to. Defaults to secrets.json"));
secretsInit.Handler = CommandHandler.Create<string>(this.InitSecretsConfig);

cmd.AddCommand(secretsInit);


rootCommand.Add(cmd);
}

Expand All @@ -50,18 +53,18 @@ private void InitScoreConfig(string file)
}
}

class SecretsConfig
internal class SecretsConfig
{
[JsonProperty(PropertyName = "twot:apikey")]
public string APIKey { get; set; } = "";
public string APIKey { get; set; } = string.Empty;

[JsonProperty(PropertyName = "twot:apisecret")]
public string APISecret { get; set; } = "";
public string APISecret { get; set; } = string.Empty;

[JsonProperty(PropertyName = "twot:accesstoken")]
public string AccessToken { get; set; } = "";
public string AccessToken { get; set; } = string.Empty;

[JsonProperty(PropertyName = "twot:accesssecret")]
public string AccessSecret { get; set; } = "";
public string AccessSecret { get; set; } = string.Empty;
}
}

0 comments on commit 342b3a6

Please sign in to comment.