AFK Macro

Idle Mafia Macro/Source/src/linux/LinuxPages.cs

LinuxPages.cs

Linux: the pages' files · 72 lines · 3 KB

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace IdleMafiaBot
{
static class LinuxPages
{
public static void Watch(Bot bot, Settings s, string dir)
{
string file = Path.Combine(dir, "link-status.json");
object gate = new object();
string said = null;
Action write = () =>
{
try
{
var stats = bot.Stats;
string json = "{\"stats\": " + Q(Tag(s.StatsLink)) + ", \"statsOn\": " + B(stats.On) + ", \"statsTrouble\": " + Q(stats.Trouble)
+ ", \"statsStatus\": " + Q(stats.On ? stats.Status : null) + ", \"notOurs\": " + B(stats.NotOurs)
+ ", \"remoteOn\": " + B(bot.Remote.On) + ", \"discord\": " + Q(Tag(s.DiscordLink))
+ ", \"discordTrouble\": " + Q(bot.Discord.Trouble) + "}\n";
lock (gate)
{
if (json == said) return;
string tmp = file + ".tmp";
File.WriteAllText(tmp, json);
if (File.Exists(file)) File.Replace(tmp, file, null);
else File.Move(tmp, file);
said = json;
}
}
catch (Exception) { }
};
bot.Stats.Changed += write;
bot.Discord.Changed += write;
new Thread(() => { while (true) { write(); Thread.Sleep(15000); } }) { IsBackground = true, Name = "link status" }.Start();
}
internal static string Tag(string link)
{
link = (link ?? "").Trim();
if (link.Length == 0) return "";
using (var sha = SHA256.Create())
{
var h = sha.ComputeHash(Encoding.UTF8.GetBytes(link));
var sb = new StringBuilder();
for (int i = 0; i < 8; i++) sb.Append(h[i].ToString("x2"));
return sb.ToString();
}
}
static string B(bool b) { return b ? "true" : "false"; }
static string Q(string t)
{
if (t == null) return "null";
var sb = new StringBuilder("\"");
foreach (char c in t)
{
if (c == '"' || c == '\\') sb.Append('\\').Append(c);
else if (c < ' ') sb.Append(' ');
else sb.Append(c);
}
return sb.Append('"').ToString();
}
}
}