Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ktos committed Oct 27, 2019
1 parent 062d0bb commit 010f956
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 40 deletions.
56 changes: 29 additions & 27 deletions src/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,19 +113,17 @@ public void LoadAlreadyAnalyzed()
}
else
{
logger.LogInformation("Loading already analyzed posts database.");
using (var fs = new FileStream(AnalyzedDatabasePath, FileMode.Open, FileAccess.Read))
logger.LogDebug("Loading already analyzed posts database.");
using var fs = new FileStream(AnalyzedDatabasePath, FileMode.Open, FileAccess.Read);
if (fs.Length == 0)
{
if (fs.Length == 0)
{
analyzed = new HashSet<int>();
return;
}
else
{
var formatter = new BinaryFormatter();
analyzed = formatter.Deserialize(fs) as HashSet<int>;
}
analyzed = new HashSet<int>();
return;
}
else
{
var formatter = new BinaryFormatter();
analyzed = formatter.Deserialize(fs) as HashSet<int>;
}
}
}
Expand All @@ -138,12 +136,10 @@ public void SaveAlreadyAnalyzed()
if (IgnoreAlreadyAnalyzed)
return;

using (var fs = new FileStream(AnalyzedDatabasePath, FileMode.Create, FileAccess.Write))
{
logger.LogInformation("Saving already analyzed ids database.");
var formatter = new BinaryFormatter();
formatter.Serialize(fs, analyzed);
}
using var fs = new FileStream(AnalyzedDatabasePath, FileMode.Create, FileAccess.Write);
logger.LogDebug("Saving already analyzed ids database.");
var formatter = new BinaryFormatter();
formatter.Serialize(fs, analyzed);
}

/// <summary>
Expand All @@ -152,9 +148,9 @@ public void SaveAlreadyAnalyzed()
/// <param name="postIds">A list of post ids to analyze</param>
public async Task AnalyzePostsByIdsAsync(int[] postIds)
{
foreach (var item in postIds.Select(async x => await coyoteHandler.GetSinglePost(x)))
foreach (var item in postIds.Select(async x => await coyoteHandler.GetSinglePost(x).ConfigureAwait(false)))
{
await AnalyzePostAsync(item.Result);
await AnalyzePostAsync(item.Result).ConfigureAwait(false);
}
}

Expand All @@ -165,28 +161,34 @@ public async Task AnalyzePostsByIdsAsync(int[] postIds)
public async Task AnalyzePostAsync(Post post)
{
if (analyzed.Contains(post.id))
{
logger.LogDebug("Ignoring post {0} because already analyzed", post.id);
return;
}

analyzed.Add(post.id);
SaveAlreadyAnalyzed();

if (IgnorePost(post))
{
logger.LogDebug("Ignoring post {0} because of blacklist", post.id);
return;
}

logger.LogDebug("Analyzing post {0}", post.id);
logger.LogInformation("Analyzing post {0}", post.id);
var problems = postAnalyzer.Analyze(post);

if (problems.Count > 0)
{
logger.LogInformation("Found problems in post {0}\n{1}\n{2}", post.id, post.url, post.text.Length < 50 ? post.text : post.text.Substring(0, 50));
foreach (var item in problems)
{
logger.LogInformation(item.ToString());
logger.LogDebug(item.ToString());

if (PostComments)
{
logger.LogDebug("Posting comment");
await coyoteHandler.PostComment(post, string.Format(NagMessage, item.Probability));
logger.LogInformation("Posting comment");
await coyoteHandler.PostComment(post, string.Format(NagMessage, item.Probability)).ConfigureAwait(false);
}
}
}
Expand All @@ -199,7 +201,7 @@ public async Task AnalyzePostAsync(Post post)
/// <param name="password">Password to log in with</param>
public async Task LoginAsync(string username, string password)
{
await coyoteHandler.Login(username, password);
await coyoteHandler.Login(username, password).ConfigureAwait(false);
}

private bool IgnorePost(Post post)
Expand All @@ -217,11 +219,11 @@ private bool IgnorePost(Post post)
public async Task AnalyzeNewPostsAsync()
{
logger.LogDebug("Getting posts...");
var posts = await coyoteHandler.GetPosts();
var posts = await coyoteHandler.GetPosts().ConfigureAwait(false);

foreach (var post in posts)
{
await AnalyzePostAsync(post);
await AnalyzePostAsync(post).ConfigureAwait(false);
}
logger.LogDebug("Analyzed (or ignored) everything");
}
Expand Down
26 changes: 13 additions & 13 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -53,9 +51,9 @@ internal static class Program
private static Bot bot;
private static ILogger logger;

private static bool runOnce = false;
private static bool configured = false;
private static bool runOnSet = false;
private static bool isRunOnce = false;
private static bool isConfigured = false;
private static bool isRunSet = false;
private static int[] runSet;

public class Options
Expand Down Expand Up @@ -97,18 +95,18 @@ private static void Main(string[] args)
Console.CancelKeyPress += RequestApplicationClose;
var opts = Parser.Default.ParseArguments<Options>(args).WithParsed(Configure);

if (!configured)
if (!isConfigured)
return;

bot.LoadAlreadyAnalyzed();

if (runOnSet)
if (isRunSet)
{
bot.AnalyzePostsByIdsAsync(runSet).Wait();
return;
}

if (runOnce)
if (isRunOnce)
{
bot.AnalyzeNewPostsAsync().Wait();
logger.LogDebug("Single run completed.");
Expand All @@ -125,13 +123,14 @@ private static void Main(string[] args)
}

bot.SaveAlreadyAnalyzed();
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}

[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static void RequestApplicationClose(object sender, ConsoleCancelEventArgs e)
{
logger.LogDebug("Requested application close by {0}", e.SpecialKey);
bot.SaveAlreadyAnalyzed();
logger?.LogDebug("Requested application close by {0}", e.SpecialKey);
bot?.SaveAlreadyAnalyzed();
Environment.Exit(0);
}

Expand All @@ -153,6 +152,7 @@ private static void Configure(Options opts)
.AddSingleton<CoyoteHandler>()
.AddSingleton<PostAnalyzer>()
.AddSingleton<Bot>()
.AddSingleton<Blacklist>()
.BuildServiceProvider();

bot = serviceProvider.GetService<Bot>();
Expand Down Expand Up @@ -184,13 +184,13 @@ private static void Configure(Options opts)
if (bot.PostComments)
bot.LoginAsync(username, password).Wait();

runOnce = opts.RunOnce || timeBetweenUpdates == 0;
isRunOnce = opts.RunOnce || timeBetweenUpdates == 0;

if (!string.IsNullOrEmpty(opts.RunOnSet))
{
runSet = opts.RunOnSet.Split(',').Select(x => int.Parse(x)).ToArray();
if (runSet != null)
runOnSet = true;
isRunSet = true;
}

var blacklistDefinition = config.GetValue("blacklist", opts.Blacklist ?? string.Empty);
Expand All @@ -199,7 +199,7 @@ private static void Configure(Options opts)

bot.IgnoreAlreadyAnalyzed = opts.IgnoreAlreadyAnalyzed;

configured = true;
isConfigured = true;
}
}
}

0 comments on commit 010f956

Please sign in to comment.