Skip to content
This repository has been archived by the owner on Jul 30, 2020. It is now read-only.

Commit

Permalink
Merge pull request #2 from Necrobot-Private/master
Browse files Browse the repository at this point in the history
Update
  • Loading branch information
HokoriXIII committed Sep 14, 2016
2 parents d30812c + 42669c9 commit 1bc539d
Show file tree
Hide file tree
Showing 5 changed files with 214 additions and 31 deletions.
108 changes: 108 additions & 0 deletions PoGo.NecroBot.CLI/CommandLineUtility/Arguments.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#region using directives

using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

#endregion

namespace PoGo.NecroBot.CLI.CommandLineUtility
{
/// <summary>
/// Arguments class
/// </summary>
public class Arguments
{
// Variables
private readonly StringDictionary _parameters;

// Constructor
public Arguments(IEnumerable<string> args)
{
_parameters = new StringDictionary();
var spliter = new Regex(@"^-{1,2}|^/|=|:",
RegexOptions.IgnoreCase | RegexOptions.Compiled);

var remover = new Regex(@"^['""]?(.*?)['""]?$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);

string parameter = null;

// Valid parameters forms:
// {-,/,--}param{ ,=,:}((",')value(",'))
// Examples:
// -param1 value1 --param2 /param3:"Test-:-work"
// /param4=happy -param5 '--=nice=--'
foreach (var arg in args)
{
// Look for new parameters (-,/ or --) and a
// possible enclosed value (=,:)
var parts = spliter.Split(arg, 3);

switch (parts.Length)
{
// Found a value (for the last parameter
// found (space separator))
case 1:
if (parameter != null)
{
if (!_parameters.ContainsKey(parameter))
{
parts[0] =
remover.Replace(parts[0], "$1");

_parameters.Add(parameter, parts[0]);
}
parameter = null;
}
// else Error: no parameter waiting for a value (skipped)
break;

// Found just a parameter
case 2:
// The last parameter is still waiting.
// With no value, set it to true.
if (parameter != null)
{
if (!_parameters.ContainsKey(parameter))
_parameters.Add(parameter, "true");
}
parameter = parts[1];
break;

// Parameter with enclosed value
case 3:
// The last parameter is still waiting.
// With no value, set it to true.
if (parameter != null)
{
if (!_parameters.ContainsKey(parameter))
_parameters.Add(parameter, "true");
}

parameter = parts[1];

// Remove possible enclosing characters (",')
if (!_parameters.ContainsKey(parameter))
{
parts[2] = remover.Replace(parts[2], "$1");
_parameters.Add(parameter, parts[2]);
}

parameter = null;
break;
}
}
// In case a parameter is still waiting
if (parameter == null)
return;

if (!_parameters.ContainsKey(parameter))
_parameters.Add(parameter, "true");
}

// Retrieve a parameter value if it exists
// (overriding C# indexer property)
public string this[string param] => _parameters[param];
}
}
1 change: 1 addition & 0 deletions PoGo.NecroBot.CLI/PoGo.NecroBot.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="CommandLineUtility\Arguments.cs" />
<Compile Include="SniperEventListener.cs" />
<Compile Include="ConsoleEventListener.cs" />
<Compile Include="ConsoleLogger.cs" />
Expand Down
66 changes: 50 additions & 16 deletions PoGo.NecroBot.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Net;
using System.Reflection;
using System.Threading;
using PoGo.NecroBot.CLI.CommandLineUtility;
using PoGo.NecroBot.CLI.Resources;
using PoGo.NecroBot.Logic;
using PoGo.NecroBot.Logic.Common;
Expand All @@ -27,6 +28,8 @@ internal class Program
{
private static readonly ManualResetEvent QuitEvent = new ManualResetEvent(false);
private static string _subPath = "";
private static bool _enableJsonValidation = true;
private static bool _ignoreKillSwitch;

private static readonly Uri StrKillSwitchUri =
new Uri("https://raw.githubusercontent.com/Necrobot-Private/Necrobot2/master/KillSwitch.txt");
Expand All @@ -49,12 +52,42 @@ private static void Main(string[] args)
QuitEvent.Set();
eArgs.Cancel = true;
};
if (args.Length > 0)
_subPath = args[0];

// Command line parsing
var commandLine = new Arguments(args);
// Look for specific arguments values
if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
{
_subPath = commandLine["subpath"];
}
if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
{
switch (commandLine["jsonvalid"])
{
case "true":
_enableJsonValidation = true;
break;
case "false":
_enableJsonValidation = false;
break;
}
}
if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
{
switch (commandLine["killswitch"])
{
case "true":
_ignoreKillSwitch = false;
break;
case "false":
_ignoreKillSwitch = true;
break;
}
}

Logger.SetLogger(new ConsoleLogger(LogLevel.Service), _subPath);

if (CheckKillSwitch())
if (!_ignoreKillSwitch && CheckKillSwitch())
return;

var profilePath = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
Expand All @@ -69,7 +102,7 @@ private static void Main(string[] args)
// Load the settings from the config file
// If the current program is not the latest version, ensure we skip saving the file after loading
// This is to prevent saving the file with new options at their default values so we can check for differences
settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest(), true);
settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest(), _enableJsonValidation);
}
else
{
Expand All @@ -84,9 +117,9 @@ private static void Main(string[] args)
boolNeedsSetup = true;
}

if (args.Length > 1)
if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
{
var crds = args[1].Split(',');
var crds = commandLine["latlng"].Split(',');
try
{
var lat = double.Parse(crds[0]);
Expand Down Expand Up @@ -175,7 +208,7 @@ private static void Main(string[] args)
}
else
{
GlobalSettings.Load(_subPath, false, true);
GlobalSettings.Load(_subPath, false, _enableJsonValidation);

Logger.Write("Press a Key to continue...",
LogLevel.Warning);
Expand Down Expand Up @@ -247,7 +280,8 @@ private static void Main(string[] args)
if (settings.TelegramConfig.UseTelegramAPI)
_session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);

if (_session.LogicSettings.UseSnipeLocationServer || _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
if (_session.LogicSettings.UseSnipeLocationServer ||
_session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
SnipePokemonTask.AsyncStart(_session);

settings.CheckProxy(_session.Translation);
Expand Down Expand Up @@ -306,13 +340,13 @@ private static bool CheckKillSwitch()
{
Console.WriteLine(strReason + $"\n");

if (PromptForKillSwitchOverride())
{
// Override
Logger.Write("Overriding killswitch... you have been warned!", LogLevel.Warning);
return false;
}
if (PromptForKillSwitchOverride())
{
// Override
Logger.Write("Overriding killswitch... you have been warned!", LogLevel.Warning);
return false;
}

Logger.Write("The bot will now close, please press enter to continue", LogLevel.Error);
Console.ReadLine();
return true;
Expand All @@ -335,7 +369,7 @@ private static void UnhandledExceptionEventHandler(object obj, UnhandledExceptio
Logger.Write("Exception caught, writing LogBuffer.", force: true);
throw new Exception();
}

public static bool PromptForKillSwitchOverride()
{
Logger.Write("Do you want to override killswitch to bot at your own risk?", LogLevel.Warning);
Expand Down
35 changes: 28 additions & 7 deletions PoGo.NecroBot.Logic/Model/Settings/AuthSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,38 @@ public void Load(string path, bool boolSkipSave = false, bool validate = false)
// validate Json using JsonSchema
Logger.Write("Validating auth.json...");
var jsonObj = JObject.Parse(input);
IList<ValidationError> errors;
var valid = jsonObj.IsValid(JsonSchema, out errors);
if (!valid)
IList<ValidationError> errors = null;
bool valid;
try
{
valid = jsonObj.IsValid(JsonSchema, out errors);
}
catch (JSchemaException ex)
{
foreach (var error in errors)
if (ex.Message.Contains("commercial licence") || ex.Message.Contains("free-quota"))
{
Logger.Write(
"auth.json [Line: " + error.LineNumber + ", Position: " + error.LinePosition + "]: " +
error.Path + " " +
error.Message, LogLevel.Error);
"auth.json: " + ex.Message);
valid = false;
}
else
{
throw;
}
}
if (!valid)
{
if (errors != null)
{
foreach (var error in errors)
{
Logger.Write(
"auth.json [Line: " + error.LineNumber + ", Position: " + error.LinePosition + "]: " +
error.Path + " " +
error.Message, LogLevel.Error);
}
}

Logger.Write("Fix auth.json and restart NecroBot or press a key to ignore and continue...",
LogLevel.Warning);
Console.ReadKey();
Expand Down
35 changes: 27 additions & 8 deletions PoGo.NecroBot.Logic/Model/Settings/GlobalSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,37 @@ public static GlobalSettings Load(string path, bool boolSkipSave = false, bool v
{
Logger.Write("Validating config.json...");
var jsonObj = JObject.Parse(input);
IList<ValidationError> errors;
var valid = jsonObj.IsValid(JsonSchema, out errors);
if (!valid)
IList<ValidationError> errors = null;
bool valid;
try
{
valid = jsonObj.IsValid(JsonSchema, out errors);
}
catch (JSchemaException ex)
{
foreach (var error in errors)
if (ex.Message.Contains("commercial licence") || ex.Message.Contains("free-quota"))
{
Logger.Write(
"config.json [Line: " + error.LineNumber + ", Position: " + error.LinePosition +
"]: " +
error.Path + " " +
error.Message, LogLevel.Error);
"config.json: " + ex.Message);
valid = false;
}
else
{
throw;
}
}
if (!valid)
{
if (errors != null)
foreach (var error in errors)
{
Logger.Write(
"config.json [Line: " + error.LineNumber + ", Position: " + error.LinePosition +
"]: " +
error.Path + " " +
error.Message, LogLevel.Error);
}

Logger.Write(
"Fix config.json and restart NecroBot or press a key to ignore and continue...",
LogLevel.Warning);
Expand Down

0 comments on commit 1bc539d

Please sign in to comment.